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

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147
  1. (function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.JitsiMeetJS = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
  2. (function (__filename){
  3. /* global Strophe, $ */
  4. /* jshint -W101 */
  5. var logger = require("jitsi-meet-logger").getLogger(__filename);
  6. var RTC = require("./modules/RTC/RTC");
  7. var XMPPEvents = require("./service/xmpp/XMPPEvents");
  8. var RTCEvents = require("./service/RTC/RTCEvents");
  9. var EventEmitter = require("events");
  10. var JitsiConferenceEvents = require("./JitsiConferenceEvents");
  11. var JitsiParticipant = require("./JitsiParticipant");
  12. var Statistics = require("./modules/statistics/statistics");
  13. var JitsiDTMFManager = require('./modules/DTMF/JitsiDTMFManager');
  14. var JitsiTrackEvents = require("./JitsiTrackEvents");
  15. /**
  16. * Creates a JitsiConference object with the given name and properties.
  17. * Note: this constructor is not a part of the public API (objects should be
  18. * created using JitsiConnection.createConference).
  19. * @param options.config properties / settings related to the conference that will be created.
  20. * @param options.name the name of the conference
  21. * @param options.connection the JitsiConnection object for this JitsiConference.
  22. * @constructor
  23. */
  24. function JitsiConference(options) {
  25. if(!options.name || options.name.toLowerCase() !== options.name) {
  26. logger.error("Invalid conference name (no conference name passed or it"
  27. + "contains invalid characters like capital letters)!");
  28. return;
  29. }
  30. this.options = options;
  31. this.connection = this.options.connection;
  32. this.xmpp = this.connection.xmpp;
  33. this.eventEmitter = new EventEmitter();
  34. this.room = this.xmpp.createRoom(this.options.name, null, null, this.options.config);
  35. this.room.updateDeviceAvailability(RTC.getDeviceAvailability());
  36. this.rtc = new RTC(this.room, options);
  37. if(!RTC.options.disableAudioLevels)
  38. this.statistics = new Statistics();
  39. setupListeners(this);
  40. this.participants = {};
  41. this.lastActiveSpeaker = null;
  42. this.dtmfManager = null;
  43. this.somebodySupportsDTMF = false;
  44. }
  45. /**
  46. * Joins the conference.
  47. * @param password {string} the password
  48. */
  49. JitsiConference.prototype.join = function (password) {
  50. if(this.room)
  51. this.room.join(password, this.connection.tokenPassword);
  52. };
  53. /**
  54. * Leaves the conference.
  55. */
  56. JitsiConference.prototype.leave = function () {
  57. if(this.xmpp && this.room)
  58. this.xmpp.leaveRoom(this.room.roomjid);
  59. this.room = null;
  60. };
  61. /**
  62. * Returns the local tracks.
  63. */
  64. JitsiConference.prototype.getLocalTracks = function () {
  65. if (this.rtc) {
  66. return this.rtc.localStreams;
  67. } else {
  68. return [];
  69. }
  70. };
  71. /**
  72. * Attaches a handler for events(For example - "participant joined".) in the conference. All possible event are defined
  73. * in JitsiConferenceEvents.
  74. * @param eventId the event ID.
  75. * @param handler handler for the event.
  76. *
  77. * Note: consider adding eventing functionality by extending an EventEmitter impl, instead of rolling ourselves
  78. */
  79. JitsiConference.prototype.on = function (eventId, handler) {
  80. if(this.eventEmitter)
  81. this.eventEmitter.on(eventId, handler);
  82. };
  83. /**
  84. * Removes event listener
  85. * @param eventId the event ID.
  86. * @param [handler] optional, the specific handler to unbind
  87. *
  88. * Note: consider adding eventing functionality by extending an EventEmitter impl, instead of rolling ourselves
  89. */
  90. JitsiConference.prototype.off = function (eventId, handler) {
  91. if(this.eventEmitter)
  92. this.eventEmitter.removeListener(eventId, handler);
  93. };
  94. // Common aliases for event emitter
  95. JitsiConference.prototype.addEventListener = JitsiConference.prototype.on;
  96. JitsiConference.prototype.removeEventListener = JitsiConference.prototype.off;
  97. /**
  98. * Receives notifications from another participants for commands / custom events
  99. * (send by sendPresenceCommand method).
  100. * @param command {String} the name of the command
  101. * @param handler {Function} handler for the command
  102. */
  103. JitsiConference.prototype.addCommandListener = function (command, handler) {
  104. if(this.room)
  105. this.room.addPresenceListener(command, handler);
  106. };
  107. /**
  108. * Removes command listener
  109. * @param command {String} the name of the command
  110. */
  111. JitsiConference.prototype.removeCommandListener = function (command) {
  112. if(this.room)
  113. this.room.removePresenceListener(command);
  114. };
  115. /**
  116. * Sends text message to the other participants in the conference
  117. * @param message the text message.
  118. */
  119. JitsiConference.prototype.sendTextMessage = function (message) {
  120. if(this.room)
  121. this.room.sendMessage(message);
  122. };
  123. /**
  124. * Send presence command.
  125. * @param name the name of the command.
  126. * @param values Object with keys and values that will be send.
  127. **/
  128. JitsiConference.prototype.sendCommand = function (name, values) {
  129. if(this.room) {
  130. this.room.addToPresence(name, values);
  131. this.room.sendPresence();
  132. }
  133. };
  134. /**
  135. * Send presence command one time.
  136. * @param name the name of the command.
  137. * @param values Object with keys and values that will be send.
  138. **/
  139. JitsiConference.prototype.sendCommandOnce = function (name, values) {
  140. this.sendCommand(name, values);
  141. this.removeCommand(name);
  142. };
  143. /**
  144. * Send presence command.
  145. * @param name the name of the command.
  146. * @param values Object with keys and values that will be send.
  147. * @param persistent if false the command will be sent only one time
  148. **/
  149. JitsiConference.prototype.removeCommand = function (name) {
  150. if(this.room)
  151. this.room.removeFromPresence(name);
  152. };
  153. /**
  154. * Sets the display name for this conference.
  155. * @param name the display name to set
  156. */
  157. JitsiConference.prototype.setDisplayName = function(name) {
  158. if(this.room){
  159. this.room.addToPresence("nick", {attributes: {xmlns: 'http://jabber.org/protocol/nick'}, value: name});
  160. this.room.sendPresence();
  161. }
  162. };
  163. /**
  164. * Adds JitsiLocalTrack object to the conference.
  165. * @param track the JitsiLocalTrack object.
  166. */
  167. JitsiConference.prototype.addTrack = function (track) {
  168. this.room.addStream(track.getOriginalStream(), function () {
  169. this.rtc.addLocalStream(track);
  170. var muteHandler = this._fireMuteChangeEvent.bind(this, track);
  171. var stopHandler = this.removeTrack.bind(this, track);
  172. var audioLevelHandler = this._fireAudioLevelChangeEvent.bind(this);
  173. track.addEventListener(JitsiTrackEvents.TRACK_MUTE_CHANGED, muteHandler);
  174. track.addEventListener(JitsiTrackEvents.TRACK_STOPPED, stopHandler);
  175. track.addEventListener(JitsiTrackEvents.TRACK_AUDIO_LEVEL_CHANGED, audioLevelHandler);
  176. this.addEventListener(JitsiConferenceEvents.TRACK_REMOVED, function (someTrack) {
  177. if (someTrack !== track) {
  178. return;
  179. }
  180. track.removeEventListener(JitsiTrackEvents.TRACK_MUTE_CHANGED, muteHandler);
  181. track.removeEventListener(JitsiTrackEvents.TRACK_STOPPED, stopHandler);
  182. track.removeEventListener(JitsiTrackEvents.TRACK_AUDIO_LEVEL_CHANGED, audioLevelHandler);
  183. });
  184. this.eventEmitter.emit(JitsiConferenceEvents.TRACK_ADDED, track);
  185. }.bind(this));
  186. };
  187. /**
  188. * Fires TRACK_AUDIO_LEVEL_CHANGED change conference event.
  189. * @param audioLevel the audio level
  190. */
  191. JitsiConference.prototype._fireAudioLevelChangeEvent = function (audioLevel) {
  192. this.eventEmitter.emit(
  193. JitsiConferenceEvents.TRACK_AUDIO_LEVEL_CHANGED,
  194. this.myUserId(), audioLevel);
  195. };
  196. /**
  197. * Fires TRACK_MUTE_CHANGED change conference event.
  198. * @param track the JitsiTrack object related to the event.
  199. */
  200. JitsiConference.prototype._fireMuteChangeEvent = function (track) {
  201. this.eventEmitter.emit(JitsiConferenceEvents.TRACK_MUTE_CHANGED, track);
  202. };
  203. /**
  204. * Removes JitsiLocalTrack object to the conference.
  205. * @param track the JitsiLocalTrack object.
  206. */
  207. JitsiConference.prototype.removeTrack = function (track) {
  208. this.room.removeStream(track.getOriginalStream(), function(){
  209. this.rtc.removeLocalStream(track);
  210. this.eventEmitter.emit(JitsiConferenceEvents.TRACK_REMOVED, track);
  211. }.bind(this));
  212. };
  213. /**
  214. * Get role of the local user.
  215. * @returns {string} user role: 'moderator' or 'none'
  216. */
  217. JitsiConference.prototype.getRole = function () {
  218. return this.room.role;
  219. };
  220. /**
  221. * Check if local user is moderator.
  222. * @returns {boolean} true if local user is moderator, false otherwise.
  223. */
  224. JitsiConference.prototype.isModerator = function () {
  225. return this.room.isModerator();
  226. };
  227. /**
  228. * Elects the participant with the given id to be the selected participant or the speaker.
  229. * @param id the identifier of the participant
  230. */
  231. JitsiConference.prototype.selectParticipant = function(participantId) {
  232. if (this.rtc) {
  233. this.rtc.selectedEndpoint(participantId);
  234. }
  235. };
  236. /**
  237. *
  238. * @param id the identifier of the participant
  239. */
  240. JitsiConference.prototype.pinParticipant = function(participantId) {
  241. if (this.rtc) {
  242. this.rtc.pinEndpoint(participantId);
  243. }
  244. };
  245. /**
  246. * Returns the list of participants for this conference.
  247. * @return Array<JitsiParticipant> a list of participant identifiers containing all conference participants.
  248. */
  249. JitsiConference.prototype.getParticipants = function() {
  250. return Object.keys(this.participants).map(function (key) {
  251. return this.participants[key];
  252. }, this);
  253. };
  254. /**
  255. * @returns {JitsiParticipant} the participant in this conference with the specified id (or
  256. * undefined if there isn't one).
  257. * @param id the id of the participant.
  258. */
  259. JitsiConference.prototype.getParticipantById = function(id) {
  260. return this.participants[id];
  261. };
  262. JitsiConference.prototype.onMemberJoined = function (jid, email, nick) {
  263. var id = Strophe.getResourceFromJid(jid);
  264. var participant = new JitsiParticipant(id, this, nick);
  265. this.eventEmitter.emit(JitsiConferenceEvents.USER_JOINED, id);
  266. this.participants[id] = participant;
  267. this.connection.xmpp.connection.disco.info(
  268. jid, "node", function(iq) {
  269. participant._supportsDTMF = $(iq).find(
  270. '>query>feature[var="urn:xmpp:jingle:dtmf:0"]').length > 0;
  271. this.updateDTMFSupport();
  272. }.bind(this)
  273. );
  274. };
  275. JitsiConference.prototype.onMemberLeft = function (jid) {
  276. var id = Strophe.getResourceFromJid(jid);
  277. delete this.participants[id];
  278. this.eventEmitter.emit(JitsiConferenceEvents.USER_LEFT, id);
  279. };
  280. JitsiConference.prototype.onUserRoleChanged = function (jid, role) {
  281. var id = Strophe.getResourceFromJid(jid);
  282. var participant = this.getParticipantById(id);
  283. if (!participant) {
  284. return;
  285. }
  286. participant._role = role;
  287. this.eventEmitter.emit(JitsiConferenceEvents.USER_ROLE_CHANGED, id, role);
  288. };
  289. JitsiConference.prototype.onDisplayNameChanged = function (jid, displayName) {
  290. var id = Strophe.getResourceFromJid(jid);
  291. var participant = this.getParticipantById(id);
  292. if (!participant) {
  293. return;
  294. }
  295. participant._displayName = displayName;
  296. this.eventEmitter.emit(JitsiConferenceEvents.DISPLAY_NAME_CHANGED, id, displayName);
  297. };
  298. JitsiConference.prototype.onTrackAdded = function (track) {
  299. var id = track.getParticipantId();
  300. var participant = this.getParticipantById(id);
  301. if (!participant) {
  302. return;
  303. }
  304. // add track to JitsiParticipant
  305. participant._tracks.push(track);
  306. var emitter = this.eventEmitter;
  307. track.addEventListener(
  308. JitsiTrackEvents.TRACK_STOPPED,
  309. function () {
  310. // remove track from JitsiParticipant
  311. var pos = participant._tracks.indexOf(track);
  312. if (pos > -1) {
  313. participant._tracks.splice(pos, 1);
  314. }
  315. emitter.emit(JitsiConferenceEvents.TRACK_REMOVED, track);
  316. }
  317. );
  318. track.addEventListener(
  319. JitsiTrackEvents.TRACK_MUTE_CHANGED,
  320. function () {
  321. emitter.emit(JitsiConferenceEvents.TRACK_MUTE_CHANGED, track);
  322. }
  323. );
  324. track.addEventListener(
  325. JitsiTrackEvents.TRACK_AUDIO_LEVEL_CHANGED,
  326. function (audioLevel) {
  327. emitter.emit(JitsiConferenceEvents.TRACK_AUDIO_LEVEL_CHANGED, id, audioLevel);
  328. }
  329. );
  330. this.eventEmitter.emit(JitsiConferenceEvents.TRACK_ADDED, track);
  331. };
  332. JitsiConference.prototype.updateDTMFSupport = function () {
  333. var somebodySupportsDTMF = false;
  334. var participants = this.getParticipants();
  335. // check if at least 1 participant supports DTMF
  336. for (var i = 0; i < participants.length; i += 1) {
  337. if (participants[i].supportsDTMF()) {
  338. somebodySupportsDTMF = true;
  339. break;
  340. }
  341. }
  342. if (somebodySupportsDTMF !== this.somebodySupportsDTMF) {
  343. this.somebodySupportsDTMF = somebodySupportsDTMF;
  344. this.eventEmitter.emit(JitsiConferenceEvents.DTMF_SUPPORT_CHANGED, somebodySupportsDTMF);
  345. }
  346. };
  347. /**
  348. * Allows to check if there is at least one user in the conference
  349. * that supports DTMF.
  350. * @returns {boolean} true if somebody supports DTMF, false otherwise
  351. */
  352. JitsiConference.prototype.isDTMFSupported = function () {
  353. return this.somebodySupportsDTMF;
  354. };
  355. /**
  356. * Returns the local user's ID
  357. * @return {string} local user's ID
  358. */
  359. JitsiConference.prototype.myUserId = function () {
  360. return (this.room && this.room.myroomjid)? Strophe.getResourceFromJid(this.room.myroomjid) : null;
  361. };
  362. JitsiConference.prototype.sendTones = function (tones, duration, pause) {
  363. if (!this.dtmfManager) {
  364. var connection = this.connection.xmpp.connection.jingle.activecall.peerconnection;
  365. if (!connection) {
  366. logger.warn("cannot sendTones: no conneciton");
  367. return;
  368. }
  369. var tracks = this.getLocalTracks().filter(function (track) {
  370. return track.isAudioTrack();
  371. });
  372. if (!tracks.length) {
  373. logger.warn("cannot sendTones: no local audio stream");
  374. return;
  375. }
  376. this.dtmfManager = new JitsiDTMFManager(tracks[0], connection);
  377. }
  378. this.dtmfManager.sendTones(tones, duration, pause);
  379. };
  380. /**
  381. * Returns true if the recording is supproted and false if not.
  382. */
  383. JitsiConference.prototype.isRecordingSupported = function () {
  384. if(this.room)
  385. return this.room.isRecordingSupported();
  386. return false;
  387. };
  388. /**
  389. * Returns null if the recording is not supported, "on" if the recording started
  390. * and "off" if the recording is not started.
  391. */
  392. JitsiConference.prototype.getRecordingState = function () {
  393. if(this.room)
  394. return this.room.getRecordingState();
  395. return "off";
  396. }
  397. /**
  398. * Returns the url of the recorded video.
  399. */
  400. JitsiConference.prototype.getRecordingURL = function () {
  401. if(this.room)
  402. return this.room.getRecordingURL();
  403. return null;
  404. }
  405. /**
  406. * Starts/stops the recording
  407. * @param token a token for authentication.
  408. */
  409. JitsiConference.prototype.toggleRecording = function (token, followEntity) {
  410. if(this.room)
  411. return this.room.toggleRecording(token, followEntity);
  412. return new Promise(function(resolve, reject){
  413. reject(new Error("The conference is not created yet!"))});
  414. }
  415. /**
  416. * Dials a number.
  417. * @param number the number
  418. */
  419. JitsiConference.prototype.dial = function (number) {
  420. if(this.room)
  421. return this.room.dial(number);
  422. return new Promise(function(resolve, reject){
  423. reject(new Error("The conference is not created yet!"))});
  424. }
  425. /**
  426. * Hangup an existing call
  427. */
  428. JitsiConference.prototype.hangup = function () {
  429. if(this.room)
  430. return this.room.hangup();
  431. return new Promise(function(resolve, reject){
  432. reject(new Error("The conference is not created yet!"))});
  433. }
  434. /**
  435. * Returns the phone number for joining the conference.
  436. */
  437. JitsiConference.prototype.getPhoneNumber = function () {
  438. if(this.room)
  439. return this.room.getPhoneNumber();
  440. return null;
  441. }
  442. /**
  443. * Returns the pin for joining the conference with phone.
  444. */
  445. JitsiConference.prototype.getPhonePin = function () {
  446. if(this.room)
  447. return this.room.getPhonePin();
  448. return null;
  449. }
  450. /**
  451. * Returns the connection state for the current room. Its ice connection state
  452. * for its session.
  453. */
  454. JitsiConference.prototype.getConnectionState = function () {
  455. if(this.room)
  456. return this.room.getConnectionState();
  457. return null;
  458. }
  459. /**
  460. * Setups the listeners needed for the conference.
  461. * @param conference the conference
  462. */
  463. function setupListeners(conference) {
  464. conference.xmpp.addListener(XMPPEvents.CALL_INCOMING, function (event) {
  465. conference.rtc.onIncommingCall(event);
  466. if(conference.statistics)
  467. conference.statistics.startRemoteStats(event.peerconnection);
  468. });
  469. conference.room.addListener(XMPPEvents.REMOTE_STREAM_RECEIVED,
  470. function (data, sid, thessrc) {
  471. var track = conference.rtc.createRemoteStream(data, sid, thessrc);
  472. if (track) {
  473. conference.onTrackAdded(track);
  474. }
  475. }
  476. );
  477. conference.room.addListener(XMPPEvents.MUC_JOINED, function () {
  478. conference.eventEmitter.emit(JitsiConferenceEvents.CONFERENCE_JOINED);
  479. });
  480. // FIXME
  481. // conference.room.addListener(XMPPEvents.MUC_JOINED, function () {
  482. // conference.eventEmitter.emit(JitsiConferenceEvents.CONFERENCE_LEFT);
  483. // });
  484. conference.room.addListener(XMPPEvents.MUC_MEMBER_JOINED, conference.onMemberJoined.bind(conference));
  485. conference.room.addListener(XMPPEvents.MUC_MEMBER_LEFT, conference.onMemberLeft.bind(conference));
  486. conference.room.addListener(XMPPEvents.DISPLAY_NAME_CHANGED, conference.onDisplayNameChanged.bind(conference));
  487. conference.room.addListener(XMPPEvents.LOCAL_ROLE_CHANGED, function (role) {
  488. conference.eventEmitter.emit(JitsiConferenceEvents.USER_ROLE_CHANGED, conference.myUserId(), role);
  489. });
  490. conference.room.addListener(XMPPEvents.MUC_ROLE_CHANGED, conference.onUserRoleChanged.bind(conference));
  491. conference.room.addListener(XMPPEvents.CONNECTION_INTERRUPTED, function () {
  492. conference.eventEmitter.emit(JitsiConferenceEvents.CONNECTION_INTERRUPTED);
  493. });
  494. conference.room.addListener(XMPPEvents.RECORDING_STATE_CHANGED,
  495. function () {
  496. conference.eventEmitter.emit(
  497. JitsiConferenceEvents.RECORDING_STATE_CHANGED);
  498. });
  499. conference.room.addListener(XMPPEvents.PHONE_NUMBER_CHANGED, function () {
  500. conference.eventEmitter.emit(
  501. JitsiConferenceEvents.PHONE_NUMBER_CHANGED);
  502. });
  503. conference.room.addListener(XMPPEvents.CONNECTION_RESTORED, function () {
  504. conference.eventEmitter.emit(JitsiConferenceEvents.CONNECTION_RESTORED);
  505. });
  506. conference.room.addListener(XMPPEvents.CONFERENCE_SETUP_FAILED, function () {
  507. conference.eventEmitter.emit(JitsiConferenceEvents.SETUP_FAILED);
  508. });
  509. conference.rtc.addListener(RTCEvents.DOMINANTSPEAKER_CHANGED, function (id) {
  510. if(conference.lastActiveSpeaker !== id && conference.room) {
  511. conference.lastActiveSpeaker = id;
  512. conference.eventEmitter.emit(JitsiConferenceEvents.ACTIVE_SPEAKER_CHANGED, id);
  513. }
  514. });
  515. conference.rtc.addListener(RTCEvents.LASTN_CHANGED, function (oldValue, newValue) {
  516. conference.eventEmitter.emit(JitsiConferenceEvents.IN_LAST_N_CHANGED, oldValue, newValue);
  517. });
  518. conference.rtc.addListener(RTCEvents.LASTN_ENDPOINT_CHANGED,
  519. function (lastNEndpoints, endpointsEnteringLastN) {
  520. conference.eventEmitter.emit(JitsiConferenceEvents.LAST_N_ENDPOINTS_CHANGED,
  521. lastNEndpoints, endpointsEnteringLastN);
  522. });
  523. if(conference.statistics) {
  524. //FIXME: Maybe remove event should not be associated with the conference.
  525. conference.statistics.addAudioLevelListener(function (ssrc, level) {
  526. var userId = null;
  527. var jid = conference.room.getJidBySSRC(ssrc);
  528. if (!jid)
  529. return;
  530. conference.rtc.setAudioLevel(jid, level);
  531. });
  532. conference.xmpp.addListener(XMPPEvents.DISPOSE_CONFERENCE,
  533. function () {
  534. conference.statistics.dispose();
  535. });
  536. // FIXME: Maybe we should move this.
  537. // RTC.addListener(RTCEvents.AVAILABLE_DEVICES_CHANGED, function (devices) {
  538. // conference.room.updateDeviceAvailability(devices);
  539. // });
  540. }
  541. }
  542. module.exports = JitsiConference;
  543. }).call(this,"/JitsiConference.js")
  544. },{"./JitsiConferenceEvents":3,"./JitsiParticipant":8,"./JitsiTrackEvents":10,"./modules/DTMF/JitsiDTMFManager":11,"./modules/RTC/RTC":16,"./modules/statistics/statistics":24,"./service/RTC/RTCEvents":84,"./service/xmpp/XMPPEvents":91,"events":44,"jitsi-meet-logger":48}],2:[function(require,module,exports){
  545. /**
  546. * Enumeration with the errors for the conference.
  547. * @type {{string: string}}
  548. */
  549. var JitsiConferenceErrors = {
  550. /**
  551. * Indicates that a password is required in order to join the conference.
  552. */
  553. PASSWORD_REQUIRED: "conference.passwordRequired",
  554. /**
  555. * Indicates that a connection error occurred when trying to join a
  556. * conference.
  557. */
  558. CONNECTION_ERROR: "conference.connectionError",
  559. /**
  560. * Indicates that there is no available videobridge.
  561. */
  562. VIDEOBRIDGE_NOT_AVAILABLE: "conference.videobridgeNotAvailable"
  563. /**
  564. * Many more errors TBD here.
  565. */
  566. };
  567. module.exports = JitsiConferenceErrors;
  568. },{}],3:[function(require,module,exports){
  569. /**
  570. * Enumeration with the events for the conference.
  571. * @type {{string: string}}
  572. */
  573. var JitsiConferenceEvents = {
  574. /**
  575. * A new media track was added to the conference.
  576. */
  577. TRACK_ADDED: "conference.trackAdded",
  578. /**
  579. * The media track was removed from the conference.
  580. */
  581. TRACK_REMOVED: "conference.trackRemoved",
  582. /**
  583. * The active speaker was changed.
  584. */
  585. ACTIVE_SPEAKER_CHANGED: "conference.activeSpeaker",
  586. /**
  587. * A new user joinned the conference.
  588. */
  589. USER_JOINED: "conference.userJoined",
  590. /**
  591. * A user has left the conference.
  592. */
  593. USER_LEFT: "conference.userLeft",
  594. /**
  595. * User role changed.
  596. */
  597. USER_ROLE_CHANGED: "conference.roleChanged",
  598. /**
  599. * New text message was received.
  600. */
  601. MESSAGE_RECEIVED: "conference.messageReceived",
  602. /**
  603. * A user has changed it display name
  604. */
  605. DISPLAY_NAME_CHANGED: "conference.displayNameChanged",
  606. /**
  607. * A participant avatar has changed.
  608. */
  609. AVATAR_CHANGED: "conference.avatarChanged",
  610. /**
  611. * New connection statistics are received.
  612. */
  613. CONNECTION_STATS_RECEIVED: "conference.connectionStatsReceived",
  614. /**
  615. * The Last N set is changed.
  616. */
  617. LAST_N_ENDPOINTS_CHANGED: "conference.lastNEndpointsChanged",
  618. /**
  619. * You are included / excluded in somebody's last N set
  620. */
  621. IN_LAST_N_CHANGED: "conference.lastNEndpointsChanged",
  622. /**
  623. * A media track ( attached to the conference) mute status was changed.
  624. */
  625. TRACK_MUTE_CHANGED: "conference.trackMuteChanged",
  626. /**
  627. * Audio levels of a media track ( attached to the conference) was changed.
  628. */
  629. TRACK_AUDIO_LEVEL_CHANGED: "conference.audioLevelsChanged",
  630. /**
  631. * Indicates that the connection to the conference has been interrupted
  632. * for some reason.
  633. */
  634. CONNECTION_INTERRUPTED: "conference.connectionInterrupted",
  635. /**
  636. * Indicates that the connection to the conference has been restored.
  637. */
  638. CONNECTION_RESTORED: "conference.connectionRestored",
  639. /**
  640. * Indicates that the conference setup failed.
  641. */
  642. SETUP_FAILED: "conference.setup_failed",
  643. /**
  644. * Indicates that conference has been joined.
  645. */
  646. CONFERENCE_JOINED: "conference.joined",
  647. /**
  648. * Indicates that conference has been left.
  649. */
  650. CONFERENCE_LEFT: "conference.left",
  651. /**
  652. * Indicates that DTMF support changed.
  653. */
  654. DTMF_SUPPORT_CHANGED: "conference.dtmfSupportChanged",
  655. /**
  656. * Indicates that recording state changed.
  657. */
  658. RECORDING_STATE_CHANGED: "conference.recordingStateChanged",
  659. /**
  660. * Indicates that phone number changed.
  661. */
  662. PHONE_NUMBER_CHANGED: "conference.phoneNumberChanged"
  663. };
  664. module.exports = JitsiConferenceEvents;
  665. },{}],4:[function(require,module,exports){
  666. var JitsiConference = require("./JitsiConference");
  667. var XMPP = require("./modules/xmpp/xmpp");
  668. var RandomUtil = require("./modules/util/RandomUtil");
  669. /**
  670. * Utility method that generates user name based on random hex values.
  671. * Eg. 12345678-1234-1234-12345678
  672. * @returns {string}
  673. */
  674. function generateUserName() {
  675. return RandomUtil.random8digitsHex() + "-" + RandomUtil.random4digitsHex() + "-" +
  676. RandomUtil.random4digitsHex() + "-" + RandomUtil.random8digitsHex();
  677. }
  678. /**
  679. * Creates new connection object for the Jitsi Meet server side video conferencing service. Provides access to the
  680. * JitsiConference interface.
  681. * @param appID identification for the provider of Jitsi Meet video conferencing services.
  682. * @param tokenPassword secret generated by the provider of Jitsi Meet video conferencing services.
  683. * The token will be send to the provider from the Jitsi Meet server deployment for authorization of the current client.
  684. * The format is:
  685. * passwordToken = token + "_" + roomName + "_" + ts
  686. * See doc/tokens.md for more info on how tokens are generated.
  687. * @param options Object with properties / settings related to connection with the server.
  688. * @constructor
  689. */
  690. function JitsiConnection(appID, tokenPassword, options) {
  691. this.appID = appID;
  692. this.tokenPassword = tokenPassword;
  693. this.options = options;
  694. this.xmpp = new XMPP(options);
  695. this.conferences = {};
  696. }
  697. /**
  698. * Connect the client with the server.
  699. * @param options {object} connecting options (for example authentications parameters).
  700. */
  701. JitsiConnection.prototype.connect = function (options) {
  702. if(!options)
  703. options = {};
  704. // If we have token provided use it as a password and generate random username
  705. if (this.tokenPassword) {
  706. options.password = this.tokenPassword;
  707. if (!options.id) {
  708. options.id = generateUserName() + "@" + this.options.hosts.domain;
  709. }
  710. }
  711. this.xmpp.connect(options.id, options.password);
  712. }
  713. /**
  714. * Disconnect the client from the server.
  715. */
  716. JitsiConnection.prototype.disconnect = function () {
  717. this.xmpp.disconnect();
  718. }
  719. /**
  720. * This method allows renewal of the tokens if they are expiring.
  721. * @param token the new token.
  722. */
  723. JitsiConnection.prototype.setToken = function (token) {
  724. this.token = token;
  725. }
  726. /**
  727. * Creates and joins new conference.
  728. * @param name the name of the conference; if null - a generated name will be provided from the api
  729. * @param options Object with properties / settings related to the conference that will be created.
  730. * @returns {JitsiConference} returns the new conference object.
  731. */
  732. JitsiConnection.prototype.initJitsiConference = function (name, options) {
  733. this.conferences[name] = new JitsiConference({name: name, config: options, connection: this});
  734. return this.conferences[name];
  735. }
  736. /**
  737. * Subscribes the passed listener to the event.
  738. * @param event {JitsiConnectionEvents} the connection event.
  739. * @param listener {Function} the function that will receive the event
  740. */
  741. JitsiConnection.prototype.addEventListener = function (event, listener) {
  742. this.xmpp.addListener(event, listener);
  743. }
  744. /**
  745. * Unsubscribes the passed handler.
  746. * @param event {JitsiConnectionEvents} the connection event.
  747. * @param listener {Function} the function that will receive the event
  748. */
  749. JitsiConnection.prototype.removeEventListener = function (event, listener) {
  750. this.xmpp.removeListener(event, listener);
  751. }
  752. module.exports = JitsiConnection;
  753. },{"./JitsiConference":1,"./modules/util/RandomUtil":25,"./modules/xmpp/xmpp":42}],5:[function(require,module,exports){
  754. /**
  755. * Enumeration with the errors for the connection.
  756. * @type {{string: string}}
  757. */
  758. var JitsiConnectionErrors = {
  759. /**
  760. * Indicates that a password is required in order to join the conference.
  761. */
  762. PASSWORD_REQUIRED: "connection.passwordRequired",
  763. /**
  764. * Indicates that a connection error occurred when trying to join a
  765. * conference.
  766. */
  767. CONNECTION_ERROR: "connection.connectionError",
  768. /**
  769. * Not specified errors.
  770. */
  771. OTHER_ERROR: "connection.otherError"
  772. };
  773. module.exports = JitsiConnectionErrors;
  774. },{}],6:[function(require,module,exports){
  775. /**
  776. * Enumeration with the events for the connection.
  777. * @type {{string: string}}
  778. */
  779. var JitsiConnnectionEvents = {
  780. /**
  781. * Indicates that the connection has been failed for some reason.
  782. */
  783. CONNECTION_FAILED: "connection.connectionFailed",
  784. /**
  785. * Indicates that the connection has been established.
  786. */
  787. CONNECTION_ESTABLISHED: "connection.connectionEstablished",
  788. /**
  789. * Indicates that the connection has been disconnected.
  790. */
  791. CONNECTION_DISCONNECTED: "connection.connectionDisconnected",
  792. /**
  793. * Indicates that the perfomed action cannot be executed because the
  794. * connection is not in the correct state(connected, disconnected, etc.)
  795. */
  796. WRONG_STATE: "connection.wrongState"
  797. };
  798. module.exports = JitsiConnnectionEvents;
  799. },{}],7:[function(require,module,exports){
  800. var JitsiConnection = require("./JitsiConnection");
  801. var JitsiConferenceEvents = require("./JitsiConferenceEvents");
  802. var JitsiConnectionEvents = require("./JitsiConnectionEvents");
  803. var JitsiConnectionErrors = require("./JitsiConnectionErrors");
  804. var JitsiConferenceErrors = require("./JitsiConferenceErrors");
  805. var JitsiTrackEvents = require("./JitsiTrackEvents");
  806. var JitsiTrackErrors = require("./JitsiTrackErrors");
  807. var Logger = require("jitsi-meet-logger");
  808. var RTC = require("./modules/RTC/RTC");
  809. var Statistics = require("./modules/statistics/statistics");
  810. /**
  811. * Namespace for the interface of Jitsi Meet Library.
  812. */
  813. var LibJitsiMeet = {
  814. JitsiConnection: JitsiConnection,
  815. events: {
  816. conference: JitsiConferenceEvents,
  817. connection: JitsiConnectionEvents,
  818. track: JitsiTrackEvents
  819. },
  820. errors: {
  821. conference: JitsiConferenceErrors,
  822. connection: JitsiConnectionErrors,
  823. track: JitsiTrackErrors
  824. },
  825. logLevels: Logger.levels,
  826. init: function (options) {
  827. return RTC.init(options || {});
  828. },
  829. setLogLevel: function (level) {
  830. Logger.setLogLevel(level);
  831. },
  832. /**
  833. * Creates the media tracks and returns them trough the callback.
  834. * @param options Object with properties / settings specifying the tracks which should be created.
  835. * should be created or some additional configurations about resolution for example.
  836. * @param {Array} options.devices the devices that will be requested
  837. * @param {string} options.resolution resolution constraints
  838. * @param {bool} options.dontCreateJitsiTrack if <tt>true</tt> objects with the following structure {stream: the Media Stream,
  839. * type: "audio" or "video", videoType: "camera" or "desktop"}
  840. * will be returned trough the Promise, otherwise JitsiTrack objects will be returned.
  841. * @param {string} options.cameraDeviceId
  842. * @param {string} options.micDeviceId
  843. * @returns {Promise.<{Array.<JitsiTrack>}, JitsiConferenceError>}
  844. * A promise that returns an array of created JitsiTracks if resolved,
  845. * or a JitsiConferenceError if rejected.
  846. */
  847. createLocalTracks: function (options) {
  848. return RTC.obtainAudioAndVideoPermissions(options || {}).then(
  849. function(tracks) {
  850. if(!RTC.options.disableAudioLevels)
  851. for(var i = 0; i < tracks.length; i++) {
  852. var track = tracks[i];
  853. var mStream = track.getOriginalStream();
  854. if(track.getType() === "audio"){
  855. Statistics.startLocalStats(mStream,
  856. track.setAudioLevel.bind(track));
  857. track.addEventListener(
  858. JitsiTrackEvents.TRACK_STOPPED,
  859. function(){
  860. Statistics.stopLocalStats(mStream);
  861. });
  862. }
  863. }
  864. return tracks;
  865. });
  866. },
  867. isDeviceListAvailable: function () {
  868. return RTC.isDeviceListAvailable();
  869. },
  870. enumerateDevices: function (callback) {
  871. RTC.enumerateDevices(callback);
  872. }
  873. };
  874. require("es6-promise").polyfill()
  875. //Setups the promise object.
  876. window.Promise = window.Promise || require("es6-promise").Promise;
  877. module.exports = LibJitsiMeet;
  878. },{"./JitsiConferenceErrors":2,"./JitsiConferenceEvents":3,"./JitsiConnection":4,"./JitsiConnectionErrors":5,"./JitsiConnectionEvents":6,"./JitsiTrackErrors":9,"./JitsiTrackEvents":10,"./modules/RTC/RTC":16,"./modules/statistics/statistics":24,"es6-promise":46,"jitsi-meet-logger":48}],8:[function(require,module,exports){
  879. /**
  880. * Represents a participant in (a member of) a conference.
  881. */
  882. function JitsiParticipant(id, conference, displayName){
  883. this._id = id;
  884. this._conference = conference;
  885. this._displayName = displayName;
  886. this._supportsDTMF = false;
  887. this._tracks = [];
  888. this._role = 'none';
  889. }
  890. /**
  891. * @returns {JitsiConference} The conference that this participant belongs to.
  892. */
  893. JitsiParticipant.prototype.getConference = function() {
  894. return this._conference;
  895. };
  896. /**
  897. * @returns {Array.<JitsiTrack>} The list of media tracks for this participant.
  898. */
  899. JitsiParticipant.prototype.getTracks = function() {
  900. return this._tracks;
  901. };
  902. /**
  903. * @returns {String} The ID (i.e. JID) of this participant.
  904. */
  905. JitsiParticipant.prototype.getId = function() {
  906. return this._id;
  907. };
  908. /**
  909. * @returns {String} The human-readable display name of this participant.
  910. */
  911. JitsiParticipant.prototype.getDisplayName = function() {
  912. return this._displayName;
  913. };
  914. /**
  915. * @returns {Boolean} Whether this participant is a moderator or not.
  916. */
  917. JitsiParticipant.prototype.isModerator = function() {
  918. return this._role === 'moderator';
  919. };
  920. // Gets a link to an etherpad instance advertised by the participant?
  921. //JitsiParticipant.prototype.getEtherpad = function() {
  922. //
  923. //}
  924. /*
  925. * @returns {Boolean} Whether this participant has muted their audio.
  926. */
  927. JitsiParticipant.prototype.isAudioMuted = function() {
  928. return this.getTracks().reduce(function (track, isAudioMuted) {
  929. return isAudioMuted && (track.isVideoTrack() || track.isMuted());
  930. }, true);
  931. };
  932. /*
  933. * @returns {Boolean} Whether this participant has muted their video.
  934. */
  935. JitsiParticipant.prototype.isVideoMuted = function() {
  936. return this.getTracks().reduce(function (track, isVideoMuted) {
  937. return isVideoMuted && (track.isAudioTrack() || track.isMuted());
  938. }, true);
  939. };
  940. /*
  941. * @returns {???} The latest statistics reported by this participant (i.e. info used to populate the GSM bars)
  942. * TODO: do we expose this or handle it internally?
  943. */
  944. JitsiParticipant.prototype.getLatestStats = function() {
  945. };
  946. /**
  947. * @returns {String} The role of this participant.
  948. */
  949. JitsiParticipant.prototype.getRole = function() {
  950. return this._role;
  951. };
  952. /*
  953. * @returns {Boolean} Whether this participant is the conference focus (i.e. jicofo).
  954. */
  955. JitsiParticipant.prototype.isFocus = function() {
  956. };
  957. /*
  958. * @returns {Boolean} Whether this participant is a conference recorder (i.e. jirecon).
  959. */
  960. JitsiParticipant.prototype.isRecorder = function() {
  961. };
  962. /*
  963. * @returns {Boolean} Whether this participant is a SIP gateway (i.e. jigasi).
  964. */
  965. JitsiParticipant.prototype.isSipGateway = function() {
  966. };
  967. /**
  968. * @returns {Boolean} Whether this participant is currently sharing their screen.
  969. */
  970. JitsiParticipant.prototype.isScreenSharing = function() {
  971. };
  972. /**
  973. * @returns {String} The user agent of this participant (i.e. browser userAgent string).
  974. */
  975. JitsiParticipant.prototype.getUserAgent = function() {
  976. };
  977. /**
  978. * Kicks the participant from the conference (requires certain privileges).
  979. */
  980. JitsiParticipant.prototype.kick = function() {
  981. };
  982. /**
  983. * Asks this participant to mute themselves.
  984. */
  985. JitsiParticipant.prototype.askToMute = function() {
  986. };
  987. JitsiParticipant.prototype.supportsDTMF = function () {
  988. return this._supportsDTMF;
  989. };
  990. module.exports = JitsiParticipant;
  991. },{}],9:[function(require,module,exports){
  992. module.exports = {
  993. /**
  994. * Returns JitsiTrackErrors based on the error object passed by GUM
  995. * @param error the error
  996. * @param {Object} options the options object given to GUM.
  997. */
  998. parseError: function (error, options) {
  999. options = options || {};
  1000. if (typeof error == "object" && error.constraintName && error.name
  1001. && (error.name == "ConstraintNotSatisfiedError" ||
  1002. error.name == "OverconstrainedError") &&
  1003. (error.constraintName == "minWidth" ||
  1004. error.constraintName == "maxWidth" ||
  1005. error.constraintName == "minHeight" ||
  1006. error.constraintName == "maxHeight") &&
  1007. options.devices.indexOf("video") !== -1) {
  1008. return this.UNSUPPORTED_RESOLUTION;
  1009. } else {
  1010. return this.GENERAL;
  1011. }
  1012. },
  1013. UNSUPPORTED_RESOLUTION: "gum.unsupported_resolution",
  1014. GENERAL: "gum.general"
  1015. };
  1016. },{}],10:[function(require,module,exports){
  1017. var JitsiTrackEvents = {
  1018. /**
  1019. * A media track mute status was changed.
  1020. */
  1021. TRACK_MUTE_CHANGED: "track.trackMuteChanged",
  1022. /**
  1023. * Audio levels of a this track was changed.
  1024. */
  1025. TRACK_AUDIO_LEVEL_CHANGED: "track.audioLevelsChanged",
  1026. /**
  1027. * The media track was removed to the conference.
  1028. */
  1029. TRACK_STOPPED: "track.stopped"
  1030. };
  1031. module.exports = JitsiTrackEvents;
  1032. },{}],11:[function(require,module,exports){
  1033. (function (__filename){
  1034. var logger = require("jitsi-meet-logger").getLogger(__filename);
  1035. function JitsiDTMFManager (localAudio, peerConnection) {
  1036. var tracks = localAudio._getTracks();
  1037. if (!tracks.length) {
  1038. throw new Error("Failed to initialize DTMFSender: no audio track.");
  1039. }
  1040. this.dtmfSender = peerConnection.peerconnection.createDTMFSender(tracks[0]);
  1041. logger.debug("Initialized DTMFSender");
  1042. }
  1043. JitsiDTMFManager.prototype.sendTones = function (tones, duration, pause) {
  1044. this.dtmfSender.insertDTMF(tones, (duration || 200), (pause || 200));
  1045. };
  1046. }).call(this,"/modules/DTMF/JitsiDTMFManager.js")
  1047. },{"jitsi-meet-logger":48}],12:[function(require,module,exports){
  1048. (function (__filename){
  1049. /* global config, APP, Strophe */
  1050. // cache datachannels to avoid garbage collection
  1051. // https://code.google.com/p/chromium/issues/detail?id=405545
  1052. var logger = require("jitsi-meet-logger").getLogger(__filename);
  1053. var RTCEvents = require("../../service/RTC/RTCEvents");
  1054. /**
  1055. * Binds "ondatachannel" event listener to given PeerConnection instance.
  1056. * @param peerConnection WebRTC peer connection instance.
  1057. */
  1058. function DataChannels(peerConnection, emitter) {
  1059. peerConnection.ondatachannel = this.onDataChannel.bind(this);
  1060. this.eventEmitter = emitter;
  1061. this._dataChannels = [];
  1062. // Sample code for opening new data channel from Jitsi Meet to the bridge.
  1063. // Although it's not a requirement to open separate channels from both bridge
  1064. // and peer as single channel can be used for sending and receiving data.
  1065. // So either channel opened by the bridge or the one opened here is enough
  1066. // for communication with the bridge.
  1067. /*var dataChannelOptions =
  1068. {
  1069. reliable: true
  1070. };
  1071. var dataChannel
  1072. = peerConnection.createDataChannel("myChannel", dataChannelOptions);
  1073. // Can be used only when is in open state
  1074. dataChannel.onopen = function ()
  1075. {
  1076. dataChannel.send("My channel !!!");
  1077. };
  1078. dataChannel.onmessage = function (event)
  1079. {
  1080. var msgData = event.data;
  1081. logger.info("Got My Data Channel Message:", msgData, dataChannel);
  1082. };*/
  1083. };
  1084. /**
  1085. * Callback triggered by PeerConnection when new data channel is opened
  1086. * on the bridge.
  1087. * @param event the event info object.
  1088. */
  1089. DataChannels.prototype.onDataChannel = function (event) {
  1090. var dataChannel = event.channel;
  1091. var self = this;
  1092. dataChannel.onopen = function () {
  1093. logger.info("Data channel opened by the Videobridge!", dataChannel);
  1094. // Code sample for sending string and/or binary data
  1095. // Sends String message to the bridge
  1096. //dataChannel.send("Hello bridge!");
  1097. // Sends 12 bytes binary message to the bridge
  1098. //dataChannel.send(new ArrayBuffer(12));
  1099. self.eventEmitter.emit(RTCEvents.DATA_CHANNEL_OPEN);
  1100. };
  1101. dataChannel.onerror = function (error) {
  1102. logger.error("Data Channel Error:", error, dataChannel);
  1103. };
  1104. dataChannel.onmessage = function (event) {
  1105. var data = event.data;
  1106. // JSON
  1107. var obj;
  1108. try {
  1109. obj = JSON.parse(data);
  1110. }
  1111. catch (e) {
  1112. logger.error(
  1113. "Failed to parse data channel message as JSON: ",
  1114. data,
  1115. dataChannel);
  1116. }
  1117. if (('undefined' !== typeof(obj)) && (null !== obj)) {
  1118. var colibriClass = obj.colibriClass;
  1119. if ("DominantSpeakerEndpointChangeEvent" === colibriClass) {
  1120. // Endpoint ID from the Videobridge.
  1121. var dominantSpeakerEndpoint = obj.dominantSpeakerEndpoint;
  1122. logger.info(
  1123. "Data channel new dominant speaker event: ",
  1124. dominantSpeakerEndpoint);
  1125. self.eventEmitter.emit(RTCEvents.DOMINANTSPEAKER_CHANGED, dominantSpeakerEndpoint);
  1126. }
  1127. else if ("InLastNChangeEvent" === colibriClass) {
  1128. var oldValue = obj.oldValue;
  1129. var newValue = obj.newValue;
  1130. // Make sure that oldValue and newValue are of type boolean.
  1131. var type;
  1132. if ((type = typeof oldValue) !== 'boolean') {
  1133. if (type === 'string') {
  1134. oldValue = (oldValue == "true");
  1135. } else {
  1136. oldValue = new Boolean(oldValue).valueOf();
  1137. }
  1138. }
  1139. if ((type = typeof newValue) !== 'boolean') {
  1140. if (type === 'string') {
  1141. newValue = (newValue == "true");
  1142. } else {
  1143. newValue = new Boolean(newValue).valueOf();
  1144. }
  1145. }
  1146. self.eventEmitter.emit(RTCEvents.LASTN_CHANGED, oldValue, newValue);
  1147. }
  1148. else if ("LastNEndpointsChangeEvent" === colibriClass) {
  1149. // The new/latest list of last-n endpoint IDs.
  1150. var lastNEndpoints = obj.lastNEndpoints;
  1151. // The list of endpoint IDs which are entering the list of
  1152. // last-n at this time i.e. were not in the old list of last-n
  1153. // endpoint IDs.
  1154. var endpointsEnteringLastN = obj.endpointsEnteringLastN;
  1155. logger.info(
  1156. "Data channel new last-n event: ",
  1157. lastNEndpoints, endpointsEnteringLastN, obj);
  1158. self.eventEmitter.emit(RTCEvents.LASTN_ENDPOINT_CHANGED,
  1159. lastNEndpoints, endpointsEnteringLastN, obj);
  1160. }
  1161. else {
  1162. logger.debug("Data channel JSON-formatted message: ", obj);
  1163. // The received message appears to be appropriately formatted
  1164. // (i.e. is a JSON object which assigns a value to the mandatory
  1165. // property colibriClass) so don't just swallow it, expose it to
  1166. // public consumption.
  1167. self.eventEmitter.emit("rtc.datachannel." + colibriClass, obj);
  1168. }
  1169. }
  1170. };
  1171. dataChannel.onclose = function () {
  1172. logger.info("The Data Channel closed", dataChannel);
  1173. var idx = self._dataChannels.indexOf(dataChannel);
  1174. if (idx > -1)
  1175. self._dataChannels = self._dataChannels.splice(idx, 1);
  1176. };
  1177. this._dataChannels.push(dataChannel);
  1178. };
  1179. DataChannels.prototype.handleSelectedEndpointEvent = function (userResource) {
  1180. this._onXXXEndpointChanged("selected", userResource);
  1181. }
  1182. DataChannels.prototype.handlePinnedEndpointEvent = function (userResource) {
  1183. this._onXXXEndpointChanged("pinnned", userResource);
  1184. }
  1185. /**
  1186. * Notifies Videobridge about a change in the value of a specific
  1187. * endpoint-related property such as selected endpoint and pinnned endpoint.
  1188. *
  1189. * @param xxx the name of the endpoint-related property whose value changed
  1190. * @param userResource the new value of the endpoint-related property after the
  1191. * change
  1192. */
  1193. DataChannels.prototype._onXXXEndpointChanged = function (xxx, userResource) {
  1194. // Derive the correct words from xxx such as selected and Selected, pinned
  1195. // and Pinned.
  1196. var head = xxx.charAt(0);
  1197. var tail = xxx.substring(1);
  1198. var lower = head.toLowerCase() + tail;
  1199. var upper = head.toUpperCase() + tail;
  1200. // Notify Videobridge about the specified endpoint change.
  1201. console.log(lower + ' endpoint changed: ', userResource);
  1202. this._some(function (dataChannel) {
  1203. if (dataChannel.readyState == 'open') {
  1204. console.log(
  1205. 'sending ' + lower
  1206. + ' endpoint changed notification to the bridge: ',
  1207. userResource);
  1208. var jsonObject = {};
  1209. jsonObject.colibriClass = (upper + 'EndpointChangedEvent');
  1210. jsonObject[lower + "Endpoint"]
  1211. = (userResource ? userResource : null);
  1212. dataChannel.send(JSON.stringify(jsonObject));
  1213. return true;
  1214. }
  1215. });
  1216. }
  1217. DataChannels.prototype._some = function (callback, thisArg) {
  1218. var dataChannels = this._dataChannels;
  1219. if (dataChannels && dataChannels.length !== 0) {
  1220. if (thisArg)
  1221. return dataChannels.some(callback, thisArg);
  1222. else
  1223. return dataChannels.some(callback);
  1224. } else {
  1225. return false;
  1226. }
  1227. }
  1228. module.exports = DataChannels;
  1229. }).call(this,"/modules/RTC/DataChannels.js")
  1230. },{"../../service/RTC/RTCEvents":84,"jitsi-meet-logger":48}],13:[function(require,module,exports){
  1231. var JitsiTrack = require("./JitsiTrack");
  1232. var RTCBrowserType = require("./RTCBrowserType");
  1233. var JitsiTrackEvents = require('../../JitsiTrackEvents');
  1234. var RTC = require("./RTCUtils");
  1235. /**
  1236. * Represents a single media track (either audio or video).
  1237. * @constructor
  1238. */
  1239. function JitsiLocalTrack(stream, videoType,
  1240. resolution)
  1241. {
  1242. this.videoType = videoType;
  1243. this.dontFireRemoveEvent = false;
  1244. this.resolution = resolution;
  1245. this.startMuted = false;
  1246. var self = this;
  1247. JitsiTrack.call(this, null, stream,
  1248. function () {
  1249. if(!this.dontFireRemoveEvent)
  1250. this.eventEmitter.emit(
  1251. JitsiTrackEvents.TRACK_STOPPED);
  1252. this.dontFireRemoveEvent = false;
  1253. }.bind(this));
  1254. }
  1255. JitsiLocalTrack.prototype = Object.create(JitsiTrack.prototype);
  1256. JitsiLocalTrack.prototype.constructor = JitsiLocalTrack;
  1257. /**
  1258. * Mutes / unmutes the track.
  1259. * @param mute {boolean} if true the track will be muted. Otherwise the track will be unmuted.
  1260. */
  1261. JitsiLocalTrack.prototype._setMute = function (mute) {
  1262. if(!this.rtc) {
  1263. this.startMuted = mute;
  1264. return;
  1265. }
  1266. var isAudio = this.type === JitsiTrack.AUDIO;
  1267. this.dontFireRemoveEvent = false;
  1268. if ((window.location.protocol != "https:") ||
  1269. (isAudio) || this.videoType === "desktop" ||
  1270. // FIXME FF does not support 'removeStream' method used to mute
  1271. RTCBrowserType.isFirefox()) {
  1272. var tracks = this._getTracks();
  1273. for (var idx = 0; idx < tracks.length; idx++) {
  1274. tracks[idx].enabled = !mute;
  1275. }
  1276. if(isAudio)
  1277. this.rtc.room.setAudioMute(mute);
  1278. else
  1279. this.rtc.room.setVideoMute(mute);
  1280. this.eventEmitter.emit(JitsiTrackEvents.TRACK_MUTE_CHANGED);
  1281. } else {
  1282. if (mute) {
  1283. this.dontFireRemoveEvent = true;
  1284. this.rtc.room.removeStream(this.stream, function () {});
  1285. RTC.stopMediaStream(this.stream);
  1286. if(isAudio)
  1287. this.rtc.room.setAudioMute(mute);
  1288. else
  1289. this.rtc.room.setVideoMute(mute);
  1290. this.stream = null;
  1291. this.eventEmitter.emit(JitsiTrackEvents.TRACK_MUTE_CHANGED);
  1292. //FIXME: Maybe here we should set the SRC for the containers to something
  1293. } else {
  1294. var self = this;
  1295. RTC.obtainAudioAndVideoPermissions({
  1296. devices: (isAudio ? ["audio"] : ["video"]),
  1297. resolution: self.resolution})
  1298. .then(function (streams) {
  1299. var stream = null;
  1300. for(var i = 0; i < streams.length; i++) {
  1301. stream = streams[i];
  1302. if(stream.type === self.type) {
  1303. self.stream = stream.stream;
  1304. self.videoType = stream.videoType;
  1305. break;
  1306. }
  1307. }
  1308. if(!stream)
  1309. return;
  1310. for(var i = 0; i < self.containers.length; i++)
  1311. {
  1312. RTC.attachMediaStream(self.containers[i], self.stream);
  1313. }
  1314. self.rtc.room.addStream(stream.stream,
  1315. function () {
  1316. if(isAudio)
  1317. self.rtc.room.setAudioMute(mute);
  1318. else
  1319. self.rtc.room.setVideoMute(mute);
  1320. self.eventEmitter.emit(
  1321. JitsiTrackEvents.TRACK_MUTE_CHANGED);
  1322. });
  1323. });
  1324. }
  1325. }
  1326. }
  1327. /**
  1328. * Stops sending the media track. And removes it from the HTML.
  1329. * NOTE: Works for local tracks only.
  1330. */
  1331. JitsiLocalTrack.prototype.stop = function () {
  1332. if(!this.stream)
  1333. return;
  1334. if(this.rtc)
  1335. this.rtc.room.removeStream(this.stream, function () {});
  1336. RTC.stopMediaStream(this.stream);
  1337. this.detach();
  1338. }
  1339. /**
  1340. * Returns <tt>true</tt> - if the stream is muted
  1341. * and <tt>false</tt> otherwise.
  1342. * @returns {boolean} <tt>true</tt> - if the stream is muted
  1343. * and <tt>false</tt> otherwise.
  1344. */
  1345. JitsiLocalTrack.prototype.isMuted = function () {
  1346. if (!this.stream)
  1347. return true;
  1348. var tracks = [];
  1349. var isAudio = this.type === JitsiTrack.AUDIO;
  1350. if (isAudio) {
  1351. tracks = this.stream.getAudioTracks();
  1352. } else {
  1353. if (!this.isActive())
  1354. return true;
  1355. tracks = this.stream.getVideoTracks();
  1356. }
  1357. for (var idx = 0; idx < tracks.length; idx++) {
  1358. if(tracks[idx].enabled)
  1359. return false;
  1360. }
  1361. return true;
  1362. };
  1363. /**
  1364. * Private method. Updates rtc property of the track.
  1365. * @param rtc the rtc instance.
  1366. */
  1367. JitsiLocalTrack.prototype._setRTC = function (rtc) {
  1368. this.rtc = rtc;
  1369. };
  1370. /**
  1371. * Return true;
  1372. */
  1373. JitsiLocalTrack.prototype.isLocal = function () {
  1374. return true;
  1375. }
  1376. module.exports = JitsiLocalTrack;
  1377. },{"../../JitsiTrackEvents":10,"./JitsiTrack":15,"./RTCBrowserType":17,"./RTCUtils":18}],14:[function(require,module,exports){
  1378. var JitsiTrack = require("./JitsiTrack");
  1379. var JitsiTrackEvents = require("../../JitsiTrackEvents");
  1380. /**
  1381. * Represents a single media track (either audio or video).
  1382. * @param RTC the rtc instance.
  1383. * @param data object with the stream and some details about it(participant id, video type, etc.)
  1384. * @param sid sid for the Media Stream
  1385. * @param ssrc ssrc for the Media Stream
  1386. * @param eventEmitter the event emitter
  1387. * @constructor
  1388. */
  1389. function JitsiRemoteTrack(RTC, data, sid, ssrc) {
  1390. JitsiTrack.call(this, RTC, data.stream,
  1391. function () {
  1392. this.eventEmitter.emit(JitsiTrackEvents.TRACK_STOPPED);
  1393. }.bind(this));
  1394. this.rtc = RTC;
  1395. this.sid = sid;
  1396. this.stream = data.stream;
  1397. this.peerjid = data.peerjid;
  1398. this.videoType = data.videoType;
  1399. this.ssrc = ssrc;
  1400. this.muted = false;
  1401. if((this.type === JitsiTrack.AUDIO && data.audiomuted)
  1402. || (this.type === JitsiTrack.VIDEO && data.videomuted)) {
  1403. this.muted = true;
  1404. }
  1405. }
  1406. JitsiRemoteTrack.prototype = Object.create(JitsiTrack.prototype);
  1407. JitsiRemoteTrack.prototype.constructor = JitsiRemoteTrack;
  1408. /**
  1409. * Sets current muted status and fires an events for the change.
  1410. * @param value the muted status.
  1411. */
  1412. JitsiRemoteTrack.prototype.setMute = function (value) {
  1413. this.stream.muted = value;
  1414. this.muted = value;
  1415. this.eventEmitter.emit(JitsiTrackEvents.TRACK_MUTE_CHANGED);
  1416. };
  1417. /**
  1418. * Returns the current muted status of the track.
  1419. * @returns {boolean|*|JitsiRemoteTrack.muted} <tt>true</tt> if the track is muted and <tt>false</tt> otherwise.
  1420. */
  1421. JitsiRemoteTrack.prototype.isMuted = function () {
  1422. return this.muted;
  1423. }
  1424. /**
  1425. * Returns the participant id which owns the track.
  1426. * @returns {string} the id of the participants.
  1427. */
  1428. JitsiRemoteTrack.prototype.getParticipantId = function() {
  1429. return Strophe.getResourceFromJid(this.peerjid);
  1430. };
  1431. /**
  1432. * Return false;
  1433. */
  1434. JitsiRemoteTrack.prototype.isLocal = function () {
  1435. return false;
  1436. }
  1437. delete JitsiRemoteTrack.prototype.stop;
  1438. delete JitsiRemoteTrack.prototype.start;
  1439. module.exports = JitsiRemoteTrack;
  1440. },{"../../JitsiTrackEvents":10,"./JitsiTrack":15}],15:[function(require,module,exports){
  1441. var RTCBrowserType = require("./RTCBrowserType");
  1442. var JitsiTrackEvents = require("../../JitsiTrackEvents");
  1443. var EventEmitter = require("events");
  1444. /**
  1445. * This implements 'onended' callback normally fired by WebRTC after the stream
  1446. * is stopped. There is no such behaviour yet in FF, so we have to add it.
  1447. * @param jitsiTrack our track object holding the original WebRTC stream object
  1448. * to which 'onended' handling will be added.
  1449. */
  1450. function implementOnEndedHandling(jitsiTrack) {
  1451. var stream = jitsiTrack.getOriginalStream();
  1452. var originalStop = stream.stop;
  1453. stream.stop = function () {
  1454. originalStop.apply(stream);
  1455. if (jitsiTrack.isActive()) {
  1456. stream.onended();
  1457. }
  1458. };
  1459. }
  1460. /**
  1461. * Adds onended/oninactive handler to a MediaStream.
  1462. * @param mediaStream a MediaStream to attach onended/oninactive handler
  1463. * @param handler the handler
  1464. */
  1465. function addMediaStreamInactiveHandler(mediaStream, handler) {
  1466. if(RTCBrowserType.isTemasysPluginUsed()) {
  1467. // themasys
  1468. //FIXME: Seems that not working properly.
  1469. if(mediaStream.onended) {
  1470. mediaStream.onended = handler;
  1471. } else if(mediaStream.addEventListener) {
  1472. mediaStream.addEventListener('ended', function () {
  1473. handler(mediaStream);
  1474. });
  1475. } else if(mediaStream.attachEvent) {
  1476. mediaStream.attachEvent('ended', function () {
  1477. handler(mediaStream);
  1478. });
  1479. }
  1480. }
  1481. else {
  1482. if(typeof mediaStream.active !== "undefined")
  1483. mediaStream.oninactive = handler;
  1484. else
  1485. mediaStream.onended = handler;
  1486. }
  1487. }
  1488. /**
  1489. * Represents a single media track (either audio or video).
  1490. * @constructor
  1491. * @param rtc the rtc instance
  1492. * @param stream the stream
  1493. * @param streamInactiveHandler the function that will handle
  1494. * onended/oninactive events of the stream.
  1495. */
  1496. function JitsiTrack(rtc, stream, streamInactiveHandler)
  1497. {
  1498. /**
  1499. * Array with the HTML elements that are displaying the streams.
  1500. * @type {Array}
  1501. */
  1502. this.containers = [];
  1503. this.rtc = rtc;
  1504. this.stream = stream;
  1505. this.eventEmitter = new EventEmitter();
  1506. this.audioLevel = -1;
  1507. this.type = (this.stream.getVideoTracks().length > 0)?
  1508. JitsiTrack.VIDEO : JitsiTrack.AUDIO;
  1509. if(this.type == "audio") {
  1510. this._getTracks = function () {
  1511. return this.stream.getAudioTracks();
  1512. }.bind(this);
  1513. } else {
  1514. this._getTracks = function () {
  1515. return this.stream.getVideoTracks();
  1516. }.bind(this);
  1517. }
  1518. if (RTCBrowserType.isFirefox() && this.stream) {
  1519. implementOnEndedHandling(this);
  1520. }
  1521. if(stream)
  1522. addMediaStreamInactiveHandler(stream, streamInactiveHandler);
  1523. }
  1524. /**
  1525. * JitsiTrack video type.
  1526. * @type {string}
  1527. */
  1528. JitsiTrack.VIDEO = "video";
  1529. /**
  1530. * JitsiTrack audio type.
  1531. * @type {string}
  1532. */
  1533. JitsiTrack.AUDIO = "audio";
  1534. /**
  1535. * Returns the type (audio or video) of this track.
  1536. */
  1537. JitsiTrack.prototype.getType = function() {
  1538. return this.type;
  1539. };
  1540. /**
  1541. * Check if this is audiotrack.
  1542. */
  1543. JitsiTrack.prototype.isAudioTrack = function () {
  1544. return this.getType() === JitsiTrack.AUDIO;
  1545. };
  1546. /**
  1547. * Check if this is videotrack.
  1548. */
  1549. JitsiTrack.prototype.isVideoTrack = function () {
  1550. return this.getType() === JitsiTrack.VIDEO;
  1551. };
  1552. /**
  1553. * Returns the RTCMediaStream from the browser (?).
  1554. */
  1555. JitsiTrack.prototype.getOriginalStream = function() {
  1556. return this.stream;
  1557. }
  1558. /**
  1559. * Mutes the track.
  1560. */
  1561. JitsiTrack.prototype.mute = function () {
  1562. this._setMute(true);
  1563. }
  1564. /**
  1565. * Unmutes the stream.
  1566. */
  1567. JitsiTrack.prototype.unmute = function () {
  1568. this._setMute(false);
  1569. }
  1570. /**
  1571. * Attaches the MediaStream of this track to an HTML container (?).
  1572. * Adds the container to the list of containers that are displaying the track.
  1573. * @param container the HTML container
  1574. */
  1575. JitsiTrack.prototype.attach = function (container) {
  1576. if(this.stream)
  1577. require("./RTCUtils").attachMediaStream(container, this.stream);
  1578. this.containers.push(container);
  1579. }
  1580. /**
  1581. * Removes the track from the passed HTML container.
  1582. * @param container the HTML container. If <tt>null</tt> all containers are removed.
  1583. */
  1584. JitsiTrack.prototype.detach = function (container) {
  1585. for(var i = 0; i < this.containers.length; i++)
  1586. {
  1587. if(this.containers[i].is(container))
  1588. {
  1589. this.containers.splice(i,1);
  1590. }
  1591. if(!container)
  1592. {
  1593. this.containers[i].find(">video").remove();
  1594. }
  1595. }
  1596. if(container)
  1597. $(container).find(">video").remove();
  1598. }
  1599. /**
  1600. * Stops sending the media track. And removes it from the HTML.
  1601. * NOTE: Works for local tracks only.
  1602. */
  1603. JitsiTrack.prototype.stop = function () {
  1604. }
  1605. /**
  1606. * Returns true if this is a video track and the source of the video is a
  1607. * screen capture as opposed to a camera.
  1608. */
  1609. JitsiTrack.prototype.isScreenSharing = function(){
  1610. }
  1611. /**
  1612. * Returns id of the track.
  1613. * @returns {string} id of the track or null if this is fake track.
  1614. */
  1615. JitsiTrack.prototype.getId = function () {
  1616. var tracks = this.stream.getTracks();
  1617. if(!tracks || tracks.length === 0)
  1618. return null;
  1619. return tracks[0].id;
  1620. };
  1621. /**
  1622. * Checks whether the MediaStream is avtive/not ended.
  1623. * When there is no check for active we don't have information and so
  1624. * will return that stream is active (in case of FF).
  1625. * @returns {boolean} whether MediaStream is active.
  1626. */
  1627. JitsiTrack.prototype.isActive = function () {
  1628. if((typeof this.stream.active !== "undefined"))
  1629. return this.stream.active;
  1630. else
  1631. return true;
  1632. };
  1633. /**
  1634. * Attaches a handler for events(For example - "audio level changed".).
  1635. * All possible event are defined in JitsiTrackEvents.
  1636. * @param eventId the event ID.
  1637. * @param handler handler for the event.
  1638. */
  1639. JitsiTrack.prototype.on = function (eventId, handler) {
  1640. if(this.eventEmitter)
  1641. this.eventEmitter.on(eventId, handler);
  1642. }
  1643. /**
  1644. * Removes event listener
  1645. * @param eventId the event ID.
  1646. * @param [handler] optional, the specific handler to unbind
  1647. */
  1648. JitsiTrack.prototype.off = function (eventId, handler) {
  1649. if(this.eventEmitter)
  1650. this.eventEmitter.removeListener(eventId, handler);
  1651. }
  1652. // Common aliases for event emitter
  1653. JitsiTrack.prototype.addEventListener = JitsiTrack.prototype.on;
  1654. JitsiTrack.prototype.removeEventListener = JitsiTrack.prototype.off;
  1655. /**
  1656. * Sets the audio level for the stream
  1657. * @param audioLevel the new audio level
  1658. */
  1659. JitsiTrack.prototype.setAudioLevel = function (audioLevel) {
  1660. if(this.audioLevel !== audioLevel) {
  1661. this.eventEmitter.emit(JitsiTrackEvents.TRACK_AUDIO_LEVEL_CHANGED,
  1662. audioLevel);
  1663. this.audioLevel = audioLevel;
  1664. }
  1665. }
  1666. module.exports = JitsiTrack;
  1667. },{"../../JitsiTrackEvents":10,"./RTCBrowserType":17,"./RTCUtils":18,"events":44}],16:[function(require,module,exports){
  1668. /* global APP */
  1669. var EventEmitter = require("events");
  1670. var RTCBrowserType = require("./RTCBrowserType");
  1671. var RTCUtils = require("./RTCUtils.js");
  1672. var JitsiTrack = require("./JitsiTrack");
  1673. var JitsiLocalTrack = require("./JitsiLocalTrack.js");
  1674. var DataChannels = require("./DataChannels");
  1675. var JitsiRemoteTrack = require("./JitsiRemoteTrack.js");
  1676. var DesktopSharingEventTypes
  1677. = require("../../service/desktopsharing/DesktopSharingEventTypes");
  1678. var MediaStreamType = require("../../service/RTC/MediaStreamTypes");
  1679. var RTCEvents = require("../../service/RTC/RTCEvents.js");
  1680. function createLocalTracks(streams) {
  1681. var newStreams = []
  1682. for (var i = 0; i < streams.length; i++) {
  1683. var localStream = new JitsiLocalTrack(streams[i].stream,
  1684. streams[i].videoType, streams[i].resolution);
  1685. newStreams.push(localStream);
  1686. if (streams[i].isMuted === true)
  1687. localStream.setMute(true);
  1688. }
  1689. return newStreams;
  1690. }
  1691. function RTC(room, options) {
  1692. this.room = room;
  1693. this.localStreams = [];
  1694. //FIXME: we should start removing those streams.
  1695. //FIXME: We should support multiple streams per jid.
  1696. this.remoteStreams = {};
  1697. this.localAudio = null;
  1698. this.localVideo = null;
  1699. this.eventEmitter = new EventEmitter();
  1700. var self = this;
  1701. this.options = options || {};
  1702. room.addPresenceListener("videomuted", function (values, from) {
  1703. if(self.remoteStreams[from]) {
  1704. self.remoteStreams[from][JitsiTrack.VIDEO].setMute(values.value == "true");
  1705. }
  1706. });
  1707. room.addPresenceListener("audiomuted", function (values, from) {
  1708. if(self.remoteStreams[from]) {
  1709. self.remoteStreams[from][JitsiTrack.AUDIO].setMute(values.value == "true");
  1710. }
  1711. });
  1712. }
  1713. /**
  1714. * Creates the local MediaStreams.
  1715. * @param {Object} [options] optional parameters
  1716. * @param {Array} options.devices the devices that will be requested
  1717. * @param {string} options.resolution resolution constraints
  1718. * @param {bool} options.dontCreateJitsiTrack if <tt>true</tt> objects with the following structure {stream: the Media Stream,
  1719. * type: "audio" or "video", videoType: "camera" or "desktop"}
  1720. * will be returned trough the Promise, otherwise JitsiTrack objects will be returned.
  1721. * @param {string} options.cameraDeviceId
  1722. * @param {string} options.micDeviceId
  1723. * @returns {*} Promise object that will receive the new JitsiTracks
  1724. */
  1725. RTC.obtainAudioAndVideoPermissions = function (options) {
  1726. return RTCUtils.obtainAudioAndVideoPermissions(options).then(createLocalTracks);
  1727. }
  1728. RTC.prototype.onIncommingCall = function(event) {
  1729. if(this.options.config.openSctp)
  1730. this.dataChannels = new DataChannels(event.peerconnection, this.eventEmitter);
  1731. for(var i = 0; i < this.localStreams.length; i++)
  1732. if(this.localStreams[i])
  1733. {
  1734. this.room.addStream(this.localStreams[i].getOriginalStream(), function () {});
  1735. }
  1736. }
  1737. RTC.prototype.selectedEndpoint = function (id) {
  1738. if(this.dataChannels)
  1739. this.dataChannels.handleSelectedEndpointEvent(id);
  1740. }
  1741. RTC.prototype.pinEndpoint = function (id) {
  1742. if(this.dataChannels)
  1743. this.dataChannels.handlePinnedEndpointEvent(id);
  1744. }
  1745. RTC.prototype.addListener = function (type, listener) {
  1746. this.eventEmitter.on(type, listener);
  1747. };
  1748. RTC.prototype.removeListener = function (eventType, listener) {
  1749. this.eventEmitter.removeListener(eventType, listener);
  1750. };
  1751. RTC.addListener = function (eventType, listener) {
  1752. RTCUtils.addListener(eventType, listener);
  1753. }
  1754. RTC.removeListener = function (eventType, listener) {
  1755. RTCUtils.removeListener(eventType, listener)
  1756. }
  1757. RTC.isRTCReady = function () {
  1758. return RTCUtils.isRTCReady();
  1759. }
  1760. RTC.init = function (options) {
  1761. this.options = options || {};
  1762. return RTCUtils.init(this.options);
  1763. }
  1764. RTC.getDeviceAvailability = function () {
  1765. return RTCUtils.getDeviceAvailability();
  1766. }
  1767. RTC.prototype.addLocalStream = function (stream) {
  1768. this.localStreams.push(stream);
  1769. stream._setRTC(this);
  1770. if (stream.type == "audio") {
  1771. this.localAudio = stream;
  1772. } else {
  1773. this.localVideo = stream;
  1774. }
  1775. };
  1776. RTC.prototype.removeLocalStream = function (stream) {
  1777. for(var i = 0; i < this.localStreams.length; i++) {
  1778. if(this.localStreams[i].getOriginalStream() === stream) {
  1779. delete this.localStreams[i];
  1780. return;
  1781. }
  1782. }
  1783. };
  1784. RTC.prototype.createRemoteStream = function (data, sid, thessrc) {
  1785. var remoteStream = new JitsiRemoteTrack(this, data, sid, thessrc);
  1786. if(!data.peerjid)
  1787. return;
  1788. var jid = data.peerjid;
  1789. if(!this.remoteStreams[jid]) {
  1790. this.remoteStreams[jid] = {};
  1791. }
  1792. this.remoteStreams[jid][remoteStream.type]= remoteStream;
  1793. return remoteStream;
  1794. };
  1795. RTC.getPCConstraints = function () {
  1796. return RTCUtils.pc_constraints;
  1797. };
  1798. RTC.attachMediaStream = function (elSelector, stream) {
  1799. RTCUtils.attachMediaStream(elSelector, stream);
  1800. };
  1801. RTC.getStreamID = function (stream) {
  1802. return RTCUtils.getStreamID(stream);
  1803. };
  1804. RTC.getVideoSrc = function (element) {
  1805. return RTCUtils.getVideoSrc(element);
  1806. };
  1807. RTC.isDeviceListAvailable = function () {
  1808. return RTCUtils.isDeviceListAvailable();
  1809. };
  1810. /**
  1811. * Allows to receive list of available cameras/microphones.
  1812. * @param {function} callback would receive array of devices as an argument
  1813. */
  1814. RTC.enumerateDevices = function (callback) {
  1815. RTCUtils.enumerateDevices(callback);
  1816. };
  1817. RTC.setVideoSrc = function (element, src) {
  1818. RTCUtils.setVideoSrc(element, src);
  1819. };
  1820. /**
  1821. * A method to handle stopping of the stream.
  1822. * One point to handle the differences in various implementations.
  1823. * @param mediaStream MediaStream object to stop.
  1824. */
  1825. RTC.stopMediaStream = function (mediaStream) {
  1826. RTCUtils.stopMediaStream(mediaStream);
  1827. };
  1828. RTC.prototype.getVideoElementName = function () {
  1829. return RTCBrowserType.isTemasysPluginUsed() ? 'object' : 'video';
  1830. };
  1831. RTC.prototype.dispose = function() {
  1832. };
  1833. RTC.prototype.switchVideoStreams = function (newStream) {
  1834. this.localVideo.stream = newStream;
  1835. this.localStreams = [];
  1836. //in firefox we have only one stream object
  1837. if (this.localAudio.getOriginalStream() != newStream)
  1838. this.localStreams.push(this.localAudio);
  1839. this.localStreams.push(this.localVideo);
  1840. };
  1841. RTC.prototype.setAudioLevel = function (jid, audioLevel) {
  1842. if(this.remoteStreams[jid] && this.remoteStreams[jid][JitsiTrack.AUDIO])
  1843. this.remoteStreams[jid][JitsiTrack.AUDIO].setAudioLevel(audioLevel);
  1844. }
  1845. module.exports = RTC;
  1846. },{"../../service/RTC/MediaStreamTypes":83,"../../service/RTC/RTCEvents.js":84,"../../service/desktopsharing/DesktopSharingEventTypes":88,"./DataChannels":12,"./JitsiLocalTrack.js":13,"./JitsiRemoteTrack.js":14,"./JitsiTrack":15,"./RTCBrowserType":17,"./RTCUtils.js":18,"events":44}],17:[function(require,module,exports){
  1847. var currentBrowser;
  1848. var browserVersion;
  1849. var isAndroid;
  1850. var RTCBrowserType = {
  1851. RTC_BROWSER_CHROME: "rtc_browser.chrome",
  1852. RTC_BROWSER_OPERA: "rtc_browser.opera",
  1853. RTC_BROWSER_FIREFOX: "rtc_browser.firefox",
  1854. RTC_BROWSER_IEXPLORER: "rtc_browser.iexplorer",
  1855. RTC_BROWSER_SAFARI: "rtc_browser.safari",
  1856. getBrowserType: function () {
  1857. return currentBrowser;
  1858. },
  1859. isChrome: function () {
  1860. return currentBrowser === RTCBrowserType.RTC_BROWSER_CHROME;
  1861. },
  1862. isOpera: function () {
  1863. return currentBrowser === RTCBrowserType.RTC_BROWSER_OPERA;
  1864. },
  1865. isFirefox: function () {
  1866. return currentBrowser === RTCBrowserType.RTC_BROWSER_FIREFOX;
  1867. },
  1868. isIExplorer: function () {
  1869. return currentBrowser === RTCBrowserType.RTC_BROWSER_IEXPLORER;
  1870. },
  1871. isSafari: function () {
  1872. return currentBrowser === RTCBrowserType.RTC_BROWSER_SAFARI;
  1873. },
  1874. isTemasysPluginUsed: function () {
  1875. return RTCBrowserType.isIExplorer() || RTCBrowserType.isSafari();
  1876. },
  1877. getFirefoxVersion: function () {
  1878. return RTCBrowserType.isFirefox() ? browserVersion : null;
  1879. },
  1880. getChromeVersion: function () {
  1881. return RTCBrowserType.isChrome() ? browserVersion : null;
  1882. },
  1883. usesPlanB: function() {
  1884. return RTCBrowserType.isChrome() || RTCBrowserType.isOpera() ||
  1885. RTCBrowserType.isTemasysPluginUsed();
  1886. },
  1887. usesUnifiedPlan: function() {
  1888. return RTCBrowserType.isFirefox();
  1889. },
  1890. /**
  1891. * Whether the browser is running on an android device.
  1892. */
  1893. isAndroid: function() {
  1894. return isAndroid;
  1895. }
  1896. // Add version getters for other browsers when needed
  1897. };
  1898. // detectOpera() must be called before detectChrome() !!!
  1899. // otherwise Opera wil be detected as Chrome
  1900. function detectChrome() {
  1901. if (navigator.webkitGetUserMedia) {
  1902. currentBrowser = RTCBrowserType.RTC_BROWSER_CHROME;
  1903. var userAgent = navigator.userAgent.toLowerCase();
  1904. // We can assume that user agent is chrome, because it's
  1905. // enforced when 'ext' streaming method is set
  1906. var ver = parseInt(userAgent.match(/chrome\/(\d+)\./)[1], 10);
  1907. console.log("This appears to be Chrome, ver: " + ver);
  1908. return ver;
  1909. }
  1910. return null;
  1911. }
  1912. function detectOpera() {
  1913. var userAgent = navigator.userAgent;
  1914. if (userAgent.match(/Opera|OPR/)) {
  1915. currentBrowser = RTCBrowserType.RTC_BROWSER_OPERA;
  1916. var version = userAgent.match(/(Opera|OPR) ?\/?(\d+)\.?/)[2];
  1917. console.info("This appears to be Opera, ver: " + version);
  1918. return version;
  1919. }
  1920. return null;
  1921. }
  1922. function detectFirefox() {
  1923. if (navigator.mozGetUserMedia) {
  1924. currentBrowser = RTCBrowserType.RTC_BROWSER_FIREFOX;
  1925. var version = parseInt(
  1926. navigator.userAgent.match(/Firefox\/([0-9]+)\./)[1], 10);
  1927. console.log('This appears to be Firefox, ver: ' + version);
  1928. return version;
  1929. }
  1930. return null;
  1931. }
  1932. function detectSafari() {
  1933. if ((/^((?!chrome).)*safari/i.test(navigator.userAgent))) {
  1934. currentBrowser = RTCBrowserType.RTC_BROWSER_SAFARI;
  1935. console.info("This appears to be Safari");
  1936. // FIXME detect Safari version when needed
  1937. return 1;
  1938. }
  1939. return null;
  1940. }
  1941. function detectIE() {
  1942. var version;
  1943. var ua = window.navigator.userAgent;
  1944. var msie = ua.indexOf('MSIE ');
  1945. if (msie > 0) {
  1946. // IE 10 or older => return version number
  1947. version = parseInt(ua.substring(msie + 5, ua.indexOf('.', msie)), 10);
  1948. }
  1949. var trident = ua.indexOf('Trident/');
  1950. if (!version && trident > 0) {
  1951. // IE 11 => return version number
  1952. var rv = ua.indexOf('rv:');
  1953. version = parseInt(ua.substring(rv + 3, ua.indexOf('.', rv)), 10);
  1954. }
  1955. var edge = ua.indexOf('Edge/');
  1956. if (!version && edge > 0) {
  1957. // IE 12 => return version number
  1958. version = parseInt(ua.substring(edge + 5, ua.indexOf('.', edge)), 10);
  1959. }
  1960. if (version) {
  1961. currentBrowser = RTCBrowserType.RTC_BROWSER_IEXPLORER;
  1962. console.info("This appears to be IExplorer, ver: " + version);
  1963. }
  1964. return version;
  1965. }
  1966. function detectBrowser() {
  1967. var version;
  1968. var detectors = [
  1969. detectOpera,
  1970. detectChrome,
  1971. detectFirefox,
  1972. detectIE,
  1973. detectSafari
  1974. ];
  1975. // Try all browser detectors
  1976. for (var i = 0; i < detectors.length; i++) {
  1977. version = detectors[i]();
  1978. if (version)
  1979. return version;
  1980. }
  1981. console.warn("Browser type defaults to Safari ver 1");
  1982. currentBrowser = RTCBrowserType.RTC_BROWSER_SAFARI;
  1983. return 1;
  1984. }
  1985. browserVersion = detectBrowser();
  1986. isAndroid = navigator.userAgent.indexOf('Android') != -1;
  1987. module.exports = RTCBrowserType;
  1988. },{}],18:[function(require,module,exports){
  1989. (function (__filename){
  1990. /* global config, require, attachMediaStream, getUserMedia,
  1991. RTCPeerConnection, RTCSessionDescription, RTCIceCandidate, MediaStreamTrack,
  1992. mozRTCPeerConnection, mozRTCSessionDescription, mozRTCIceCandidate,
  1993. webkitRTCPeerConnection, webkitMediaStream, webkitURL
  1994. */
  1995. /* jshint -W101 */
  1996. var logger = require("jitsi-meet-logger").getLogger(__filename);
  1997. var RTCBrowserType = require("./RTCBrowserType");
  1998. var Resolutions = require("../../service/RTC/Resolutions");
  1999. var RTCEvents = require("../../service/RTC/RTCEvents");
  2000. var AdapterJS = require("./adapter.screenshare");
  2001. var SDPUtil = require("../xmpp/SDPUtil");
  2002. var EventEmitter = require("events");
  2003. var screenObtainer = require("./ScreenObtainer");
  2004. var JitsiTrackErrors = require("../../JitsiTrackErrors");
  2005. var eventEmitter = new EventEmitter();
  2006. var devices = {
  2007. audio: true,
  2008. video: true
  2009. };
  2010. var rtcReady = false;
  2011. function setResolutionConstraints(constraints, resolution) {
  2012. var isAndroid = RTCBrowserType.isAndroid();
  2013. if (Resolutions[resolution]) {
  2014. constraints.video.mandatory.minWidth = Resolutions[resolution].width;
  2015. constraints.video.mandatory.minHeight = Resolutions[resolution].height;
  2016. }
  2017. else if (isAndroid) {
  2018. // FIXME can't remember if the purpose of this was to always request
  2019. // low resolution on Android ? if yes it should be moved up front
  2020. constraints.video.mandatory.minWidth = 320;
  2021. constraints.video.mandatory.minHeight = 240;
  2022. constraints.video.mandatory.maxFrameRate = 15;
  2023. }
  2024. if (constraints.video.mandatory.minWidth)
  2025. constraints.video.mandatory.maxWidth =
  2026. constraints.video.mandatory.minWidth;
  2027. if (constraints.video.mandatory.minHeight)
  2028. constraints.video.mandatory.maxHeight =
  2029. constraints.video.mandatory.minHeight;
  2030. }
  2031. /**
  2032. * @param {string[]} um required user media types
  2033. *
  2034. * @param {Object} [options={}] optional parameters
  2035. * @param {string} options.resolution
  2036. * @param {number} options.bandwidth
  2037. * @param {number} options.fps
  2038. * @param {string} options.desktopStream
  2039. * @param {string} options.cameraDeviceId
  2040. * @param {string} options.micDeviceId
  2041. * @param {bool} firefox_fake_device
  2042. */
  2043. function getConstraints(um, options) {
  2044. var constraints = {audio: false, video: false};
  2045. if (um.indexOf('video') >= 0) {
  2046. // same behaviour as true
  2047. constraints.video = { mandatory: {}, optional: [] };
  2048. if (options.cameraDeviceId) {
  2049. constraints.video.optional.push({
  2050. sourceId: options.cameraDeviceId
  2051. });
  2052. }
  2053. constraints.video.optional.push({ googLeakyBucket: true });
  2054. setResolutionConstraints(constraints, options.resolution);
  2055. }
  2056. if (um.indexOf('audio') >= 0) {
  2057. if (!RTCBrowserType.isFirefox()) {
  2058. // same behaviour as true
  2059. constraints.audio = { mandatory: {}, optional: []};
  2060. if (options.micDeviceId) {
  2061. constraints.audio.optional.push({
  2062. sourceId: options.micDeviceId
  2063. });
  2064. }
  2065. // if it is good enough for hangouts...
  2066. constraints.audio.optional.push(
  2067. {googEchoCancellation: true},
  2068. {googAutoGainControl: true},
  2069. {googNoiseSupression: true},
  2070. {googHighpassFilter: true},
  2071. {googNoisesuppression2: true},
  2072. {googEchoCancellation2: true},
  2073. {googAutoGainControl2: true}
  2074. );
  2075. } else {
  2076. if (options.micDeviceId) {
  2077. constraints.audio = {
  2078. mandatory: {},
  2079. optional: [{
  2080. sourceId: options.micDeviceId
  2081. }]};
  2082. } else {
  2083. constraints.audio = true;
  2084. }
  2085. }
  2086. }
  2087. if (um.indexOf('screen') >= 0) {
  2088. if (RTCBrowserType.isChrome()) {
  2089. constraints.video = {
  2090. mandatory: {
  2091. chromeMediaSource: "screen",
  2092. googLeakyBucket: true,
  2093. maxWidth: window.screen.width,
  2094. maxHeight: window.screen.height,
  2095. maxFrameRate: 3
  2096. },
  2097. optional: []
  2098. };
  2099. } else if (RTCBrowserType.isTemasysPluginUsed()) {
  2100. constraints.video = {
  2101. optional: [
  2102. {
  2103. sourceId: AdapterJS.WebRTCPlugin.plugin.screensharingKey
  2104. }
  2105. ]
  2106. };
  2107. } else if (RTCBrowserType.isFirefox()) {
  2108. constraints.video = {
  2109. mozMediaSource: "window",
  2110. mediaSource: "window"
  2111. };
  2112. } else {
  2113. logger.error(
  2114. "'screen' WebRTC media source is supported only in Chrome" +
  2115. " and with Temasys plugin");
  2116. }
  2117. }
  2118. if (um.indexOf('desktop') >= 0) {
  2119. constraints.video = {
  2120. mandatory: {
  2121. chromeMediaSource: "desktop",
  2122. chromeMediaSourceId: options.desktopStream,
  2123. googLeakyBucket: true,
  2124. maxWidth: window.screen.width,
  2125. maxHeight: window.screen.height,
  2126. maxFrameRate: 3
  2127. },
  2128. optional: []
  2129. };
  2130. }
  2131. if (options.bandwidth) {
  2132. if (!constraints.video) {
  2133. //same behaviour as true
  2134. constraints.video = {mandatory: {}, optional: []};
  2135. }
  2136. constraints.video.optional.push({bandwidth: options.bandwidth});
  2137. }
  2138. if (options.fps) {
  2139. // for some cameras it might be necessary to request 30fps
  2140. // so they choose 30fps mjpg over 10fps yuy2
  2141. if (!constraints.video) {
  2142. // same behaviour as true;
  2143. constraints.video = {mandatory: {}, optional: []};
  2144. }
  2145. constraints.video.mandatory.minFrameRate = options.fps;
  2146. }
  2147. // we turn audio for both audio and video tracks, the fake audio & video seems to work
  2148. // only when enabled in one getUserMedia call, we cannot get fake audio separate by fake video
  2149. // this later can be a problem with some of the tests
  2150. if(RTCBrowserType.isFirefox() && options.firefox_fake_device)
  2151. {
  2152. // seems to be fixed now, removing this experimental fix, as having
  2153. // multiple audio tracks brake the tests
  2154. //constraints.audio = true;
  2155. constraints.fake = true;
  2156. }
  2157. return constraints;
  2158. }
  2159. function setAvailableDevices(um, available) {
  2160. if (um.indexOf("video") != -1) {
  2161. devices.video = available;
  2162. }
  2163. if (um.indexOf("audio") != -1) {
  2164. devices.audio = available;
  2165. }
  2166. eventEmitter.emit(RTCEvents.AVAILABLE_DEVICES_CHANGED, devices);
  2167. }
  2168. // In case of IE we continue from 'onReady' callback
  2169. // passed to RTCUtils constructor. It will be invoked by Temasys plugin
  2170. // once it is initialized.
  2171. function onReady (options, GUM) {
  2172. rtcReady = true;
  2173. eventEmitter.emit(RTCEvents.RTC_READY, true);
  2174. screenObtainer.init(eventEmitter, options, GUM);
  2175. }
  2176. /**
  2177. * Apply function with arguments if function exists.
  2178. * Do nothing if function not provided.
  2179. * @param {function} [fn] function to apply
  2180. * @param {Array} [args=[]] arguments for function
  2181. */
  2182. function maybeApply(fn, args) {
  2183. if (fn) {
  2184. fn.apply(null, args || []);
  2185. }
  2186. }
  2187. var getUserMediaStatus = {
  2188. initialized: false,
  2189. callbacks: []
  2190. };
  2191. /**
  2192. * Wrap `getUserMedia` to allow others to know if it was executed at least
  2193. * once or not. Wrapper function uses `getUserMediaStatus` object.
  2194. * @param {Function} getUserMedia native function
  2195. * @returns {Function} wrapped function
  2196. */
  2197. function wrapGetUserMedia(getUserMedia) {
  2198. return function (constraints, successCallback, errorCallback) {
  2199. getUserMedia(constraints, function (stream) {
  2200. maybeApply(successCallback, [stream]);
  2201. if (!getUserMediaStatus.initialized) {
  2202. getUserMediaStatus.initialized = true;
  2203. getUserMediaStatus.callbacks.forEach(function (callback) {
  2204. callback();
  2205. });
  2206. getUserMediaStatus.callbacks.length = 0;
  2207. }
  2208. }, function (error) {
  2209. maybeApply(errorCallback, [error]);
  2210. });
  2211. };
  2212. }
  2213. /**
  2214. * Create stub device which equals to auto selected device.
  2215. * @param {string} kind if that should be `audio` or `video` device
  2216. * @returns {Object} stub device description in `enumerateDevices` format
  2217. */
  2218. function createAutoDeviceInfo(kind) {
  2219. return {
  2220. facing: null,
  2221. label: 'Auto',
  2222. kind: kind,
  2223. deviceId: '',
  2224. groupId: null
  2225. };
  2226. }
  2227. /**
  2228. * Execute function after getUserMedia was executed at least once.
  2229. * @param {Function} callback function to execute after getUserMedia
  2230. */
  2231. function afterUserMediaInitialized(callback) {
  2232. if (getUserMediaStatus.initialized) {
  2233. callback();
  2234. } else {
  2235. getUserMediaStatus.callbacks.push(callback);
  2236. }
  2237. }
  2238. /**
  2239. * Wrapper function which makes enumerateDevices to wait
  2240. * until someone executes getUserMedia first time.
  2241. * @param {Function} enumerateDevices native function
  2242. * @returns {Funtion} wrapped function
  2243. */
  2244. function wrapEnumerateDevices(enumerateDevices) {
  2245. return function (callback) {
  2246. // enumerate devices only after initial getUserMedia
  2247. afterUserMediaInitialized(function () {
  2248. enumerateDevices().then(function (devices) {
  2249. //add auto devices
  2250. devices.unshift(
  2251. createAutoDeviceInfo('audioinput'),
  2252. createAutoDeviceInfo('videoinput')
  2253. );
  2254. callback(devices);
  2255. }, function (err) {
  2256. console.error('cannot enumerate devices: ', err);
  2257. // return only auto devices
  2258. callback([createAutoDeviceInfo('audioInput'),
  2259. createAutoDeviceInfo('videoinput')]);
  2260. });
  2261. });
  2262. };
  2263. }
  2264. /**
  2265. * Use old MediaStreamTrack to get devices list and
  2266. * convert it to enumerateDevices format.
  2267. * @param {Function} callback function to call when received devices list.
  2268. */
  2269. function enumerateDevicesThroughMediaStreamTrack (callback) {
  2270. MediaStreamTrack.getSources(function (sources) {
  2271. var devices = sources.map(function (source) {
  2272. var kind = (source.kind || '').toLowerCase();
  2273. return {
  2274. facing: source.facing || null,
  2275. label: source.label,
  2276. kind: kind ? kind + 'input': null,
  2277. deviceId: source.id,
  2278. groupId: source.groupId || null
  2279. };
  2280. });
  2281. //add auto devices
  2282. devices.unshift(
  2283. createAutoDeviceInfo('audioinput'),
  2284. createAutoDeviceInfo('videoinput')
  2285. );
  2286. callback(devices);
  2287. });
  2288. }
  2289. function obtainDevices(options) {
  2290. if(!options.devices || options.devices.length === 0) {
  2291. return options.successCallback(options.streams || {});
  2292. }
  2293. var device = options.devices.splice(0, 1);
  2294. options.deviceGUM[device](function (stream) {
  2295. options.streams = options.streams || {};
  2296. options.streams[device] = stream;
  2297. obtainDevices(options);
  2298. },
  2299. function (error) {
  2300. logger.error(
  2301. "failed to obtain " + device + " stream - stop", error);
  2302. options.errorCallback(JitsiTrackErrors.parseError(error));
  2303. });
  2304. }
  2305. /**
  2306. * Handles the newly created Media Streams.
  2307. * @param streams the new Media Streams
  2308. * @param resolution the resolution of the video streams
  2309. * @returns {*[]} object that describes the new streams
  2310. */
  2311. function handleLocalStream(streams, resolution) {
  2312. var audioStream, videoStream, desktopStream, res = [];
  2313. // If this is FF, the stream parameter is *not* a MediaStream object, it's
  2314. // an object with two properties: audioStream, videoStream.
  2315. if (window.webkitMediaStream) {
  2316. var audioVideo = streams.audioVideo;
  2317. if (audioVideo) {
  2318. var audioTracks = audioVideo.getAudioTracks();
  2319. if(audioTracks.length) {
  2320. audioStream = new webkitMediaStream();
  2321. for (var i = 0; i < audioTracks.length; i++) {
  2322. audioStream.addTrack(audioTracks[i]);
  2323. }
  2324. }
  2325. var videoTracks = audioVideo.getVideoTracks();
  2326. if(videoTracks.length) {
  2327. videoStream = new webkitMediaStream();
  2328. for (var j = 0; j < videoTracks.length; j++) {
  2329. videoStream.addTrack(videoTracks[j]);
  2330. }
  2331. }
  2332. }
  2333. if (streams && streams.desktopStream)
  2334. desktopStream = streams.desktopStream;
  2335. }
  2336. else if (RTCBrowserType.isFirefox() || RTCBrowserType.isTemasysPluginUsed()) { // Firefox and Temasys plugin
  2337. if (streams && streams.audio)
  2338. audioStream = streams.audio;
  2339. if (streams && streams.video)
  2340. videoStream = streams.video;
  2341. if(streams && streams.desktop)
  2342. desktopStream = streams.desktop;
  2343. }
  2344. if (desktopStream)
  2345. res.push({stream: desktopStream,
  2346. type: "video", videoType: "desktop"});
  2347. if(audioStream)
  2348. res.push({stream: audioStream, type: "audio", videoType: null});
  2349. if(videoStream)
  2350. res.push({stream: videoStream, type: "video", videoType: "camera",
  2351. resolution: resolution});
  2352. return res;
  2353. }
  2354. //Options parameter is to pass config options. Currently uses only "useIPv6".
  2355. var RTCUtils = {
  2356. init: function (options) {
  2357. return new Promise(function(resolve, reject) {
  2358. if (RTCBrowserType.isFirefox()) {
  2359. var FFversion = RTCBrowserType.getFirefoxVersion();
  2360. if (FFversion < 40) {
  2361. logger.error(
  2362. "Firefox version too old: " + FFversion +
  2363. ". Required >= 40.");
  2364. reject(new Error("Firefox version too old: " + FFversion +
  2365. ". Required >= 40."));
  2366. return;
  2367. }
  2368. this.peerconnection = mozRTCPeerConnection;
  2369. this.getUserMedia = wrapGetUserMedia(navigator.mozGetUserMedia.bind(navigator));
  2370. this.enumerateDevices = wrapEnumerateDevices(
  2371. navigator.mediaDevices.enumerateDevices.bind(navigator.mediaDevices)
  2372. );
  2373. this.pc_constraints = {};
  2374. this.attachMediaStream = function (element, stream) {
  2375. // srcObject is being standardized and FF will eventually
  2376. // support that unprefixed. FF also supports the
  2377. // "element.src = URL.createObjectURL(...)" combo, but that
  2378. // will be deprecated in favour of srcObject.
  2379. //
  2380. // https://groups.google.com/forum/#!topic/mozilla.dev.media/pKOiioXonJg
  2381. // https://github.com/webrtc/samples/issues/302
  2382. if (!element[0])
  2383. return;
  2384. element[0].mozSrcObject = stream;
  2385. element[0].play();
  2386. };
  2387. this.getStreamID = function (stream) {
  2388. var id = stream.id;
  2389. if (!id) {
  2390. var tracks = stream.getVideoTracks();
  2391. if (!tracks || tracks.length === 0) {
  2392. tracks = stream.getAudioTracks();
  2393. }
  2394. id = tracks[0].id;
  2395. }
  2396. return SDPUtil.filter_special_chars(id);
  2397. };
  2398. this.getVideoSrc = function (element) {
  2399. if (!element)
  2400. return null;
  2401. return element.mozSrcObject;
  2402. };
  2403. this.setVideoSrc = function (element, src) {
  2404. if (element)
  2405. element.mozSrcObject = src;
  2406. };
  2407. RTCSessionDescription = mozRTCSessionDescription;
  2408. RTCIceCandidate = mozRTCIceCandidate;
  2409. } else if (RTCBrowserType.isChrome() || RTCBrowserType.isOpera()) {
  2410. this.peerconnection = webkitRTCPeerConnection;
  2411. var getUserMedia = navigator.webkitGetUserMedia.bind(navigator);
  2412. if (navigator.mediaDevices) {
  2413. this.getUserMedia = wrapGetUserMedia(getUserMedia);
  2414. this.enumerateDevices = wrapEnumerateDevices(
  2415. navigator.mediaDevices.enumerateDevices.bind(navigator.mediaDevices)
  2416. );
  2417. } else {
  2418. this.getUserMedia = getUserMedia;
  2419. this.enumerateDevices = enumerateDevicesThroughMediaStreamTrack;
  2420. }
  2421. this.attachMediaStream = function (element, stream) {
  2422. element.attr('src', webkitURL.createObjectURL(stream));
  2423. };
  2424. this.getStreamID = function (stream) {
  2425. // streams from FF endpoints have the characters '{' and '}'
  2426. // that make jQuery choke.
  2427. return SDPUtil.filter_special_chars(stream.id);
  2428. };
  2429. this.getVideoSrc = function (element) {
  2430. if (!element)
  2431. return null;
  2432. return element.getAttribute("src");
  2433. };
  2434. this.setVideoSrc = function (element, src) {
  2435. if (element)
  2436. element.setAttribute("src", src);
  2437. };
  2438. // DTLS should now be enabled by default but..
  2439. this.pc_constraints = {'optional': [
  2440. {'DtlsSrtpKeyAgreement': 'true'}
  2441. ]};
  2442. if (options.useIPv6) {
  2443. // https://code.google.com/p/webrtc/issues/detail?id=2828
  2444. this.pc_constraints.optional.push({googIPv6: true});
  2445. }
  2446. if (RTCBrowserType.isAndroid()) {
  2447. this.pc_constraints = {}; // disable DTLS on Android
  2448. }
  2449. if (!webkitMediaStream.prototype.getVideoTracks) {
  2450. webkitMediaStream.prototype.getVideoTracks = function () {
  2451. return this.videoTracks;
  2452. };
  2453. }
  2454. if (!webkitMediaStream.prototype.getAudioTracks) {
  2455. webkitMediaStream.prototype.getAudioTracks = function () {
  2456. return this.audioTracks;
  2457. };
  2458. }
  2459. }
  2460. // Detect IE/Safari
  2461. else if (RTCBrowserType.isTemasysPluginUsed()) {
  2462. //AdapterJS.WebRTCPlugin.setLogLevel(
  2463. // AdapterJS.WebRTCPlugin.PLUGIN_LOG_LEVELS.VERBOSE);
  2464. var self = this;
  2465. AdapterJS.webRTCReady(function (isPlugin) {
  2466. self.peerconnection = RTCPeerConnection;
  2467. self.getUserMedia = window.getUserMedia;
  2468. self.enumerateDevices = enumerateDevicesThroughMediaStreamTrack;
  2469. self.attachMediaStream = function (elSel, stream) {
  2470. if (stream.id === "dummyAudio" || stream.id === "dummyVideo") {
  2471. return;
  2472. }
  2473. attachMediaStream(elSel[0], stream);
  2474. };
  2475. self.getStreamID = function (stream) {
  2476. var id = SDPUtil.filter_special_chars(stream.label);
  2477. return id;
  2478. };
  2479. self.getVideoSrc = function (element) {
  2480. if (!element) {
  2481. logger.warn("Attempt to get video SRC of null element");
  2482. return null;
  2483. }
  2484. var children = element.children;
  2485. for (var i = 0; i !== children.length; ++i) {
  2486. if (children[i].name === 'streamId') {
  2487. return children[i].value;
  2488. }
  2489. }
  2490. //logger.info(element.id + " SRC: " + src);
  2491. return null;
  2492. };
  2493. self.setVideoSrc = function (element, src) {
  2494. //logger.info("Set video src: ", element, src);
  2495. if (!src) {
  2496. logger.warn("Not attaching video stream, 'src' is null");
  2497. return;
  2498. }
  2499. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  2500. var stream = AdapterJS.WebRTCPlugin.plugin
  2501. .getStreamWithId(AdapterJS.WebRTCPlugin.pageId, src);
  2502. attachMediaStream(element, stream);
  2503. };
  2504. onReady(options, self.getUserMediaWithConstraints);
  2505. resolve();
  2506. });
  2507. } else {
  2508. try {
  2509. logger.error('Browser does not appear to be WebRTC-capable');
  2510. } catch (e) {
  2511. }
  2512. reject('Browser does not appear to be WebRTC-capable');
  2513. return;
  2514. }
  2515. // Call onReady() if Temasys plugin is not used
  2516. if (!RTCBrowserType.isTemasysPluginUsed()) {
  2517. onReady(options, this.getUserMediaWithConstraints);
  2518. resolve();
  2519. }
  2520. }.bind(this));
  2521. },
  2522. /**
  2523. * @param {string[]} um required user media types
  2524. * @param {function} success_callback
  2525. * @param {Function} failure_callback
  2526. * @param {Object} [options] optional parameters
  2527. * @param {string} options.resolution
  2528. * @param {number} options.bandwidth
  2529. * @param {number} options.fps
  2530. * @param {string} options.desktopStream
  2531. * @param {string} options.cameraDeviceId
  2532. * @param {string} options.micDeviceId
  2533. **/
  2534. getUserMediaWithConstraints: function ( um, success_callback, failure_callback, options) {
  2535. options = options || {};
  2536. var resolution = options.resolution;
  2537. var constraints = getConstraints(um, options);
  2538. logger.info("Get media constraints", constraints);
  2539. try {
  2540. this.getUserMedia(constraints,
  2541. function (stream) {
  2542. logger.log('onUserMediaSuccess');
  2543. setAvailableDevices(um, true);
  2544. success_callback(stream);
  2545. },
  2546. function (error) {
  2547. setAvailableDevices(um, false);
  2548. logger.warn('Failed to get access to local media. Error ',
  2549. error, constraints);
  2550. if (failure_callback) {
  2551. failure_callback(error, resolution);
  2552. }
  2553. });
  2554. } catch (e) {
  2555. logger.error('GUM failed: ', e);
  2556. if (failure_callback) {
  2557. failure_callback(e);
  2558. }
  2559. }
  2560. },
  2561. /**
  2562. * Creates the local MediaStreams.
  2563. * @param {Object} [options] optional parameters
  2564. * @param {Array} options.devices the devices that will be requested
  2565. * @param {string} options.resolution resolution constraints
  2566. * @param {bool} options.dontCreateJitsiTrack if <tt>true</tt> objects with the following structure {stream: the Media Stream,
  2567. * type: "audio" or "video", videoType: "camera" or "desktop"}
  2568. * will be returned trough the Promise, otherwise JitsiTrack objects will be returned.
  2569. * @param {string} options.cameraDeviceId
  2570. * @param {string} options.micDeviceId
  2571. * @returns {*} Promise object that will receive the new JitsiTracks
  2572. */
  2573. obtainAudioAndVideoPermissions: function (options) {
  2574. var self = this;
  2575. options = options || {};
  2576. return new Promise(function (resolve, reject) {
  2577. var successCallback = function (stream) {
  2578. resolve(handleLocalStream(stream, options.resolution));
  2579. };
  2580. options.devices = options.devices || ['audio', 'video'];
  2581. if(!screenObtainer.isSupported()
  2582. && options.devices.indexOf("desktop") !== -1){
  2583. reject(new Error("Desktop sharing is not supported!"));
  2584. }
  2585. if (RTCBrowserType.isFirefox() ||
  2586. RTCBrowserType.isTemasysPluginUsed()) {
  2587. var GUM = function (device, s, e) {
  2588. this.getUserMediaWithConstraints(device, s, e, options);
  2589. };
  2590. var deviceGUM = {
  2591. "audio": GUM.bind(self, ["audio"]),
  2592. "video": GUM.bind(self, ["video"]),
  2593. "desktop": screenObtainer.obtainStream
  2594. };
  2595. // With FF/IE we can't split the stream into audio and video because FF
  2596. // doesn't support media stream constructors. So, we need to get the
  2597. // audio stream separately from the video stream using two distinct GUM
  2598. // calls. Not very user friendly :-( but we don't have many other
  2599. // options neither.
  2600. //
  2601. // Note that we pack those 2 streams in a single object and pass it to
  2602. // the successCallback method.
  2603. obtainDevices({
  2604. devices: options.devices,
  2605. streams: [],
  2606. successCallback: successCallback,
  2607. errorCallback: reject,
  2608. deviceGUM: deviceGUM
  2609. });
  2610. } else {
  2611. var hasDesktop = options.devices.indexOf('desktop') > -1;
  2612. if (hasDesktop) {
  2613. options.devices.splice(options.devices.indexOf("desktop"), 1);
  2614. }
  2615. options.resolution = options.resolution || '360';
  2616. if(options.devices.length) {
  2617. this.getUserMediaWithConstraints(
  2618. options.devices,
  2619. function (stream) {
  2620. if(hasDesktop) {
  2621. screenObtainer.obtainStream(
  2622. function (desktopStream) {
  2623. successCallback({audioVideo: stream,
  2624. desktopStream: desktopStream});
  2625. }, function (error) {
  2626. reject(
  2627. JitsiTrackErrors.parseError(error));
  2628. });
  2629. } else {
  2630. successCallback({audioVideo: stream});
  2631. }
  2632. },
  2633. function (error) {
  2634. reject(JitsiTrackErrors.parseError(error));
  2635. },
  2636. options);
  2637. } else if (hasDesktop) {
  2638. screenObtainer.obtainStream(
  2639. function (stream) {
  2640. successCallback({desktopStream: stream});
  2641. }, function (error) {
  2642. reject(
  2643. JitsiTrackErrors.parseError(error));
  2644. });
  2645. }
  2646. }
  2647. }.bind(this));
  2648. },
  2649. addListener: function (eventType, listener) {
  2650. eventEmitter.on(eventType, listener);
  2651. },
  2652. removeListener: function (eventType, listener) {
  2653. eventEmitter.removeListener(eventType, listener);
  2654. },
  2655. getDeviceAvailability: function () {
  2656. return devices;
  2657. },
  2658. isRTCReady: function () {
  2659. return rtcReady;
  2660. },
  2661. /**
  2662. * Checks if its possible to enumerate available cameras/micropones.
  2663. * @returns {boolean} true if available, false otherwise.
  2664. */
  2665. isDeviceListAvailable: function () {
  2666. var isEnumerateDevicesAvailable = navigator.mediaDevices && navigator.mediaDevices.enumerateDevices;
  2667. if (isEnumerateDevicesAvailable) {
  2668. return true;
  2669. }
  2670. return (MediaStreamTrack && MediaStreamTrack.getSources)? true : false;
  2671. },
  2672. /**
  2673. * A method to handle stopping of the stream.
  2674. * One point to handle the differences in various implementations.
  2675. * @param mediaStream MediaStream object to stop.
  2676. */
  2677. stopMediaStream: function (mediaStream) {
  2678. mediaStream.getTracks().forEach(function (track) {
  2679. // stop() not supported with IE
  2680. if (track.stop) {
  2681. track.stop();
  2682. }
  2683. });
  2684. // leave stop for implementation still using it
  2685. if (mediaStream.stop) {
  2686. mediaStream.stop();
  2687. }
  2688. }
  2689. };
  2690. module.exports = RTCUtils;
  2691. }).call(this,"/modules/RTC/RTCUtils.js")
  2692. },{"../../JitsiTrackErrors":9,"../../service/RTC/RTCEvents":84,"../../service/RTC/Resolutions":85,"../xmpp/SDPUtil":32,"./RTCBrowserType":17,"./ScreenObtainer":19,"./adapter.screenshare":20,"events":44,"jitsi-meet-logger":48}],19:[function(require,module,exports){
  2693. (function (__filename){
  2694. /* global chrome, $, alert */
  2695. /* jshint -W003 */
  2696. var logger = require("jitsi-meet-logger").getLogger(__filename);
  2697. var RTCBrowserType = require("./RTCBrowserType");
  2698. var AdapterJS = require("./adapter.screenshare");
  2699. var DesktopSharingEventTypes
  2700. = require("../../service/desktopsharing/DesktopSharingEventTypes");
  2701. /**
  2702. * Indicates whether the Chrome desktop sharing extension is installed.
  2703. * @type {boolean}
  2704. */
  2705. var chromeExtInstalled = false;
  2706. /**
  2707. * Indicates whether an update of the Chrome desktop sharing extension is
  2708. * required.
  2709. * @type {boolean}
  2710. */
  2711. var chromeExtUpdateRequired = false;
  2712. /**
  2713. * Whether the jidesha extension for firefox is installed for the domain on
  2714. * which we are running. Null designates an unknown value.
  2715. * @type {null}
  2716. */
  2717. var firefoxExtInstalled = null;
  2718. /**
  2719. * If set to true, detection of an installed firefox extension will be started
  2720. * again the next time obtainScreenOnFirefox is called (e.g. next time the
  2721. * user tries to enable screen sharing).
  2722. */
  2723. var reDetectFirefoxExtension = false;
  2724. var GUM = null;
  2725. /**
  2726. * Handles obtaining a stream from a screen capture on different browsers.
  2727. */
  2728. var ScreenObtainer = {
  2729. /**
  2730. * The EventEmitter to use to emit events.
  2731. * @type {null}
  2732. */
  2733. eventEmitter: null,
  2734. obtainStream: null,
  2735. /**
  2736. * Initializes the function used to obtain a screen capture
  2737. * (this.obtainStream).
  2738. *
  2739. * If the browser is Chrome, it uses the value of
  2740. * 'options.desktopSharingChromeMethod' (or 'options.desktopSharing') to
  2741. * decide whether to use the a Chrome extension (if the value is 'ext'),
  2742. * use the "screen" media source (if the value is 'webrtc'),
  2743. * or disable screen capture (if the value is other).
  2744. * Note that for the "screen" media source to work the
  2745. * 'chrome://flags/#enable-usermedia-screen-capture' flag must be set.
  2746. */
  2747. init: function(eventEmitter, options, gum) {
  2748. this.eventEmitter = eventEmitter;
  2749. var obtainDesktopStream = null;
  2750. this.options = options = options || {};
  2751. GUM = gum;
  2752. if (RTCBrowserType.isFirefox())
  2753. initFirefoxExtensionDetection(options);
  2754. // TODO remove this, options.desktopSharing is deprecated.
  2755. var chromeMethod =
  2756. (options.desktopSharingChromeMethod || options.desktopSharing);
  2757. if (RTCBrowserType.isTemasysPluginUsed()) {
  2758. if (!AdapterJS.WebRTCPlugin.plugin.HasScreensharingFeature) {
  2759. logger.info("Screensharing not supported by this plugin " +
  2760. "version");
  2761. } else if(!AdapterJS.WebRTCPlugin.plugin.isScreensharingAvailable) {
  2762. logger.info(
  2763. "Screensharing not available with Temasys plugin on" +
  2764. " this site");
  2765. } else {
  2766. obtainDesktopStream = obtainWebRTCScreen;
  2767. logger.info("Using Temasys plugin for desktop sharing");
  2768. }
  2769. } else if (RTCBrowserType.isChrome()) {
  2770. if (chromeMethod == "ext") {
  2771. if (RTCBrowserType.getChromeVersion() >= 34) {
  2772. obtainDesktopStream =
  2773. this.obtainScreenFromExtension;
  2774. logger.info("Using Chrome extension for desktop sharing");
  2775. initChromeExtension(options);
  2776. } else {
  2777. logger.info("Chrome extension not supported until ver 34");
  2778. }
  2779. } else if (chromeMethod == "webrtc") {
  2780. obtainDesktopStream = obtainWebRTCScreen;
  2781. logger.info("Using Chrome WebRTC for desktop sharing");
  2782. }
  2783. } else if (RTCBrowserType.isFirefox()) {
  2784. if (options.desktopSharingFirefoxDisabled) {
  2785. obtainDesktopStream = null;
  2786. } else if (window.location.protocol === "http:"){
  2787. logger.log("Screen sharing is not supported over HTTP. " +
  2788. "Use of HTTPS is required.");
  2789. obtainDesktopStream = null;
  2790. } else {
  2791. obtainDesktopStream = this.obtainScreenOnFirefox;
  2792. }
  2793. }
  2794. if (!obtainDesktopStream) {
  2795. logger.info("Desktop sharing disabled");
  2796. }
  2797. this.obtainStream = obtainDesktopStream;
  2798. },
  2799. /**
  2800. * Checks whether obtaining a screen capture is supported in the current
  2801. * environment.
  2802. * @returns {boolean}
  2803. */
  2804. isSupported: function() {
  2805. return !!this.obtainStream;
  2806. },
  2807. /**
  2808. * Obtains a screen capture stream on Firefox.
  2809. * @param callback
  2810. * @param errorCallback
  2811. */
  2812. obtainScreenOnFirefox:
  2813. function (callback, errorCallback) {
  2814. var self = this;
  2815. var extensionRequired = false;
  2816. if (this.options.desktopSharingFirefoxMaxVersionExtRequired === -1 ||
  2817. (this.options.desktopSharingFirefoxMaxVersionExtRequired >= 0 &&
  2818. RTCBrowserType.getFirefoxVersion() <=
  2819. this.options.desktopSharingFirefoxMaxVersionExtRequired)) {
  2820. extensionRequired = true;
  2821. logger.log("Jidesha extension required on firefox version " +
  2822. RTCBrowserType.getFirefoxVersion());
  2823. }
  2824. if (!extensionRequired || firefoxExtInstalled === true) {
  2825. obtainWebRTCScreen(callback, errorCallback);
  2826. return;
  2827. }
  2828. if (reDetectFirefoxExtension) {
  2829. reDetectFirefoxExtension = false;
  2830. initFirefoxExtensionDetection(this.options);
  2831. }
  2832. // Give it some (more) time to initialize, and assume lack of
  2833. // extension if it hasn't.
  2834. if (firefoxExtInstalled === null) {
  2835. window.setTimeout(
  2836. function() {
  2837. if (firefoxExtInstalled === null)
  2838. firefoxExtInstalled = false;
  2839. self.obtainScreenOnFirefox(callback, errorCallback);
  2840. },
  2841. 300
  2842. );
  2843. logger.log("Waiting for detection of jidesha on firefox to " +
  2844. "finish.");
  2845. return;
  2846. }
  2847. // We need an extension and it isn't installed.
  2848. // Make sure we check for the extension when the user clicks again.
  2849. firefoxExtInstalled = null;
  2850. reDetectFirefoxExtension = true;
  2851. // Prompt the user to install the extension
  2852. this.eventEmitter.emit(
  2853. DesktopSharingEventTypes.FIREFOX_EXTENSION_NEEDED,
  2854. this.options.desktopSharingFirefoxExtensionURL);
  2855. // Make sure desktopsharing knows that we failed, so that it doesn't get
  2856. // stuck in 'switching' mode.
  2857. errorCallback('Firefox extension required.');
  2858. },
  2859. /**
  2860. * Asks Chrome extension to call chooseDesktopMedia and gets chrome
  2861. * 'desktop' stream for returned stream token.
  2862. */
  2863. obtainScreenFromExtension: function (streamCallback, failCallback) {
  2864. if (chromeExtInstalled) {
  2865. doGetStreamFromExtension(this.options, streamCallback,
  2866. failCallback);
  2867. } else {
  2868. if (chromeExtUpdateRequired) {
  2869. alert(
  2870. 'Jitsi Desktop Streamer requires update. ' +
  2871. 'Changes will take effect after next Chrome restart.');
  2872. }
  2873. chrome.webstore.install(
  2874. getWebStoreInstallUrl(this.options),
  2875. function (arg) {
  2876. logger.log("Extension installed successfully", arg);
  2877. chromeExtInstalled = true;
  2878. // We need to give a moment for the endpoint to become
  2879. // available
  2880. window.setTimeout(function () {
  2881. doGetStreamFromExtension(this.options, streamCallback,
  2882. failCallback);
  2883. }, 500);
  2884. },
  2885. function (arg) {
  2886. logger.log("Failed to install the extension", arg);
  2887. failCallback(arg);
  2888. }
  2889. );
  2890. }
  2891. }
  2892. };
  2893. /**
  2894. * Obtains a desktop stream using getUserMedia.
  2895. * For this to work on Chrome, the
  2896. * 'chrome://flags/#enable-usermedia-screen-capture' flag must be enabled.
  2897. *
  2898. * On firefox, the document's domain must be white-listed in the
  2899. * 'media.getusermedia.screensharing.allowed_domains' preference in
  2900. * 'about:config'.
  2901. */
  2902. function obtainWebRTCScreen(streamCallback, failCallback) {
  2903. GUM(
  2904. ['screen'],
  2905. streamCallback,
  2906. failCallback
  2907. );
  2908. }
  2909. /**
  2910. * Constructs inline install URL for Chrome desktop streaming extension.
  2911. * The 'chromeExtensionId' must be defined in options parameter.
  2912. * @param options supports "desktopSharingChromeExtId" and "chromeExtensionId"
  2913. * @returns {string}
  2914. */
  2915. function getWebStoreInstallUrl(options)
  2916. {
  2917. //TODO remove chromeExtensionId (deprecated)
  2918. return "https://chrome.google.com/webstore/detail/" +
  2919. (options.desktopSharingChromeExtId || options.chromeExtensionId);
  2920. }
  2921. /**
  2922. * Checks whether an update of the Chrome extension is required.
  2923. * @param minVersion minimal required version
  2924. * @param extVersion current extension version
  2925. * @returns {boolean}
  2926. */
  2927. function isUpdateRequired(minVersion, extVersion) {
  2928. try {
  2929. var s1 = minVersion.split('.');
  2930. var s2 = extVersion.split('.');
  2931. var len = Math.max(s1.length, s2.length);
  2932. for (var i = 0; i < len; i++) {
  2933. var n1 = 0,
  2934. n2 = 0;
  2935. if (i < s1.length)
  2936. n1 = parseInt(s1[i]);
  2937. if (i < s2.length)
  2938. n2 = parseInt(s2[i]);
  2939. if (isNaN(n1) || isNaN(n2)) {
  2940. return true;
  2941. } else if (n1 !== n2) {
  2942. return n1 > n2;
  2943. }
  2944. }
  2945. // will happen if both versions have identical numbers in
  2946. // their components (even if one of them is longer, has more components)
  2947. return false;
  2948. }
  2949. catch (e) {
  2950. logger.error("Failed to parse extension version", e);
  2951. return true;
  2952. }
  2953. }
  2954. function checkChromeExtInstalled(callback, options) {
  2955. if (!chrome || !chrome.runtime) {
  2956. // No API, so no extension for sure
  2957. callback(false, false);
  2958. return;
  2959. }
  2960. chrome.runtime.sendMessage(
  2961. //TODO: remove chromeExtensionId (deprecated)
  2962. (options.desktopSharingChromeExtId || options.chromeExtensionId),
  2963. { getVersion: true },
  2964. function (response) {
  2965. if (!response || !response.version) {
  2966. // Communication failure - assume that no endpoint exists
  2967. logger.warn(
  2968. "Extension not installed?: ", chrome.runtime.lastError);
  2969. callback(false, false);
  2970. return;
  2971. }
  2972. // Check installed extension version
  2973. var extVersion = response.version;
  2974. logger.log('Extension version is: ' + extVersion);
  2975. //TODO: remove minChromeExtVersion (deprecated)
  2976. var updateRequired
  2977. = isUpdateRequired(
  2978. (options.desktopSharingChromeMinExtVersion ||
  2979. options.minChromeExtVersion),
  2980. extVersion);
  2981. callback(!updateRequired, updateRequired);
  2982. }
  2983. );
  2984. }
  2985. function doGetStreamFromExtension(options, streamCallback, failCallback) {
  2986. // Sends 'getStream' msg to the extension.
  2987. // Extension id must be defined in the config.
  2988. chrome.runtime.sendMessage(
  2989. //TODO: remove chromeExtensionId (deprecated)
  2990. (options.desktopSharingChromeExtId || options.chromeExtensionId),
  2991. {
  2992. getStream: true,
  2993. //TODO: remove desktopSharingSources (deprecated).
  2994. sources: (options.desktopSharingChromeSources ||
  2995. options.desktopSharingSources)
  2996. },
  2997. function (response) {
  2998. if (!response) {
  2999. failCallback(chrome.runtime.lastError);
  3000. return;
  3001. }
  3002. logger.log("Response from extension: " + response);
  3003. if (response.streamId) {
  3004. GUM(
  3005. ['desktop'],
  3006. function (stream) {
  3007. streamCallback(stream);
  3008. },
  3009. failCallback,
  3010. {desktopStream: response.streamId});
  3011. } else {
  3012. failCallback("Extension failed to get the stream");
  3013. }
  3014. }
  3015. );
  3016. }
  3017. /**
  3018. * Initializes <link rel=chrome-webstore-item /> with extension id set in
  3019. * config.js to support inline installs. Host site must be selected as main
  3020. * website of published extension.
  3021. * @param options supports "desktopSharingChromeExtId" and "chromeExtensionId"
  3022. */
  3023. function initInlineInstalls(options)
  3024. {
  3025. $("link[rel=chrome-webstore-item]").attr("href",
  3026. getWebStoreInstallUrl(options));
  3027. }
  3028. function initChromeExtension(options) {
  3029. // Initialize Chrome extension inline installs
  3030. initInlineInstalls(options);
  3031. // Check if extension is installed
  3032. checkChromeExtInstalled(function (installed, updateRequired) {
  3033. chromeExtInstalled = installed;
  3034. chromeExtUpdateRequired = updateRequired;
  3035. logger.info(
  3036. "Chrome extension installed: " + chromeExtInstalled +
  3037. " updateRequired: " + chromeExtUpdateRequired);
  3038. }, options);
  3039. }
  3040. /**
  3041. * Starts the detection of an installed jidesha extension for firefox.
  3042. * @param options supports "desktopSharingFirefoxDisabled",
  3043. * "desktopSharingFirefoxExtId" and "chromeExtensionId"
  3044. */
  3045. function initFirefoxExtensionDetection(options) {
  3046. if (options.desktopSharingFirefoxDisabled) {
  3047. return;
  3048. }
  3049. if (firefoxExtInstalled === false || firefoxExtInstalled === true)
  3050. return;
  3051. if (!options.desktopSharingFirefoxExtId) {
  3052. firefoxExtInstalled = false;
  3053. return;
  3054. }
  3055. var img = document.createElement('img');
  3056. img.onload = function(){
  3057. logger.log("Detected firefox screen sharing extension.");
  3058. firefoxExtInstalled = true;
  3059. };
  3060. img.onerror = function(){
  3061. logger.log("Detected lack of firefox screen sharing extension.");
  3062. firefoxExtInstalled = false;
  3063. };
  3064. // The jidesha extension exposes an empty image file under the url:
  3065. // "chrome://EXT_ID/content/DOMAIN.png"
  3066. // Where EXT_ID is the ID of the extension with "@" replaced by ".", and
  3067. // DOMAIN is a domain whitelisted by the extension.
  3068. var src = "chrome://" +
  3069. (options.desktopSharingFirefoxExtId.replace('@', '.')) +
  3070. "/content/" + document.location.hostname + ".png";
  3071. img.setAttribute('src', src);
  3072. }
  3073. module.exports = ScreenObtainer;
  3074. }).call(this,"/modules/RTC/ScreenObtainer.js")
  3075. },{"../../service/desktopsharing/DesktopSharingEventTypes":88,"./RTCBrowserType":17,"./adapter.screenshare":20,"jitsi-meet-logger":48}],20:[function(require,module,exports){
  3076. (function (__filename){
  3077. /*! adapterjs - v0.12.0 - 2015-09-04 */
  3078. var console = require("jitsi-meet-logger").getLogger(__filename);
  3079. // Adapter's interface.
  3080. var AdapterJS = AdapterJS || {};
  3081. // Browserify compatibility
  3082. if(typeof exports !== 'undefined') {
  3083. module.exports = AdapterJS;
  3084. }
  3085. AdapterJS.options = AdapterJS.options || {};
  3086. // uncomment to get virtual webcams
  3087. // AdapterJS.options.getAllCams = true;
  3088. // uncomment to prevent the install prompt when the plugin in not yet installed
  3089. // AdapterJS.options.hidePluginInstallPrompt = true;
  3090. // AdapterJS version
  3091. AdapterJS.VERSION = '0.12.0';
  3092. // This function will be called when the WebRTC API is ready to be used
  3093. // Whether it is the native implementation (Chrome, Firefox, Opera) or
  3094. // the plugin
  3095. // You may Override this function to synchronise the start of your application
  3096. // with the WebRTC API being ready.
  3097. // If you decide not to override use this synchronisation, it may result in
  3098. // an extensive CPU usage on the plugin start (once per tab loaded)
  3099. // Params:
  3100. // - isUsingPlugin: true is the WebRTC plugin is being used, false otherwise
  3101. //
  3102. AdapterJS.onwebrtcready = AdapterJS.onwebrtcready || function(isUsingPlugin) {
  3103. // The WebRTC API is ready.
  3104. // Override me and do whatever you want here
  3105. };
  3106. // Sets a callback function to be called when the WebRTC interface is ready.
  3107. // The first argument is the function to callback.\
  3108. // Throws an error if the first argument is not a function
  3109. AdapterJS.webRTCReady = function (callback) {
  3110. if (typeof callback !== 'function') {
  3111. throw new Error('Callback provided is not a function');
  3112. }
  3113. if (true === AdapterJS.onwebrtcreadyDone) {
  3114. // All WebRTC interfaces are ready, just call the callback
  3115. callback(null !== AdapterJS.WebRTCPlugin.plugin);
  3116. } else {
  3117. // will be triggered automatically when your browser/plugin is ready.
  3118. AdapterJS.onwebrtcready = callback;
  3119. }
  3120. };
  3121. // Plugin namespace
  3122. AdapterJS.WebRTCPlugin = AdapterJS.WebRTCPlugin || {};
  3123. // The object to store plugin information
  3124. AdapterJS.WebRTCPlugin.pluginInfo = {
  3125. prefix : 'Tem',
  3126. plugName : 'TemWebRTCPlugin',
  3127. pluginId : 'plugin0',
  3128. type : 'application/x-temwebrtcplugin',
  3129. onload : '__TemWebRTCReady0',
  3130. portalLink : 'http://skylink.io/plugin/',
  3131. downloadLink : null, //set below
  3132. companyName: 'Temasys'
  3133. };
  3134. if(!!navigator.platform.match(/^Mac/i)) {
  3135. AdapterJS.WebRTCPlugin.pluginInfo.downloadLink = 'http://bit.ly/1n77hco';
  3136. }
  3137. else if(!!navigator.platform.match(/^Win/i)) {
  3138. AdapterJS.WebRTCPlugin.pluginInfo.downloadLink = 'http://bit.ly/1kkS4FN';
  3139. }
  3140. AdapterJS.WebRTCPlugin.TAGS = {
  3141. NONE : 'none',
  3142. AUDIO : 'audio',
  3143. VIDEO : 'video'
  3144. };
  3145. // Unique identifier of each opened page
  3146. AdapterJS.WebRTCPlugin.pageId = Math.random().toString(36).slice(2);
  3147. // Use this whenever you want to call the plugin.
  3148. AdapterJS.WebRTCPlugin.plugin = null;
  3149. // Set log level for the plugin once it is ready.
  3150. // The different values are
  3151. // This is an asynchronous function that will run when the plugin is ready
  3152. AdapterJS.WebRTCPlugin.setLogLevel = null;
  3153. // Defines webrtc's JS interface according to the plugin's implementation.
  3154. // Define plugin Browsers as WebRTC Interface.
  3155. AdapterJS.WebRTCPlugin.defineWebRTCInterface = null;
  3156. // This function detects whether or not a plugin is installed.
  3157. // Checks if Not IE (firefox, for example), else if it's IE,
  3158. // we're running IE and do something. If not it is not supported.
  3159. AdapterJS.WebRTCPlugin.isPluginInstalled = null;
  3160. // Lets adapter.js wait until the the document is ready before injecting the plugin
  3161. AdapterJS.WebRTCPlugin.pluginInjectionInterval = null;
  3162. // Inject the HTML DOM object element into the page.
  3163. AdapterJS.WebRTCPlugin.injectPlugin = null;
  3164. // States of readiness that the plugin goes through when
  3165. // being injected and stated
  3166. AdapterJS.WebRTCPlugin.PLUGIN_STATES = {
  3167. NONE : 0, // no plugin use
  3168. INITIALIZING : 1, // Detected need for plugin
  3169. INJECTING : 2, // Injecting plugin
  3170. INJECTED: 3, // Plugin element injected but not usable yet
  3171. READY: 4 // Plugin ready to be used
  3172. };
  3173. // Current state of the plugin. You cannot use the plugin before this is
  3174. // equal to AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY
  3175. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.NONE;
  3176. // True is AdapterJS.onwebrtcready was already called, false otherwise
  3177. // Used to make sure AdapterJS.onwebrtcready is only called once
  3178. AdapterJS.onwebrtcreadyDone = false;
  3179. // Log levels for the plugin.
  3180. // To be set by calling AdapterJS.WebRTCPlugin.setLogLevel
  3181. /*
  3182. Log outputs are prefixed in some cases.
  3183. INFO: Information reported by the plugin.
  3184. ERROR: Errors originating from within the plugin.
  3185. WEBRTC: Error originating from within the libWebRTC library
  3186. */
  3187. // From the least verbose to the most verbose
  3188. AdapterJS.WebRTCPlugin.PLUGIN_LOG_LEVELS = {
  3189. NONE : 'NONE',
  3190. ERROR : 'ERROR',
  3191. WARNING : 'WARNING',
  3192. INFO: 'INFO',
  3193. VERBOSE: 'VERBOSE',
  3194. SENSITIVE: 'SENSITIVE'
  3195. };
  3196. // Does a waiting check before proceeding to load the plugin.
  3197. AdapterJS.WebRTCPlugin.WaitForPluginReady = null;
  3198. // This methid will use an interval to wait for the plugin to be ready.
  3199. AdapterJS.WebRTCPlugin.callWhenPluginReady = null;
  3200. // !!!! WARNING: DO NOT OVERRIDE THIS FUNCTION. !!!
  3201. // This function will be called when plugin is ready. It sends necessary
  3202. // details to the plugin.
  3203. // The function will wait for the document to be ready and the set the
  3204. // plugin state to AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY,
  3205. // indicating that it can start being requested.
  3206. // This function is not in the IE/Safari condition brackets so that
  3207. // TemPluginLoaded function might be called on Chrome/Firefox.
  3208. // This function is the only private function that is not encapsulated to
  3209. // allow the plugin method to be called.
  3210. __TemWebRTCReady0 = function () {
  3211. if (document.readyState === 'complete') {
  3212. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY;
  3213. AdapterJS.maybeThroughWebRTCReady();
  3214. } else {
  3215. AdapterJS.WebRTCPlugin.documentReadyInterval = setInterval(function () {
  3216. if (document.readyState === 'complete') {
  3217. // TODO: update comments, we wait for the document to be ready
  3218. clearInterval(AdapterJS.WebRTCPlugin.documentReadyInterval);
  3219. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY;
  3220. AdapterJS.maybeThroughWebRTCReady();
  3221. }
  3222. }, 100);
  3223. }
  3224. };
  3225. AdapterJS.maybeThroughWebRTCReady = function() {
  3226. if (!AdapterJS.onwebrtcreadyDone) {
  3227. AdapterJS.onwebrtcreadyDone = true;
  3228. if (typeof(AdapterJS.onwebrtcready) === 'function') {
  3229. AdapterJS.onwebrtcready(AdapterJS.WebRTCPlugin.plugin !== null);
  3230. }
  3231. }
  3232. };
  3233. // Text namespace
  3234. AdapterJS.TEXT = {
  3235. PLUGIN: {
  3236. REQUIRE_INSTALLATION: 'This website requires you to install a WebRTC-enabling plugin ' +
  3237. 'to work on this browser.',
  3238. NOT_SUPPORTED: 'Your browser does not support WebRTC.',
  3239. BUTTON: 'Install Now'
  3240. },
  3241. REFRESH: {
  3242. REQUIRE_REFRESH: 'Please refresh page',
  3243. BUTTON: 'Refresh Page'
  3244. }
  3245. };
  3246. // The result of ice connection states.
  3247. // - starting: Ice connection is starting.
  3248. // - checking: Ice connection is checking.
  3249. // - connected Ice connection is connected.
  3250. // - completed Ice connection is connected.
  3251. // - done Ice connection has been completed.
  3252. // - disconnected Ice connection has been disconnected.
  3253. // - failed Ice connection has failed.
  3254. // - closed Ice connection is closed.
  3255. AdapterJS._iceConnectionStates = {
  3256. starting : 'starting',
  3257. checking : 'checking',
  3258. connected : 'connected',
  3259. completed : 'connected',
  3260. done : 'completed',
  3261. disconnected : 'disconnected',
  3262. failed : 'failed',
  3263. closed : 'closed'
  3264. };
  3265. //The IceConnection states that has been fired for each peer.
  3266. AdapterJS._iceConnectionFiredStates = [];
  3267. // Check if WebRTC Interface is defined.
  3268. AdapterJS.isDefined = null;
  3269. // This function helps to retrieve the webrtc detected browser information.
  3270. // This sets:
  3271. // - webrtcDetectedBrowser: The browser agent name.
  3272. // - webrtcDetectedVersion: The browser version.
  3273. // - webrtcDetectedType: The types of webRTC support.
  3274. // - 'moz': Mozilla implementation of webRTC.
  3275. // - 'webkit': WebKit implementation of webRTC.
  3276. // - 'plugin': Using the plugin implementation.
  3277. AdapterJS.parseWebrtcDetectedBrowser = function () {
  3278. var hasMatch, checkMatch = navigator.userAgent.match(
  3279. /(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i) || [];
  3280. if (/trident/i.test(checkMatch[1])) {
  3281. hasMatch = /\brv[ :]+(\d+)/g.exec(navigator.userAgent) || [];
  3282. webrtcDetectedBrowser = 'IE';
  3283. webrtcDetectedVersion = parseInt(hasMatch[1] || '0', 10);
  3284. } else if (checkMatch[1] === 'Chrome') {
  3285. hasMatch = navigator.userAgent.match(/\bOPR\/(\d+)/);
  3286. if (hasMatch !== null) {
  3287. webrtcDetectedBrowser = 'opera';
  3288. webrtcDetectedVersion = parseInt(hasMatch[1], 10);
  3289. }
  3290. }
  3291. if (navigator.userAgent.indexOf('Safari')) {
  3292. if (typeof InstallTrigger !== 'undefined') {
  3293. webrtcDetectedBrowser = 'firefox';
  3294. } else if (/*@cc_on!@*/ false || !!document.documentMode) {
  3295. webrtcDetectedBrowser = 'IE';
  3296. } else if (
  3297. Object.prototype.toString.call(window.HTMLElement).indexOf('Constructor') > 0) {
  3298. webrtcDetectedBrowser = 'safari';
  3299. } else if (!!window.opera || navigator.userAgent.indexOf(' OPR/') >= 0) {
  3300. webrtcDetectedBrowser = 'opera';
  3301. } else if (!!window.chrome) {
  3302. webrtcDetectedBrowser = 'chrome';
  3303. }
  3304. }
  3305. if (!webrtcDetectedBrowser) {
  3306. webrtcDetectedVersion = checkMatch[1];
  3307. }
  3308. if (!webrtcDetectedVersion) {
  3309. try {
  3310. checkMatch = (checkMatch[2]) ? [checkMatch[1], checkMatch[2]] :
  3311. [navigator.appName, navigator.appVersion, '-?'];
  3312. if ((hasMatch = navigator.userAgent.match(/version\/(\d+)/i)) !== null) {
  3313. checkMatch.splice(1, 1, hasMatch[1]);
  3314. }
  3315. webrtcDetectedVersion = parseInt(checkMatch[1], 10);
  3316. } catch (error) { }
  3317. }
  3318. };
  3319. // To fix configuration as some browsers does not support
  3320. // the 'urls' attribute.
  3321. AdapterJS.maybeFixConfiguration = function (pcConfig) {
  3322. if (pcConfig === null) {
  3323. return;
  3324. }
  3325. for (var i = 0; i < pcConfig.iceServers.length; i++) {
  3326. if (pcConfig.iceServers[i].hasOwnProperty('urls')) {
  3327. pcConfig.iceServers[i].url = pcConfig.iceServers[i].urls;
  3328. delete pcConfig.iceServers[i].urls;
  3329. }
  3330. }
  3331. };
  3332. AdapterJS.addEvent = function(elem, evnt, func) {
  3333. if (elem.addEventListener) { // W3C DOM
  3334. elem.addEventListener(evnt, func, false);
  3335. } else if (elem.attachEvent) {// OLD IE DOM
  3336. elem.attachEvent('on'+evnt, func);
  3337. } else { // No much to do
  3338. elem[evnt] = func;
  3339. }
  3340. };
  3341. AdapterJS.renderNotificationBar = function (text, buttonText, buttonLink, openNewTab, displayRefreshBar) {
  3342. // only inject once the page is ready
  3343. if (document.readyState !== 'complete') {
  3344. return;
  3345. }
  3346. var w = window;
  3347. var i = document.createElement('iframe');
  3348. i.style.position = 'fixed';
  3349. i.style.top = '-41px';
  3350. i.style.left = 0;
  3351. i.style.right = 0;
  3352. i.style.width = '100%';
  3353. i.style.height = '40px';
  3354. i.style.backgroundColor = '#ffffe1';
  3355. i.style.border = 'none';
  3356. i.style.borderBottom = '1px solid #888888';
  3357. i.style.zIndex = '9999999';
  3358. if(typeof i.style.webkitTransition === 'string') {
  3359. i.style.webkitTransition = 'all .5s ease-out';
  3360. } else if(typeof i.style.transition === 'string') {
  3361. i.style.transition = 'all .5s ease-out';
  3362. }
  3363. document.body.appendChild(i);
  3364. c = (i.contentWindow) ? i.contentWindow :
  3365. (i.contentDocument.document) ? i.contentDocument.document : i.contentDocument;
  3366. c.document.open();
  3367. c.document.write('<span style="display: inline-block; font-family: Helvetica, Arial,' +
  3368. 'sans-serif; font-size: .9rem; padding: 4px; vertical-align: ' +
  3369. 'middle; cursor: default;">' + text + '</span>');
  3370. if(buttonText && buttonLink) {
  3371. c.document.write('<button id="okay">' + buttonText + '</button><button id="cancel">Cancel</button>');
  3372. c.document.close();
  3373. // On click on okay
  3374. AdapterJS.addEvent(c.document.getElementById('okay'), 'click', function(e) {
  3375. if (!!displayRefreshBar) {
  3376. AdapterJS.renderNotificationBar(AdapterJS.TEXT.EXTENSION ?
  3377. AdapterJS.TEXT.EXTENSION.REQUIRE_REFRESH : AdapterJS.TEXT.REFRESH.REQUIRE_REFRESH,
  3378. AdapterJS.TEXT.REFRESH.BUTTON, 'javascript:location.reload()');
  3379. }
  3380. window.open(buttonLink, !!openNewTab ? '_blank' : '_top');
  3381. e.preventDefault();
  3382. try {
  3383. event.cancelBubble = true;
  3384. } catch(error) { }
  3385. var pluginInstallInterval = setInterval(function(){
  3386. if(! isIE) {
  3387. navigator.plugins.refresh(false);
  3388. }
  3389. AdapterJS.WebRTCPlugin.isPluginInstalled(
  3390. AdapterJS.WebRTCPlugin.pluginInfo.prefix,
  3391. AdapterJS.WebRTCPlugin.pluginInfo.plugName,
  3392. function() { // plugin now installed
  3393. clearInterval(pluginInstallInterval);
  3394. AdapterJS.WebRTCPlugin.defineWebRTCInterface();
  3395. },
  3396. function() {
  3397. // still no plugin detected, nothing to do
  3398. });
  3399. } , 500);
  3400. });
  3401. // On click on Cancel
  3402. AdapterJS.addEvent(c.document.getElementById('cancel'), 'click', function(e) {
  3403. w.document.body.removeChild(i);
  3404. });
  3405. } else {
  3406. c.document.close();
  3407. }
  3408. setTimeout(function() {
  3409. if(typeof i.style.webkitTransform === 'string') {
  3410. i.style.webkitTransform = 'translateY(40px)';
  3411. } else if(typeof i.style.transform === 'string') {
  3412. i.style.transform = 'translateY(40px)';
  3413. } else {
  3414. i.style.top = '0px';
  3415. }
  3416. }, 300);
  3417. };
  3418. // -----------------------------------------------------------
  3419. // Detected webrtc implementation. Types are:
  3420. // - 'moz': Mozilla implementation of webRTC.
  3421. // - 'webkit': WebKit implementation of webRTC.
  3422. // - 'plugin': Using the plugin implementation.
  3423. webrtcDetectedType = null;
  3424. // Detected webrtc datachannel support. Types are:
  3425. // - 'SCTP': SCTP datachannel support.
  3426. // - 'RTP': RTP datachannel support.
  3427. webrtcDetectedDCSupport = null;
  3428. // Set the settings for creating DataChannels, MediaStream for
  3429. // Cross-browser compability.
  3430. // - This is only for SCTP based support browsers.
  3431. // the 'urls' attribute.
  3432. checkMediaDataChannelSettings =
  3433. function (peerBrowserAgent, peerBrowserVersion, callback, constraints) {
  3434. if (typeof callback !== 'function') {
  3435. return;
  3436. }
  3437. var beOfferer = true;
  3438. var isLocalFirefox = webrtcDetectedBrowser === 'firefox';
  3439. // Nightly version does not require MozDontOfferDataChannel for interop
  3440. var isLocalFirefoxInterop = webrtcDetectedType === 'moz' && webrtcDetectedVersion > 30;
  3441. var isPeerFirefox = peerBrowserAgent === 'firefox';
  3442. var isPeerFirefoxInterop = peerBrowserAgent === 'firefox' &&
  3443. ((peerBrowserVersion) ? (peerBrowserVersion > 30) : false);
  3444. // Resends an updated version of constraints for MozDataChannel to work
  3445. // If other userAgent is firefox and user is firefox, remove MozDataChannel
  3446. if ((isLocalFirefox && isPeerFirefox) || (isLocalFirefoxInterop)) {
  3447. try {
  3448. delete constraints.mandatory.MozDontOfferDataChannel;
  3449. } catch (error) {
  3450. console.error('Failed deleting MozDontOfferDataChannel');
  3451. console.error(error);
  3452. }
  3453. } else if ((isLocalFirefox && !isPeerFirefox)) {
  3454. constraints.mandatory.MozDontOfferDataChannel = true;
  3455. }
  3456. if (!isLocalFirefox) {
  3457. // temporary measure to remove Moz* constraints in non Firefox browsers
  3458. for (var prop in constraints.mandatory) {
  3459. if (constraints.mandatory.hasOwnProperty(prop)) {
  3460. if (prop.indexOf('Moz') !== -1) {
  3461. delete constraints.mandatory[prop];
  3462. }
  3463. }
  3464. }
  3465. }
  3466. // Firefox (not interopable) cannot offer DataChannel as it will cause problems to the
  3467. // interopability of the media stream
  3468. if (isLocalFirefox && !isPeerFirefox && !isLocalFirefoxInterop) {
  3469. beOfferer = false;
  3470. }
  3471. callback(beOfferer, constraints);
  3472. };
  3473. // Handles the differences for all browsers ice connection state output.
  3474. // - Tested outcomes are:
  3475. // - Chrome (offerer) : 'checking' > 'completed' > 'completed'
  3476. // - Chrome (answerer) : 'checking' > 'connected'
  3477. // - Firefox (offerer) : 'checking' > 'connected'
  3478. // - Firefox (answerer): 'checking' > 'connected'
  3479. checkIceConnectionState = function (peerId, iceConnectionState, callback) {
  3480. if (typeof callback !== 'function') {
  3481. console.warn('No callback specified in checkIceConnectionState. Aborted.');
  3482. return;
  3483. }
  3484. peerId = (peerId) ? peerId : 'peer';
  3485. if (!AdapterJS._iceConnectionFiredStates[peerId] ||
  3486. iceConnectionState === AdapterJS._iceConnectionStates.disconnected ||
  3487. iceConnectionState === AdapterJS._iceConnectionStates.failed ||
  3488. iceConnectionState === AdapterJS._iceConnectionStates.closed) {
  3489. AdapterJS._iceConnectionFiredStates[peerId] = [];
  3490. }
  3491. iceConnectionState = AdapterJS._iceConnectionStates[iceConnectionState];
  3492. if (AdapterJS._iceConnectionFiredStates[peerId].indexOf(iceConnectionState) < 0) {
  3493. AdapterJS._iceConnectionFiredStates[peerId].push(iceConnectionState);
  3494. if (iceConnectionState === AdapterJS._iceConnectionStates.connected) {
  3495. setTimeout(function () {
  3496. AdapterJS._iceConnectionFiredStates[peerId]
  3497. .push(AdapterJS._iceConnectionStates.done);
  3498. callback(AdapterJS._iceConnectionStates.done);
  3499. }, 1000);
  3500. }
  3501. callback(iceConnectionState);
  3502. }
  3503. return;
  3504. };
  3505. // Firefox:
  3506. // - Creates iceServer from the url for Firefox.
  3507. // - Create iceServer with stun url.
  3508. // - Create iceServer with turn url.
  3509. // - Ignore the transport parameter from TURN url for FF version <=27.
  3510. // - Return null for createIceServer if transport=tcp.
  3511. // - FF 27 and above supports transport parameters in TURN url,
  3512. // - So passing in the full url to create iceServer.
  3513. // Chrome:
  3514. // - Creates iceServer from the url for Chrome M33 and earlier.
  3515. // - Create iceServer with stun url.
  3516. // - Chrome M28 & above uses below TURN format.
  3517. // Plugin:
  3518. // - Creates Ice Server for Plugin Browsers
  3519. // - If Stun - Create iceServer with stun url.
  3520. // - Else - Create iceServer with turn url
  3521. // - This is a WebRTC Function
  3522. createIceServer = null;
  3523. // Firefox:
  3524. // - Creates IceServers for Firefox
  3525. // - Use .url for FireFox.
  3526. // - Multiple Urls support
  3527. // Chrome:
  3528. // - Creates iceServers from the urls for Chrome M34 and above.
  3529. // - .urls is supported since Chrome M34.
  3530. // - Multiple Urls support
  3531. // Plugin:
  3532. // - Creates Ice Servers for Plugin Browsers
  3533. // - Multiple Urls support
  3534. // - This is a WebRTC Function
  3535. createIceServers = null;
  3536. //------------------------------------------------------------
  3537. //The RTCPeerConnection object.
  3538. RTCPeerConnection = null;
  3539. // Creates RTCSessionDescription object for Plugin Browsers
  3540. RTCSessionDescription = (typeof RTCSessionDescription === 'function') ?
  3541. RTCSessionDescription : null;
  3542. // Creates RTCIceCandidate object for Plugin Browsers
  3543. RTCIceCandidate = (typeof RTCIceCandidate === 'function') ?
  3544. RTCIceCandidate : null;
  3545. // Get UserMedia (only difference is the prefix).
  3546. // Code from Adam Barth.
  3547. getUserMedia = null;
  3548. // Attach a media stream to an element.
  3549. attachMediaStream = null;
  3550. // Re-attach a media stream to an element.
  3551. reattachMediaStream = null;
  3552. // Detected browser agent name. Types are:
  3553. // - 'firefox': Firefox browser.
  3554. // - 'chrome': Chrome browser.
  3555. // - 'opera': Opera browser.
  3556. // - 'safari': Safari browser.
  3557. // - 'IE' - Internet Explorer browser.
  3558. webrtcDetectedBrowser = null;
  3559. // Detected browser version.
  3560. webrtcDetectedVersion = null;
  3561. // Check for browser types and react accordingly
  3562. if (navigator.mozGetUserMedia) {
  3563. webrtcDetectedBrowser = 'firefox';
  3564. webrtcDetectedVersion = parseInt(navigator
  3565. .userAgent.match(/Firefox\/([0-9]+)\./)[1], 10);
  3566. webrtcDetectedType = 'moz';
  3567. webrtcDetectedDCSupport = 'SCTP';
  3568. RTCPeerConnection = function (pcConfig, pcConstraints) {
  3569. AdapterJS.maybeFixConfiguration(pcConfig);
  3570. return new mozRTCPeerConnection(pcConfig, pcConstraints);
  3571. };
  3572. // The RTCSessionDescription object.
  3573. RTCSessionDescription = mozRTCSessionDescription;
  3574. window.RTCSessionDescription = RTCSessionDescription;
  3575. // The RTCIceCandidate object.
  3576. RTCIceCandidate = mozRTCIceCandidate;
  3577. window.RTCIceCandidate = RTCIceCandidate;
  3578. window.getUserMedia = navigator.mozGetUserMedia.bind(navigator);
  3579. navigator.getUserMedia = window.getUserMedia;
  3580. // Shim for MediaStreamTrack.getSources.
  3581. MediaStreamTrack.getSources = function(successCb) {
  3582. setTimeout(function() {
  3583. var infos = [
  3584. { kind: 'audio', id: 'default', label:'', facing:'' },
  3585. { kind: 'video', id: 'default', label:'', facing:'' }
  3586. ];
  3587. successCb(infos);
  3588. }, 0);
  3589. };
  3590. createIceServer = function (url, username, password) {
  3591. var iceServer = null;
  3592. var url_parts = url.split(':');
  3593. if (url_parts[0].indexOf('stun') === 0) {
  3594. iceServer = { url : url };
  3595. } else if (url_parts[0].indexOf('turn') === 0) {
  3596. if (webrtcDetectedVersion < 27) {
  3597. var turn_url_parts = url.split('?');
  3598. if (turn_url_parts.length === 1 ||
  3599. turn_url_parts[1].indexOf('transport=udp') === 0) {
  3600. iceServer = {
  3601. url : turn_url_parts[0],
  3602. credential : password,
  3603. username : username
  3604. };
  3605. }
  3606. } else {
  3607. iceServer = {
  3608. url : url,
  3609. credential : password,
  3610. username : username
  3611. };
  3612. }
  3613. }
  3614. return iceServer;
  3615. };
  3616. createIceServers = function (urls, username, password) {
  3617. var iceServers = [];
  3618. for (i = 0; i < urls.length; i++) {
  3619. var iceServer = createIceServer(urls[i], username, password);
  3620. if (iceServer !== null) {
  3621. iceServers.push(iceServer);
  3622. }
  3623. }
  3624. return iceServers;
  3625. };
  3626. attachMediaStream = function (element, stream) {
  3627. element.mozSrcObject = stream;
  3628. if (stream !== null)
  3629. element.play();
  3630. return element;
  3631. };
  3632. reattachMediaStream = function (to, from) {
  3633. to.mozSrcObject = from.mozSrcObject;
  3634. to.play();
  3635. return to;
  3636. };
  3637. MediaStreamTrack.getSources = MediaStreamTrack.getSources || function (callback) {
  3638. if (!callback) {
  3639. throw new TypeError('Failed to execute \'getSources\' on \'MediaStreamTrack\'' +
  3640. ': 1 argument required, but only 0 present.');
  3641. }
  3642. return callback([]);
  3643. };
  3644. // Fake get{Video,Audio}Tracks
  3645. if (!MediaStream.prototype.getVideoTracks) {
  3646. MediaStream.prototype.getVideoTracks = function () {
  3647. return [];
  3648. };
  3649. }
  3650. if (!MediaStream.prototype.getAudioTracks) {
  3651. MediaStream.prototype.getAudioTracks = function () {
  3652. return [];
  3653. };
  3654. }
  3655. AdapterJS.maybeThroughWebRTCReady();
  3656. } else if (navigator.webkitGetUserMedia) {
  3657. webrtcDetectedBrowser = 'chrome';
  3658. webrtcDetectedType = 'webkit';
  3659. webrtcDetectedVersion = parseInt(navigator
  3660. .userAgent.match(/Chrom(e|ium)\/([0-9]+)\./)[2], 10);
  3661. // check if browser is opera 20+
  3662. var checkIfOpera = navigator.userAgent.match(/\bOPR\/(\d+)/);
  3663. if (checkIfOpera !== null) {
  3664. webrtcDetectedBrowser = 'opera';
  3665. webrtcDetectedVersion = parseInt(checkIfOpera[1], 10);
  3666. }
  3667. // check browser datachannel support
  3668. if ((webrtcDetectedBrowser === 'chrome' && webrtcDetectedVersion >= 31) ||
  3669. (webrtcDetectedBrowser === 'opera' && webrtcDetectedVersion >= 20)) {
  3670. webrtcDetectedDCSupport = 'SCTP';
  3671. } else if (webrtcDetectedBrowser === 'chrome' && webrtcDetectedVersion < 30 &&
  3672. webrtcDetectedVersion > 24) {
  3673. webrtcDetectedDCSupport = 'RTP';
  3674. } else {
  3675. webrtcDetectedDCSupport = '';
  3676. }
  3677. createIceServer = function (url, username, password) {
  3678. var iceServer = null;
  3679. var url_parts = url.split(':');
  3680. if (url_parts[0].indexOf('stun') === 0) {
  3681. iceServer = { 'url' : url };
  3682. } else if (url_parts[0].indexOf('turn') === 0) {
  3683. iceServer = {
  3684. 'url' : url,
  3685. 'credential' : password,
  3686. 'username' : username
  3687. };
  3688. }
  3689. return iceServer;
  3690. };
  3691. createIceServers = function (urls, username, password) {
  3692. var iceServers = [];
  3693. if (webrtcDetectedVersion >= 34) {
  3694. iceServers = {
  3695. 'urls' : urls,
  3696. 'credential' : password,
  3697. 'username' : username
  3698. };
  3699. } else {
  3700. for (i = 0; i < urls.length; i++) {
  3701. var iceServer = createIceServer(urls[i], username, password);
  3702. if (iceServer !== null) {
  3703. iceServers.push(iceServer);
  3704. }
  3705. }
  3706. }
  3707. return iceServers;
  3708. };
  3709. RTCPeerConnection = function (pcConfig, pcConstraints) {
  3710. if (webrtcDetectedVersion < 34) {
  3711. AdapterJS.maybeFixConfiguration(pcConfig);
  3712. }
  3713. return new webkitRTCPeerConnection(pcConfig, pcConstraints);
  3714. };
  3715. window.getUserMedia = navigator.webkitGetUserMedia.bind(navigator);
  3716. navigator.getUserMedia = window.getUserMedia;
  3717. attachMediaStream = function (element, stream) {
  3718. if (typeof element.srcObject !== 'undefined') {
  3719. element.srcObject = stream;
  3720. } else if (typeof element.mozSrcObject !== 'undefined') {
  3721. element.mozSrcObject = stream;
  3722. } else if (typeof element.src !== 'undefined') {
  3723. element.src = (stream === null ? '' : URL.createObjectURL(stream));
  3724. } else {
  3725. console.log('Error attaching stream to element.');
  3726. }
  3727. return element;
  3728. };
  3729. reattachMediaStream = function (to, from) {
  3730. to.src = from.src;
  3731. return to;
  3732. };
  3733. AdapterJS.maybeThroughWebRTCReady();
  3734. } else if (navigator.mediaDevices && navigator.userAgent.match(
  3735. /Edge\/(\d+).(\d+)$/)) {
  3736. webrtcDetectedBrowser = 'edge';
  3737. webrtcDetectedVersion =
  3738. parseInt(navigator.userAgent.match(/Edge\/(\d+).(\d+)$/)[2], 10);
  3739. // the minimum version still supported by adapter.
  3740. webrtcMinimumVersion = 12;
  3741. window.getUserMedia = navigator.getUserMedia.bind(navigator);
  3742. attachMediaStream = function(element, stream) {
  3743. element.srcObject = stream;
  3744. return element;
  3745. };
  3746. reattachMediaStream = function(to, from) {
  3747. to.srcObject = from.srcObject;
  3748. return to;
  3749. };
  3750. AdapterJS.maybeThroughWebRTCReady();
  3751. } else { // TRY TO USE PLUGIN
  3752. // IE 9 is not offering an implementation of console.log until you open a console
  3753. if (typeof console !== 'object' || typeof console.log !== 'function') {
  3754. /* jshint -W020 */
  3755. console = {} || console;
  3756. // Implemented based on console specs from MDN
  3757. // You may override these functions
  3758. console.log = function (arg) {};
  3759. console.info = function (arg) {};
  3760. console.error = function (arg) {};
  3761. console.dir = function (arg) {};
  3762. console.exception = function (arg) {};
  3763. console.trace = function (arg) {};
  3764. console.warn = function (arg) {};
  3765. console.count = function (arg) {};
  3766. console.debug = function (arg) {};
  3767. console.count = function (arg) {};
  3768. console.time = function (arg) {};
  3769. console.timeEnd = function (arg) {};
  3770. console.group = function (arg) {};
  3771. console.groupCollapsed = function (arg) {};
  3772. console.groupEnd = function (arg) {};
  3773. /* jshint +W020 */
  3774. }
  3775. webrtcDetectedType = 'plugin';
  3776. webrtcDetectedDCSupport = 'plugin';
  3777. AdapterJS.parseWebrtcDetectedBrowser();
  3778. isIE = webrtcDetectedBrowser === 'IE';
  3779. /* jshint -W035 */
  3780. AdapterJS.WebRTCPlugin.WaitForPluginReady = function() {
  3781. while (AdapterJS.WebRTCPlugin.pluginState !== AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY) {
  3782. /* empty because it needs to prevent the function from running. */
  3783. }
  3784. };
  3785. /* jshint +W035 */
  3786. AdapterJS.WebRTCPlugin.callWhenPluginReady = function (callback) {
  3787. if (AdapterJS.WebRTCPlugin.pluginState === AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY) {
  3788. // Call immediately if possible
  3789. // Once the plugin is set, the code will always take this path
  3790. callback();
  3791. } else {
  3792. // otherwise start a 100ms interval
  3793. var checkPluginReadyState = setInterval(function () {
  3794. if (AdapterJS.WebRTCPlugin.pluginState === AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY) {
  3795. clearInterval(checkPluginReadyState);
  3796. callback();
  3797. }
  3798. }, 100);
  3799. }
  3800. };
  3801. AdapterJS.WebRTCPlugin.setLogLevel = function(logLevel) {
  3802. AdapterJS.WebRTCPlugin.callWhenPluginReady(function() {
  3803. AdapterJS.WebRTCPlugin.plugin.setLogLevel(logLevel);
  3804. });
  3805. };
  3806. AdapterJS.WebRTCPlugin.injectPlugin = function () {
  3807. // only inject once the page is ready
  3808. if (document.readyState !== 'complete') {
  3809. return;
  3810. }
  3811. // Prevent multiple injections
  3812. if (AdapterJS.WebRTCPlugin.pluginState !== AdapterJS.WebRTCPlugin.PLUGIN_STATES.INITIALIZING) {
  3813. return;
  3814. }
  3815. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.INJECTING;
  3816. if (webrtcDetectedBrowser === 'IE' && webrtcDetectedVersion <= 10) {
  3817. var frag = document.createDocumentFragment();
  3818. AdapterJS.WebRTCPlugin.plugin = document.createElement('div');
  3819. AdapterJS.WebRTCPlugin.plugin.innerHTML = '<object id="' +
  3820. AdapterJS.WebRTCPlugin.pluginInfo.pluginId + '" type="' +
  3821. AdapterJS.WebRTCPlugin.pluginInfo.type + '" ' + 'width="1" height="1">' +
  3822. '<param name="pluginId" value="' +
  3823. AdapterJS.WebRTCPlugin.pluginInfo.pluginId + '" /> ' +
  3824. '<param name="windowless" value="false" /> ' +
  3825. '<param name="pageId" value="' + AdapterJS.WebRTCPlugin.pageId + '" /> ' +
  3826. '<param name="onload" value="' + AdapterJS.WebRTCPlugin.pluginInfo.onload + '" />' +
  3827. '<param name="tag" value="' + AdapterJS.WebRTCPlugin.TAGS.NONE + '" />' +
  3828. // uncomment to be able to use virtual cams
  3829. (AdapterJS.options.getAllCams ? '<param name="forceGetAllCams" value="True" />':'') +
  3830. '</object>';
  3831. while (AdapterJS.WebRTCPlugin.plugin.firstChild) {
  3832. frag.appendChild(AdapterJS.WebRTCPlugin.plugin.firstChild);
  3833. }
  3834. document.body.appendChild(frag);
  3835. // Need to re-fetch the plugin
  3836. AdapterJS.WebRTCPlugin.plugin =
  3837. document.getElementById(AdapterJS.WebRTCPlugin.pluginInfo.pluginId);
  3838. } else {
  3839. // Load Plugin
  3840. AdapterJS.WebRTCPlugin.plugin = document.createElement('object');
  3841. AdapterJS.WebRTCPlugin.plugin.id =
  3842. AdapterJS.WebRTCPlugin.pluginInfo.pluginId;
  3843. // IE will only start the plugin if it's ACTUALLY visible
  3844. if (isIE) {
  3845. AdapterJS.WebRTCPlugin.plugin.width = '1px';
  3846. AdapterJS.WebRTCPlugin.plugin.height = '1px';
  3847. } else { // The size of the plugin on Safari should be 0x0px
  3848. // so that the autorisation prompt is at the top
  3849. AdapterJS.WebRTCPlugin.plugin.width = '0px';
  3850. AdapterJS.WebRTCPlugin.plugin.height = '0px';
  3851. }
  3852. AdapterJS.WebRTCPlugin.plugin.type = AdapterJS.WebRTCPlugin.pluginInfo.type;
  3853. AdapterJS.WebRTCPlugin.plugin.innerHTML = '<param name="onload" value="' +
  3854. AdapterJS.WebRTCPlugin.pluginInfo.onload + '">' +
  3855. '<param name="pluginId" value="' +
  3856. AdapterJS.WebRTCPlugin.pluginInfo.pluginId + '">' +
  3857. '<param name="windowless" value="false" /> ' +
  3858. (AdapterJS.options.getAllCams ? '<param name="forceGetAllCams" value="True" />':'') +
  3859. '<param name="pageId" value="' + AdapterJS.WebRTCPlugin.pageId + '">' +
  3860. '<param name="tag" value="' + AdapterJS.WebRTCPlugin.TAGS.NONE + '" />';
  3861. document.body.appendChild(AdapterJS.WebRTCPlugin.plugin);
  3862. }
  3863. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.INJECTED;
  3864. };
  3865. AdapterJS.WebRTCPlugin.isPluginInstalled =
  3866. function (comName, plugName, installedCb, notInstalledCb) {
  3867. if (!isIE) {
  3868. var pluginArray = navigator.plugins;
  3869. for (var i = 0; i < pluginArray.length; i++) {
  3870. if (pluginArray[i].name.indexOf(plugName) >= 0) {
  3871. installedCb();
  3872. return;
  3873. }
  3874. }
  3875. notInstalledCb();
  3876. } else {
  3877. try {
  3878. var axo = new ActiveXObject(comName + '.' + plugName);
  3879. } catch (e) {
  3880. notInstalledCb();
  3881. return;
  3882. }
  3883. installedCb();
  3884. }
  3885. };
  3886. AdapterJS.WebRTCPlugin.defineWebRTCInterface = function () {
  3887. if (AdapterJS.WebRTCPlugin.pluginState ===
  3888. AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY) {
  3889. console.error("AdapterJS - WebRTC interface has already been defined");
  3890. return;
  3891. }
  3892. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.INITIALIZING;
  3893. AdapterJS.isDefined = function (variable) {
  3894. return variable !== null && variable !== undefined;
  3895. };
  3896. createIceServer = function (url, username, password) {
  3897. var iceServer = null;
  3898. var url_parts = url.split(':');
  3899. if (url_parts[0].indexOf('stun') === 0) {
  3900. iceServer = {
  3901. 'url' : url,
  3902. 'hasCredentials' : false
  3903. };
  3904. } else if (url_parts[0].indexOf('turn') === 0) {
  3905. iceServer = {
  3906. 'url' : url,
  3907. 'hasCredentials' : true,
  3908. 'credential' : password,
  3909. 'username' : username
  3910. };
  3911. }
  3912. return iceServer;
  3913. };
  3914. createIceServers = function (urls, username, password) {
  3915. var iceServers = [];
  3916. for (var i = 0; i < urls.length; ++i) {
  3917. iceServers.push(createIceServer(urls[i], username, password));
  3918. }
  3919. return iceServers;
  3920. };
  3921. RTCSessionDescription = function (info) {
  3922. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  3923. return AdapterJS.WebRTCPlugin.plugin.
  3924. ConstructSessionDescription(info.type, info.sdp);
  3925. };
  3926. RTCPeerConnection = function (servers, constraints) {
  3927. var iceServers = null;
  3928. if (servers) {
  3929. iceServers = servers.iceServers;
  3930. for (var i = 0; i < iceServers.length; i++) {
  3931. if (iceServers[i].urls && !iceServers[i].url) {
  3932. iceServers[i].url = iceServers[i].urls;
  3933. }
  3934. iceServers[i].hasCredentials = AdapterJS.
  3935. isDefined(iceServers[i].username) &&
  3936. AdapterJS.isDefined(iceServers[i].credential);
  3937. }
  3938. }
  3939. var mandatory = (constraints && constraints.mandatory) ?
  3940. constraints.mandatory : null;
  3941. var optional = (constraints && constraints.optional) ?
  3942. constraints.optional : null;
  3943. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  3944. return AdapterJS.WebRTCPlugin.plugin.
  3945. PeerConnection(AdapterJS.WebRTCPlugin.pageId,
  3946. iceServers, mandatory, optional);
  3947. };
  3948. MediaStreamTrack = {};
  3949. MediaStreamTrack.getSources = function (callback) {
  3950. AdapterJS.WebRTCPlugin.callWhenPluginReady(function() {
  3951. AdapterJS.WebRTCPlugin.plugin.GetSources(callback);
  3952. });
  3953. };
  3954. window.getUserMedia = function (constraints, successCallback, failureCallback) {
  3955. constraints.audio = constraints.audio || false;
  3956. constraints.video = constraints.video || false;
  3957. AdapterJS.WebRTCPlugin.callWhenPluginReady(function() {
  3958. AdapterJS.WebRTCPlugin.plugin.
  3959. getUserMedia(constraints, successCallback, failureCallback);
  3960. });
  3961. };
  3962. window.navigator.getUserMedia = window.getUserMedia;
  3963. attachMediaStream = function (element, stream) {
  3964. if (!element || !element.parentNode) {
  3965. return;
  3966. }
  3967. var streamId
  3968. if (stream === null) {
  3969. streamId = '';
  3970. }
  3971. else {
  3972. stream.enableSoundTracks(true); // TODO: remove on 0.12.0
  3973. streamId = stream.id;
  3974. }
  3975. var elementId = element.id.length === 0 ? Math.random().toString(36).slice(2) : element.id;
  3976. var nodeName = element.nodeName.toLowerCase();
  3977. if (nodeName !== 'object') { // not a plugin <object> tag yet
  3978. var tag;
  3979. switch(nodeName) {
  3980. case 'audio':
  3981. tag = AdapterJS.WebRTCPlugin.TAGS.AUDIO;
  3982. break;
  3983. case 'video':
  3984. tag = AdapterJS.WebRTCPlugin.TAGS.VIDEO;
  3985. break;
  3986. default:
  3987. tag = AdapterJS.WebRTCPlugin.TAGS.NONE;
  3988. }
  3989. var frag = document.createDocumentFragment();
  3990. var temp = document.createElement('div');
  3991. var classHTML = '';
  3992. if (element.className) {
  3993. classHTML = 'class="' + element.className + '" ';
  3994. } else if (element.attributes && element.attributes['class']) {
  3995. classHTML = 'class="' + element.attributes['class'].value + '" ';
  3996. }
  3997. temp.innerHTML = '<object id="' + elementId + '" ' + classHTML +
  3998. 'type="' + AdapterJS.WebRTCPlugin.pluginInfo.type + '">' +
  3999. '<param name="pluginId" value="' + elementId + '" /> ' +
  4000. '<param name="pageId" value="' + AdapterJS.WebRTCPlugin.pageId + '" /> ' +
  4001. '<param name="windowless" value="true" /> ' +
  4002. '<param name="streamId" value="' + streamId + '" /> ' +
  4003. '<param name="tag" value="' + tag + '" /> ' +
  4004. '</object>';
  4005. while (temp.firstChild) {
  4006. frag.appendChild(temp.firstChild);
  4007. }
  4008. var height = '';
  4009. var width = '';
  4010. if (element.getBoundingClientRect) {
  4011. var rectObject = element.getBoundingClientRect();
  4012. width = rectObject.width + 'px';
  4013. height = rectObject.height + 'px';
  4014. }
  4015. else if (element.width) {
  4016. width = element.width;
  4017. height = element.height;
  4018. } else {
  4019. // TODO: What scenario could bring us here?
  4020. }
  4021. element.parentNode.insertBefore(frag, element);
  4022. frag = document.getElementById(elementId);
  4023. frag.width = width;
  4024. frag.height = height;
  4025. element.parentNode.removeChild(element);
  4026. } else { // already an <object> tag, just change the stream id
  4027. var children = element.children;
  4028. for (var i = 0; i !== children.length; ++i) {
  4029. if (children[i].name === 'streamId') {
  4030. children[i].value = streamId;
  4031. break;
  4032. }
  4033. }
  4034. element.setStreamId(streamId);
  4035. }
  4036. var newElement = document.getElementById(elementId);
  4037. newElement.onplaying = (element.onplaying) ? element.onplaying : function (arg) {};
  4038. newElement.onplay = (element.onplay) ? element.onplay : function (arg) {};
  4039. newElement.onclick = (element.onclick) ? element.onclick : function (arg) {};
  4040. if (isIE) { // on IE the event needs to be plugged manually
  4041. newElement.attachEvent('onplaying', newElement.onplaying);
  4042. newElement.attachEvent('onplay', newElement.onplay);
  4043. newElement._TemOnClick = function (id) {
  4044. var arg = {
  4045. srcElement : document.getElementById(id)
  4046. };
  4047. newElement.onclick(arg);
  4048. };
  4049. }
  4050. return newElement;
  4051. };
  4052. reattachMediaStream = function (to, from) {
  4053. var stream = null;
  4054. var children = from.children;
  4055. for (var i = 0; i !== children.length; ++i) {
  4056. if (children[i].name === 'streamId') {
  4057. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  4058. stream = AdapterJS.WebRTCPlugin.plugin
  4059. .getStreamWithId(AdapterJS.WebRTCPlugin.pageId, children[i].value);
  4060. break;
  4061. }
  4062. }
  4063. if (stream !== null) {
  4064. return attachMediaStream(to, stream);
  4065. } else {
  4066. console.log('Could not find the stream associated with this element');
  4067. }
  4068. };
  4069. RTCIceCandidate = function (candidate) {
  4070. if (!candidate.sdpMid) {
  4071. candidate.sdpMid = '';
  4072. }
  4073. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  4074. return AdapterJS.WebRTCPlugin.plugin.ConstructIceCandidate(
  4075. candidate.sdpMid, candidate.sdpMLineIndex, candidate.candidate
  4076. );
  4077. };
  4078. // inject plugin
  4079. AdapterJS.addEvent(document, 'readystatechange', AdapterJS.WebRTCPlugin.injectPlugin);
  4080. AdapterJS.WebRTCPlugin.injectPlugin();
  4081. };
  4082. // This function will be called if the plugin is needed (browser different
  4083. // from Chrome or Firefox), but the plugin is not installed.
  4084. AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCb = AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCb ||
  4085. function() {
  4086. AdapterJS.addEvent(document,
  4087. 'readystatechange',
  4088. AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCbPriv);
  4089. AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCbPriv();
  4090. };
  4091. AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCbPriv = function () {
  4092. if (AdapterJS.options.hidePluginInstallPrompt) {
  4093. return;
  4094. }
  4095. var downloadLink = AdapterJS.WebRTCPlugin.pluginInfo.downloadLink;
  4096. if(downloadLink) { // if download link
  4097. var popupString;
  4098. if (AdapterJS.WebRTCPlugin.pluginInfo.portalLink) { // is portal link
  4099. popupString = 'This website requires you to install the ' +
  4100. ' <a href="' + AdapterJS.WebRTCPlugin.pluginInfo.portalLink +
  4101. '" target="_blank">' + AdapterJS.WebRTCPlugin.pluginInfo.companyName +
  4102. ' WebRTC Plugin</a>' +
  4103. ' to work on this browser.';
  4104. } else { // no portal link, just print a generic explanation
  4105. popupString = AdapterJS.TEXT.PLUGIN.REQUIRE_INSTALLATION;
  4106. }
  4107. AdapterJS.renderNotificationBar(popupString, AdapterJS.TEXT.PLUGIN.BUTTON, downloadLink);
  4108. } else { // no download link, just print a generic explanation
  4109. AdapterJS.renderNotificationBar(AdapterJS.TEXT.PLUGIN.NOT_SUPPORTED);
  4110. }
  4111. };
  4112. // Try to detect the plugin and act accordingly
  4113. AdapterJS.WebRTCPlugin.isPluginInstalled(
  4114. AdapterJS.WebRTCPlugin.pluginInfo.prefix,
  4115. AdapterJS.WebRTCPlugin.pluginInfo.plugName,
  4116. AdapterJS.WebRTCPlugin.defineWebRTCInterface,
  4117. AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCb);
  4118. }
  4119. }).call(this,"/modules/RTC/adapter.screenshare.js")
  4120. },{"jitsi-meet-logger":48}],21:[function(require,module,exports){
  4121. (function (__filename){
  4122. var logger = require("jitsi-meet-logger").getLogger(__filename);
  4123. function supportsLocalStorage() {
  4124. try {
  4125. return 'localStorage' in window && window.localStorage !== null;
  4126. } catch (e) {
  4127. logger.log("localstorage is not supported");
  4128. return false;
  4129. }
  4130. }
  4131. function generateUniqueId() {
  4132. function _p8() {
  4133. return (Math.random().toString(16) + "000000000").substr(2, 8);
  4134. }
  4135. return _p8() + _p8() + _p8() + _p8();
  4136. }
  4137. function Settings(conferenceID) {
  4138. this.email = '';
  4139. this.displayName = '';
  4140. this.userId;
  4141. this.language = null;
  4142. this.confSettings = null;
  4143. this.conferenceID = conferenceID;
  4144. if (supportsLocalStorage()) {
  4145. if(!window.localStorage.getItem(conferenceID))
  4146. this.confSettings = {};
  4147. else
  4148. this.confSettings = JSON.parse(window.localStorage.getItem(conferenceID));
  4149. if(!this.confSettings.jitsiMeetId) {
  4150. this.confSettings.jitsiMeetId = generateUniqueId();
  4151. logger.log("generated id",
  4152. this.confSettings.jitsiMeetId);
  4153. this.save();
  4154. }
  4155. this.userId = this.confSettings.jitsiMeetId || '';
  4156. this.email = this.confSettings.email || '';
  4157. this.displayName = this.confSettings.displayname || '';
  4158. this.language = this.confSettings.language;
  4159. } else {
  4160. logger.log("local storage is not supported");
  4161. this.userId = generateUniqueId();
  4162. }
  4163. }
  4164. Settings.prototype.save = function () {
  4165. if(!supportsLocalStorage())
  4166. window.localStorage.setItem(this.conferenceID, JSON.stringify(this.confSettings));
  4167. }
  4168. Settings.prototype.setDisplayName = function (newDisplayName) {
  4169. this.displayName = newDisplayName;
  4170. if(this.confSettings != null)
  4171. this.confSettings.displayname = displayName;
  4172. this.save();
  4173. return this.displayName;
  4174. },
  4175. Settings.prototype.setEmail = function (newEmail) {
  4176. this.email = newEmail;
  4177. if(this.confSettings != null)
  4178. this.confSettings.email = newEmail;
  4179. this.save();
  4180. return this.email;
  4181. },
  4182. Settings.prototype.getSettings = function () {
  4183. return {
  4184. email: this.email,
  4185. displayName: this.displayName,
  4186. uid: this.userId,
  4187. language: this.language
  4188. };
  4189. },
  4190. Settings.prototype.setLanguage = function (lang) {
  4191. this.language = lang;
  4192. if(this.confSettings != null)
  4193. this.confSettings.language = lang;
  4194. this.save();
  4195. }
  4196. module.exports = Settings;
  4197. }).call(this,"/modules/settings/Settings.js")
  4198. },{"jitsi-meet-logger":48}],22:[function(require,module,exports){
  4199. /* global config */
  4200. /**
  4201. * Provides statistics for the local stream.
  4202. */
  4203. var RTCBrowserType = require('../RTC/RTCBrowserType');
  4204. /**
  4205. * Size of the webaudio analyzer buffer.
  4206. * @type {number}
  4207. */
  4208. var WEBAUDIO_ANALYZER_FFT_SIZE = 2048;
  4209. /**
  4210. * Value of the webaudio analyzer smoothing time parameter.
  4211. * @type {number}
  4212. */
  4213. var WEBAUDIO_ANALYZER_SMOOTING_TIME = 0.8;
  4214. /**
  4215. * Converts time domain data array to audio level.
  4216. * @param samples the time domain data array.
  4217. * @returns {number} the audio level
  4218. */
  4219. function timeDomainDataToAudioLevel(samples) {
  4220. var maxVolume = 0;
  4221. var length = samples.length;
  4222. for (var i = 0; i < length; i++) {
  4223. if (maxVolume < samples[i])
  4224. maxVolume = samples[i];
  4225. }
  4226. return parseFloat(((maxVolume - 127) / 128).toFixed(3));
  4227. }
  4228. /**
  4229. * Animates audio level change
  4230. * @param newLevel the new audio level
  4231. * @param lastLevel the last audio level
  4232. * @returns {Number} the audio level to be set
  4233. */
  4234. function animateLevel(newLevel, lastLevel) {
  4235. var value = 0;
  4236. var diff = lastLevel - newLevel;
  4237. if(diff > 0.2) {
  4238. value = lastLevel - 0.2;
  4239. }
  4240. else if(diff < -0.4) {
  4241. value = lastLevel + 0.4;
  4242. }
  4243. else {
  4244. value = newLevel;
  4245. }
  4246. return parseFloat(value.toFixed(3));
  4247. }
  4248. /**
  4249. * <tt>LocalStatsCollector</tt> calculates statistics for the local stream.
  4250. *
  4251. * @param stream the local stream
  4252. * @param interval stats refresh interval given in ms.
  4253. * @param callback function that receives the audio levels.
  4254. * @constructor
  4255. */
  4256. function LocalStatsCollector(stream, interval, callback) {
  4257. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  4258. this.stream = stream;
  4259. this.intervalId = null;
  4260. this.intervalMilis = interval;
  4261. this.audioLevel = 0;
  4262. this.callback = callback;
  4263. }
  4264. /**
  4265. * Starts the collecting the statistics.
  4266. */
  4267. LocalStatsCollector.prototype.start = function () {
  4268. if (!window.AudioContext ||
  4269. RTCBrowserType.isTemasysPluginUsed())
  4270. return;
  4271. var context = new AudioContext();
  4272. var analyser = context.createAnalyser();
  4273. analyser.smoothingTimeConstant = WEBAUDIO_ANALYZER_SMOOTING_TIME;
  4274. analyser.fftSize = WEBAUDIO_ANALYZER_FFT_SIZE;
  4275. var source = context.createMediaStreamSource(this.stream);
  4276. source.connect(analyser);
  4277. var self = this;
  4278. this.intervalId = setInterval(
  4279. function () {
  4280. var array = new Uint8Array(analyser.frequencyBinCount);
  4281. analyser.getByteTimeDomainData(array);
  4282. var audioLevel = timeDomainDataToAudioLevel(array);
  4283. if (audioLevel != self.audioLevel) {
  4284. self.audioLevel = animateLevel(audioLevel, self.audioLevel);
  4285. self.callback(self.audioLevel);
  4286. }
  4287. },
  4288. this.intervalMilis
  4289. );
  4290. };
  4291. /**
  4292. * Stops collecting the statistics.
  4293. */
  4294. LocalStatsCollector.prototype.stop = function () {
  4295. if (this.intervalId) {
  4296. clearInterval(this.intervalId);
  4297. this.intervalId = null;
  4298. }
  4299. };
  4300. module.exports = LocalStatsCollector;
  4301. },{"../RTC/RTCBrowserType":17}],23:[function(require,module,exports){
  4302. (function (__filename){
  4303. /* global require, ssrc2jid */
  4304. /* jshint -W117 */
  4305. var logger = require("jitsi-meet-logger").getLogger(__filename);
  4306. var RTCBrowserType = require("../RTC/RTCBrowserType");
  4307. var StatisticsEvents = require("../../service/statistics/Events");
  4308. /* Whether we support the browser we are running into for logging statistics */
  4309. var browserSupported = RTCBrowserType.isChrome() ||
  4310. RTCBrowserType.isOpera();
  4311. var keyMap = {};
  4312. keyMap[RTCBrowserType.RTC_BROWSER_FIREFOX] = {
  4313. "ssrc": "ssrc",
  4314. "packetsReceived": "packetsReceived",
  4315. "packetsLost": "packetsLost",
  4316. "packetsSent": "packetsSent",
  4317. "bytesReceived": "bytesReceived",
  4318. "bytesSent": "bytesSent"
  4319. };
  4320. keyMap[RTCBrowserType.RTC_BROWSER_CHROME] = {
  4321. "receiveBandwidth": "googAvailableReceiveBandwidth",
  4322. "sendBandwidth": "googAvailableSendBandwidth",
  4323. "remoteAddress": "googRemoteAddress",
  4324. "transportType": "googTransportType",
  4325. "localAddress": "googLocalAddress",
  4326. "activeConnection": "googActiveConnection",
  4327. "ssrc": "ssrc",
  4328. "packetsReceived": "packetsReceived",
  4329. "packetsSent": "packetsSent",
  4330. "packetsLost": "packetsLost",
  4331. "bytesReceived": "bytesReceived",
  4332. "bytesSent": "bytesSent",
  4333. "googFrameHeightReceived": "googFrameHeightReceived",
  4334. "googFrameWidthReceived": "googFrameWidthReceived",
  4335. "googFrameHeightSent": "googFrameHeightSent",
  4336. "googFrameWidthSent": "googFrameWidthSent",
  4337. "audioInputLevel": "audioInputLevel",
  4338. "audioOutputLevel": "audioOutputLevel"
  4339. };
  4340. keyMap[RTCBrowserType.RTC_BROWSER_OPERA] =
  4341. keyMap[RTCBrowserType.RTC_BROWSER_CHROME];
  4342. /**
  4343. * Calculates packet lost percent using the number of lost packets and the
  4344. * number of all packet.
  4345. * @param lostPackets the number of lost packets
  4346. * @param totalPackets the number of all packets.
  4347. * @returns {number} packet loss percent
  4348. */
  4349. function calculatePacketLoss(lostPackets, totalPackets) {
  4350. if(!totalPackets || totalPackets <= 0 || !lostPackets || lostPackets <= 0)
  4351. return 0;
  4352. return Math.round((lostPackets/totalPackets)*100);
  4353. }
  4354. function getStatValue(item, name) {
  4355. var browserType = RTCBrowserType.getBrowserType();
  4356. if (!keyMap[browserType][name])
  4357. throw "The property isn't supported!";
  4358. var key = keyMap[browserType][name];
  4359. return (RTCBrowserType.isChrome() || RTCBrowserType.isOpera()) ?
  4360. item.stat(key) : item[key];
  4361. }
  4362. function formatAudioLevel(audioLevel) {
  4363. return Math.min(Math.max(audioLevel, 0), 1);
  4364. }
  4365. /**
  4366. * Checks whether a certain record should be included in the logged statistics.
  4367. */
  4368. function acceptStat(reportId, reportType, statName) {
  4369. if (reportType == "googCandidatePair" && statName == "googChannelId")
  4370. return false;
  4371. if (reportType == "ssrc") {
  4372. if (statName == "googTrackId" ||
  4373. statName == "transportId" ||
  4374. statName == "ssrc")
  4375. return false;
  4376. }
  4377. return true;
  4378. }
  4379. /**
  4380. * Checks whether a certain record should be included in the logged statistics.
  4381. */
  4382. function acceptReport(id, type) {
  4383. if (id.substring(0, 15) == "googCertificate" ||
  4384. id.substring(0, 9) == "googTrack" ||
  4385. id.substring(0, 20) == "googLibjingleSession")
  4386. return false;
  4387. if (type == "googComponent")
  4388. return false;
  4389. return true;
  4390. }
  4391. /**
  4392. * Peer statistics data holder.
  4393. * @constructor
  4394. */
  4395. function PeerStats()
  4396. {
  4397. this.ssrc2Loss = {};
  4398. this.ssrc2AudioLevel = {};
  4399. this.ssrc2bitrate = {};
  4400. this.ssrc2resolution = {};
  4401. }
  4402. /**
  4403. * Sets packets loss rate for given <tt>ssrc</tt> that blong to the peer
  4404. * represented by this instance.
  4405. * @param lossRate new packet loss rate value to be set.
  4406. */
  4407. PeerStats.prototype.setSsrcLoss = function (lossRate)
  4408. {
  4409. this.ssrc2Loss = lossRate;
  4410. };
  4411. /**
  4412. * Sets resolution that belong to the ssrc
  4413. * represented by this instance.
  4414. * @param resolution new resolution value to be set.
  4415. */
  4416. PeerStats.prototype.setSsrcResolution = function (resolution)
  4417. {
  4418. if(resolution === null && this.ssrc2resolution[ssrc])
  4419. {
  4420. delete this.ssrc2resolution[ssrc];
  4421. }
  4422. else if(resolution !== null)
  4423. this.ssrc2resolution[ssrc] = resolution;
  4424. };
  4425. /**
  4426. * Sets the bit rate for given <tt>ssrc</tt> that blong to the peer
  4427. * represented by this instance.
  4428. * @param ssrc audio or video RTP stream SSRC.
  4429. * @param bitrate new bitrate value to be set.
  4430. */
  4431. PeerStats.prototype.setSsrcBitrate = function (ssrc, bitrate)
  4432. {
  4433. if(this.ssrc2bitrate[ssrc])
  4434. {
  4435. this.ssrc2bitrate[ssrc].download += bitrate.download;
  4436. this.ssrc2bitrate[ssrc].upload += bitrate.upload;
  4437. }
  4438. else {
  4439. this.ssrc2bitrate[ssrc] = bitrate;
  4440. }
  4441. };
  4442. /**
  4443. * Sets new audio level(input or output) for given <tt>ssrc</tt> that identifies
  4444. * the stream which belongs to the peer represented by this instance.
  4445. * @param ssrc RTP stream SSRC for which current audio level value will be
  4446. * updated.
  4447. * @param audioLevel the new audio level value to be set. Value is truncated to
  4448. * fit the range from 0 to 1.
  4449. */
  4450. PeerStats.prototype.setSsrcAudioLevel = function (ssrc, audioLevel)
  4451. {
  4452. // Range limit 0 - 1
  4453. this.ssrc2AudioLevel[ssrc] = formatAudioLevel(audioLevel);
  4454. };
  4455. function ConferenceStats() {
  4456. /**
  4457. * The bandwidth
  4458. * @type {{}}
  4459. */
  4460. this.bandwidth = {};
  4461. /**
  4462. * The bit rate
  4463. * @type {{}}
  4464. */
  4465. this.bitrate = {};
  4466. /**
  4467. * The packet loss rate
  4468. * @type {{}}
  4469. */
  4470. this.packetLoss = null;
  4471. /**
  4472. * Array with the transport information.
  4473. * @type {Array}
  4474. */
  4475. this.transport = [];
  4476. }
  4477. /**
  4478. * <tt>StatsCollector</tt> registers for stats updates of given
  4479. * <tt>peerconnection</tt> in given <tt>interval</tt>. On each update particular
  4480. * stats are extracted and put in {@link PeerStats} objects. Once the processing
  4481. * is done <tt>audioLevelsUpdateCallback</tt> is called with <tt>this</tt>
  4482. * instance as an event source.
  4483. *
  4484. * @param peerconnection webRTC peer connection object.
  4485. * @param interval stats refresh interval given in ms.
  4486. * @param {function(StatsCollector)} audioLevelsUpdateCallback the callback
  4487. * called on stats update.
  4488. * @param config {object} supports the following properties - disableAudioLevels, disableStats, logStats
  4489. * @constructor
  4490. */
  4491. function StatsCollector(peerconnection, audioLevelsInterval, statsInterval, eventEmitter, config)
  4492. {
  4493. this.peerconnection = peerconnection;
  4494. this.baselineAudioLevelsReport = null;
  4495. this.currentAudioLevelsReport = null;
  4496. this.currentStatsReport = null;
  4497. this.baselineStatsReport = null;
  4498. this.audioLevelsIntervalId = null;
  4499. this.eventEmitter = eventEmitter;
  4500. this.config = config || {};
  4501. this.conferenceStats = new ConferenceStats();
  4502. /**
  4503. * Gather PeerConnection stats once every this many milliseconds.
  4504. */
  4505. this.GATHER_INTERVAL = 15000;
  4506. /**
  4507. * Log stats via the focus once every this many milliseconds.
  4508. */
  4509. this.LOG_INTERVAL = 60000;
  4510. /**
  4511. * Gather stats and store them in this.statsToBeLogged.
  4512. */
  4513. this.gatherStatsIntervalId = null;
  4514. /**
  4515. * Send the stats already saved in this.statsToBeLogged to be logged via
  4516. * the focus.
  4517. */
  4518. this.logStatsIntervalId = null;
  4519. /**
  4520. * Stores the statistics which will be send to the focus to be logged.
  4521. */
  4522. this.statsToBeLogged =
  4523. {
  4524. timestamps: [],
  4525. stats: {}
  4526. };
  4527. // Updates stats interval
  4528. this.audioLevelsIntervalMilis = audioLevelsInterval;
  4529. this.statsIntervalId = null;
  4530. this.statsIntervalMilis = statsInterval;
  4531. // Map of ssrcs to PeerStats
  4532. this.ssrc2stats = {};
  4533. }
  4534. module.exports = StatsCollector;
  4535. /**
  4536. * Stops stats updates.
  4537. */
  4538. StatsCollector.prototype.stop = function () {
  4539. if (this.audioLevelsIntervalId) {
  4540. clearInterval(this.audioLevelsIntervalId);
  4541. this.audioLevelsIntervalId = null;
  4542. }
  4543. if (this.statsIntervalId)
  4544. {
  4545. clearInterval(this.statsIntervalId);
  4546. this.statsIntervalId = null;
  4547. }
  4548. if(this.logStatsIntervalId)
  4549. {
  4550. clearInterval(this.logStatsIntervalId);
  4551. this.logStatsIntervalId = null;
  4552. }
  4553. if(this.gatherStatsIntervalId)
  4554. {
  4555. clearInterval(this.gatherStatsIntervalId);
  4556. this.gatherStatsIntervalId = null;
  4557. }
  4558. };
  4559. /**
  4560. * Callback passed to <tt>getStats</tt> method.
  4561. * @param error an error that occurred on <tt>getStats</tt> call.
  4562. */
  4563. StatsCollector.prototype.errorCallback = function (error)
  4564. {
  4565. logger.error("Get stats error", error);
  4566. this.stop();
  4567. };
  4568. /**
  4569. * Starts stats updates.
  4570. */
  4571. StatsCollector.prototype.start = function ()
  4572. {
  4573. var self = this;
  4574. this.audioLevelsIntervalId = setInterval(
  4575. function () {
  4576. // Interval updates
  4577. self.peerconnection.getStats(
  4578. function (report) {
  4579. var results = null;
  4580. if (!report || !report.result ||
  4581. typeof report.result != 'function') {
  4582. results = report;
  4583. }
  4584. else {
  4585. results = report.result();
  4586. }
  4587. //logger.error("Got interval report", results);
  4588. self.currentAudioLevelsReport = results;
  4589. self.processAudioLevelReport();
  4590. self.baselineAudioLevelsReport =
  4591. self.currentAudioLevelsReport;
  4592. },
  4593. self.errorCallback
  4594. );
  4595. },
  4596. self.audioLevelsIntervalMilis
  4597. );
  4598. // if (!this.config.disableStats && browserSupported) {
  4599. // this.statsIntervalId = setInterval(
  4600. // function () {
  4601. // // Interval updates
  4602. // self.peerconnection.getStats(
  4603. // function (report) {
  4604. // var results = null;
  4605. // if (!report || !report.result ||
  4606. // typeof report.result != 'function') {
  4607. // //firefox
  4608. // results = report;
  4609. // }
  4610. // else {
  4611. // //chrome
  4612. // results = report.result();
  4613. // }
  4614. // //logger.error("Got interval report", results);
  4615. // self.currentStatsReport = results;
  4616. // try {
  4617. // self.processStatsReport();
  4618. // }
  4619. // catch (e) {
  4620. // logger.error("Unsupported key:" + e, e);
  4621. // }
  4622. //
  4623. // self.baselineStatsReport = self.currentStatsReport;
  4624. // },
  4625. // self.errorCallback
  4626. // );
  4627. // },
  4628. // self.statsIntervalMilis
  4629. // );
  4630. // }
  4631. //
  4632. // if (this.config.logStats && browserSupported) {
  4633. // this.gatherStatsIntervalId = setInterval(
  4634. // function () {
  4635. // self.peerconnection.getStats(
  4636. // function (report) {
  4637. // self.addStatsToBeLogged(report.result());
  4638. // },
  4639. // function () {
  4640. // }
  4641. // );
  4642. // },
  4643. // this.GATHER_INTERVAL
  4644. // );
  4645. //
  4646. // this.logStatsIntervalId = setInterval(
  4647. // function() { self.logStats(); },
  4648. // this.LOG_INTERVAL);
  4649. // }
  4650. };
  4651. /**
  4652. * Converts the stats to the format used for logging, and saves the data in
  4653. * this.statsToBeLogged.
  4654. * @param reports Reports as given by webkitRTCPerConnection.getStats.
  4655. */
  4656. StatsCollector.prototype.addStatsToBeLogged = function (reports) {
  4657. var self = this;
  4658. var num_records = this.statsToBeLogged.timestamps.length;
  4659. this.statsToBeLogged.timestamps.push(new Date().getTime());
  4660. reports.map(function (report) {
  4661. if (!acceptReport(report.id, report.type))
  4662. return;
  4663. var stat = self.statsToBeLogged.stats[report.id];
  4664. if (!stat) {
  4665. stat = self.statsToBeLogged.stats[report.id] = {};
  4666. }
  4667. stat.type = report.type;
  4668. report.names().map(function (name) {
  4669. if (!acceptStat(report.id, report.type, name))
  4670. return;
  4671. var values = stat[name];
  4672. if (!values) {
  4673. values = stat[name] = [];
  4674. }
  4675. while (values.length < num_records) {
  4676. values.push(null);
  4677. }
  4678. values.push(report.stat(name));
  4679. });
  4680. });
  4681. };
  4682. //FIXME:
  4683. //StatsCollector.prototype.logStats = function () {
  4684. //
  4685. // if(!APP.xmpp.sendLogs(this.statsToBeLogged))
  4686. // return;
  4687. // // Reset the stats
  4688. // this.statsToBeLogged.stats = {};
  4689. // this.statsToBeLogged.timestamps = [];
  4690. //};
  4691. /**
  4692. * Stats processing logic.
  4693. */
  4694. StatsCollector.prototype.processStatsReport = function () {
  4695. if (!this.baselineStatsReport) {
  4696. return;
  4697. }
  4698. for (var idx in this.currentStatsReport) {
  4699. var now = this.currentStatsReport[idx];
  4700. try {
  4701. if (getStatValue(now, 'receiveBandwidth') ||
  4702. getStatValue(now, 'sendBandwidth')) {
  4703. this.conferenceStats.bandwidth = {
  4704. "download": Math.round(
  4705. (getStatValue(now, 'receiveBandwidth')) / 1000),
  4706. "upload": Math.round(
  4707. (getStatValue(now, 'sendBandwidth')) / 1000)
  4708. };
  4709. }
  4710. }
  4711. catch(e){/*not supported*/}
  4712. if(now.type == 'googCandidatePair')
  4713. {
  4714. var ip, type, localIP, active;
  4715. try {
  4716. ip = getStatValue(now, 'remoteAddress');
  4717. type = getStatValue(now, "transportType");
  4718. localIP = getStatValue(now, "localAddress");
  4719. active = getStatValue(now, "activeConnection");
  4720. }
  4721. catch(e){/*not supported*/}
  4722. if(!ip || !type || !localIP || active != "true")
  4723. continue;
  4724. var addressSaved = false;
  4725. for(var i = 0; i < this.conferenceStats.transport.length; i++)
  4726. {
  4727. if(this.conferenceStats.transport[i].ip == ip &&
  4728. this.conferenceStats.transport[i].type == type &&
  4729. this.conferenceStats.transport[i].localip == localIP)
  4730. {
  4731. addressSaved = true;
  4732. }
  4733. }
  4734. if(addressSaved)
  4735. continue;
  4736. this.conferenceStats.transport.push({localip: localIP, ip: ip, type: type});
  4737. continue;
  4738. }
  4739. if(now.type == "candidatepair")
  4740. {
  4741. if(now.state == "succeeded")
  4742. continue;
  4743. var local = this.currentStatsReport[now.localCandidateId];
  4744. var remote = this.currentStatsReport[now.remoteCandidateId];
  4745. this.conferenceStats.transport.push({localip: local.ipAddress + ":" + local.portNumber,
  4746. ip: remote.ipAddress + ":" + remote.portNumber, type: local.transport});
  4747. }
  4748. if (now.type != 'ssrc' && now.type != "outboundrtp" &&
  4749. now.type != "inboundrtp") {
  4750. continue;
  4751. }
  4752. var before = this.baselineStatsReport[idx];
  4753. if (!before) {
  4754. logger.warn(getStatValue(now, 'ssrc') + ' not enough data');
  4755. continue;
  4756. }
  4757. var ssrc = getStatValue(now, 'ssrc');
  4758. if(!ssrc)
  4759. continue;
  4760. var ssrcStats = this.ssrc2stats[ssrc];
  4761. if (!ssrcStats) {
  4762. ssrcStats = new PeerStats();
  4763. this.ssrc2stats[ssrc] = ssrcStats;
  4764. }
  4765. var isDownloadStream = true;
  4766. var key = 'packetsReceived';
  4767. var packetsNow = getStatValue(now, key);
  4768. if (typeof packetsNow === 'undefined' || packetsNow === null) {
  4769. isDownloadStream = false;
  4770. key = 'packetsSent';
  4771. packetsNow = getStatValue(now, key);
  4772. if (typeof packetsNow === 'undefined' || packetsNow === null) {
  4773. console.warn("No packetsReceived nor packetsSent stat found");
  4774. continue;
  4775. }
  4776. }
  4777. if (!packetsNow || packetsNow < 0)
  4778. packetsNow = 0;
  4779. var packetsBefore = getStatValue(before, key);
  4780. if (!packetsBefore || packetsBefore < 0)
  4781. packetsBefore = 0;
  4782. var packetRate = packetsNow - packetsBefore;
  4783. if (!packetRate || packetRate < 0)
  4784. packetRate = 0;
  4785. var currentLoss = getStatValue(now, 'packetsLost');
  4786. if (!currentLoss || currentLoss < 0)
  4787. currentLoss = 0;
  4788. var previousLoss = getStatValue(before, 'packetsLost');
  4789. if (!previousLoss || previousLoss < 0)
  4790. previousLoss = 0;
  4791. var lossRate = currentLoss - previousLoss;
  4792. if (!lossRate || lossRate < 0)
  4793. lossRate = 0;
  4794. var packetsTotal = (packetRate + lossRate);
  4795. ssrcStats.setSsrcLoss(ssrc,
  4796. {"packetsTotal": packetsTotal,
  4797. "packetsLost": lossRate,
  4798. "isDownloadStream": isDownloadStream});
  4799. var bytesReceived = 0, bytesSent = 0;
  4800. if(getStatValue(now, "bytesReceived")) {
  4801. bytesReceived = getStatValue(now, "bytesReceived") -
  4802. getStatValue(before, "bytesReceived");
  4803. }
  4804. if (getStatValue(now, "bytesSent")) {
  4805. bytesSent = getStatValue(now, "bytesSent") -
  4806. getStatValue(before, "bytesSent");
  4807. }
  4808. var time = Math.round((now.timestamp - before.timestamp) / 1000);
  4809. if (bytesReceived <= 0 || time <= 0) {
  4810. bytesReceived = 0;
  4811. } else {
  4812. bytesReceived = Math.round(((bytesReceived * 8) / time) / 1000);
  4813. }
  4814. if (bytesSent <= 0 || time <= 0) {
  4815. bytesSent = 0;
  4816. } else {
  4817. bytesSent = Math.round(((bytesSent * 8) / time) / 1000);
  4818. }
  4819. ssrcStats.setSsrcBitrate(ssrc, {
  4820. "download": bytesReceived,
  4821. "upload": bytesSent});
  4822. var resolution = {height: null, width: null};
  4823. try {
  4824. if (getStatValue(now, "googFrameHeightReceived") &&
  4825. getStatValue(now, "googFrameWidthReceived")) {
  4826. resolution.height =
  4827. getStatValue(now, "googFrameHeightReceived");
  4828. resolution.width = getStatValue(now, "googFrameWidthReceived");
  4829. }
  4830. else if (getStatValue(now, "googFrameHeightSent") &&
  4831. getStatValue(now, "googFrameWidthSent")) {
  4832. resolution.height = getStatValue(now, "googFrameHeightSent");
  4833. resolution.width = getStatValue(now, "googFrameWidthSent");
  4834. }
  4835. }
  4836. catch(e){/*not supported*/}
  4837. if (resolution.height && resolution.width) {
  4838. ssrcStats.setSsrcResolution(ssrc, resolution);
  4839. } else {
  4840. ssrcStats.setSsrcResolution(ssrc, null);
  4841. }
  4842. }
  4843. var self = this;
  4844. // Jid stats
  4845. var totalPackets = {download: 0, upload: 0};
  4846. var lostPackets = {download: 0, upload: 0};
  4847. var bitrateDownload = 0;
  4848. var bitrateUpload = 0;
  4849. var resolutions = {};
  4850. Object.keys(this.ssrc2stats).forEach(
  4851. function (jid) {
  4852. Object.keys(self.ssrc2stats[jid].ssrc2Loss).forEach(
  4853. function (ssrc) {
  4854. var type = "upload";
  4855. if(self.ssrc2stats[jid].ssrc2Loss[ssrc].isDownloadStream)
  4856. type = "download";
  4857. totalPackets[type] +=
  4858. self.ssrc2stats[jid].ssrc2Loss[ssrc].packetsTotal;
  4859. lostPackets[type] +=
  4860. self.ssrc2stats[jid].ssrc2Loss[ssrc].packetsLost;
  4861. }
  4862. );
  4863. Object.keys(self.ssrc2stats[jid].ssrc2bitrate).forEach(
  4864. function (ssrc) {
  4865. bitrateDownload +=
  4866. self.ssrc2stats[jid].ssrc2bitrate[ssrc].download;
  4867. bitrateUpload +=
  4868. self.ssrc2stats[jid].ssrc2bitrate[ssrc].upload;
  4869. delete self.ssrc2stats[jid].ssrc2bitrate[ssrc];
  4870. }
  4871. );
  4872. resolutions[jid] = self.ssrc2stats[jid].ssrc2resolution;
  4873. }
  4874. );
  4875. this.conferenceStats.bitrate = {"upload": bitrateUpload, "download": bitrateDownload};
  4876. this.conferenceStats.packetLoss = {
  4877. total:
  4878. calculatePacketLoss(lostPackets.download + lostPackets.upload,
  4879. totalPackets.download + totalPackets.upload),
  4880. download:
  4881. calculatePacketLoss(lostPackets.download, totalPackets.download),
  4882. upload:
  4883. calculatePacketLoss(lostPackets.upload, totalPackets.upload)
  4884. };
  4885. this.eventEmitter.emit(StatisticsEvents.CONNECTION_STATS,
  4886. {
  4887. "bitrate": this.conferenceStats.bitrate,
  4888. "packetLoss": this.conferenceStats.packetLoss,
  4889. "bandwidth": this.conferenceStats.bandwidth,
  4890. "resolution": resolutions,
  4891. "transport": this.conferenceStats.transport
  4892. });
  4893. this.conferenceStats.transport = [];
  4894. };
  4895. /**
  4896. * Stats processing logic.
  4897. */
  4898. StatsCollector.prototype.processAudioLevelReport = function () {
  4899. if (!this.baselineAudioLevelsReport) {
  4900. return;
  4901. }
  4902. for (var idx in this.currentAudioLevelsReport) {
  4903. var now = this.currentAudioLevelsReport[idx];
  4904. //if we don't have "packetsReceived" this is local stream
  4905. if (now.type != 'ssrc' || !getStatValue(now, 'packetsReceived')) {
  4906. continue;
  4907. }
  4908. var before = this.baselineAudioLevelsReport[idx];
  4909. if (!before) {
  4910. logger.warn(getStatValue(now, 'ssrc') + ' not enough data');
  4911. continue;
  4912. }
  4913. var ssrc = getStatValue(now, 'ssrc');
  4914. if (!ssrc) {
  4915. if((Date.now() - now.timestamp) < 3000)
  4916. logger.warn("No ssrc: ");
  4917. continue;
  4918. }
  4919. var ssrcStats = this.ssrc2stats[ssrc];
  4920. if (!ssrcStats) {
  4921. ssrcStats = new PeerStats();
  4922. this.ssrc2stats[ssrc] = ssrcStats;
  4923. }
  4924. // Audio level
  4925. var audioLevel = null;
  4926. try {
  4927. audioLevel = getStatValue(now, 'audioInputLevel');
  4928. if (!audioLevel)
  4929. audioLevel = getStatValue(now, 'audioOutputLevel');
  4930. }
  4931. catch(e) {/*not supported*/
  4932. logger.warn("Audio Levels are not available in the statistics.");
  4933. clearInterval(this.audioLevelsIntervalId);
  4934. return;
  4935. }
  4936. if (audioLevel) {
  4937. // TODO: can't find specs about what this value really is,
  4938. // but it seems to vary between 0 and around 32k.
  4939. audioLevel = audioLevel / 32767;
  4940. ssrcStats.setSsrcAudioLevel(ssrc, audioLevel);
  4941. this.eventEmitter.emit(
  4942. StatisticsEvents.AUDIO_LEVEL, ssrc, audioLevel);
  4943. }
  4944. }
  4945. };
  4946. }).call(this,"/modules/statistics/RTPStatsCollector.js")
  4947. },{"../../service/statistics/Events":89,"../RTC/RTCBrowserType":17,"jitsi-meet-logger":48}],24:[function(require,module,exports){
  4948. /* global require, APP */
  4949. var LocalStats = require("./LocalStatsCollector.js");
  4950. var RTPStats = require("./RTPStatsCollector.js");
  4951. var EventEmitter = require("events");
  4952. var StatisticsEvents = require("../../service/statistics/Events");
  4953. //var StreamEventTypes = require("../../service/RTC/StreamEventTypes.js");
  4954. //var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  4955. //var CallStats = require("./CallStats");
  4956. //var RTCEvents = require("../../service/RTC/RTCEvents");
  4957. //
  4958. //function onDisposeConference(onUnload) {
  4959. // CallStats.sendTerminateEvent();
  4960. // stopRemote();
  4961. // if(onUnload) {
  4962. // stopLocal();
  4963. // eventEmitter.removeAllListeners();
  4964. // }
  4965. //}
  4966. var eventEmitter = new EventEmitter();
  4967. function Statistics() {
  4968. this.rtpStats = null;
  4969. this.eventEmitter = new EventEmitter();
  4970. }
  4971. Statistics.prototype.startRemoteStats = function (peerconnection) {
  4972. if (this.rtpStats) {
  4973. this.rtpStats.stop();
  4974. }
  4975. this.rtpStats = new RTPStats(peerconnection, 200, 2000, this.eventEmitter);
  4976. this.rtpStats.start();
  4977. }
  4978. Statistics.localStats = [];
  4979. Statistics.startLocalStats = function (stream, callback) {
  4980. var localStats = new LocalStats(stream, 200, callback);
  4981. this.localStats.push(localStats);
  4982. localStats.start();
  4983. }
  4984. Statistics.prototype.addAudioLevelListener = function(listener)
  4985. {
  4986. this.eventEmitter.on(StatisticsEvents.AUDIO_LEVEL, listener);
  4987. }
  4988. Statistics.prototype.removeAudioLevelListener = function(listener)
  4989. {
  4990. this.eventEmitter.removeListener(StatisticsEvents.AUDIO_LEVEL, listener);
  4991. }
  4992. Statistics.prototype.dispose = function () {
  4993. Statistics.stopAllLocalStats();
  4994. this.stopRemote();
  4995. if(this.eventEmitter)
  4996. this.eventEmitter.removeAllListeners();
  4997. if(eventEmitter)
  4998. eventEmitter.removeAllListeners();
  4999. }
  5000. Statistics.stopAllLocalStats = function () {
  5001. for(var i = 0; i < this.localStats.length; i++)
  5002. this.localStats[i].stop();
  5003. this.localStats = [];
  5004. }
  5005. Statistics.stopLocalStats = function (stream) {
  5006. for(var i = 0; i < Statistics.localStats.length; i++)
  5007. if(Statistics.localStats[i].stream === stream){
  5008. var localStats = Statistics.localStats.splice(i, 1);
  5009. localStats.stop();
  5010. break;
  5011. }
  5012. }
  5013. Statistics.prototype.stopRemote = function () {
  5014. if (this.rtpStats) {
  5015. this.rtpStats.stop();
  5016. this.eventEmitter.emit(StatisticsEvents.STOP);
  5017. this.rtpStats = null;
  5018. }
  5019. };
  5020. /**
  5021. * Obtains audio level reported in the stats for specified peer.
  5022. * @param peerJid full MUC jid of the user for whom we want to obtain last
  5023. * audio level.
  5024. * @param ssrc the SSRC of audio stream for which we want to obtain audio
  5025. * level.
  5026. * @returns {*} a float form 0 to 1 that represents current audio level or
  5027. * <tt>null</tt> if for any reason the value is not available
  5028. * at this time.
  5029. */
  5030. Statistics.prototype.getPeerSSRCAudioLevel = function (peerJid, ssrc) {
  5031. var peerStats = this.rtpStats.jid2stats[peerJid];
  5032. return peerStats ? peerStats.ssrc2AudioLevel[ssrc] : null;
  5033. };
  5034. Statistics.LOCAL_JID = require("../../service/statistics/constants").LOCAL_JID;
  5035. //
  5036. //var statistics = {
  5037. // /**
  5038. // * Indicates that this audio level is for local jid.
  5039. // * @type {string}
  5040. // */
  5041. // LOCAL_JID: 'local',
  5042. //
  5043. // addConnectionStatsListener: function(listener)
  5044. // {
  5045. // eventEmitter.on("statistics.connectionstats", listener);
  5046. // },
  5047. //
  5048. // removeConnectionStatsListener: function(listener)
  5049. // {
  5050. // eventEmitter.removeListener("statistics.connectionstats", listener);
  5051. // },
  5052. //
  5053. //
  5054. // addRemoteStatsStopListener: function(listener)
  5055. // {
  5056. // eventEmitter.on("statistics.stop", listener);
  5057. // },
  5058. //
  5059. // removeRemoteStatsStopListener: function(listener)
  5060. // {
  5061. // eventEmitter.removeListener("statistics.stop", listener);
  5062. // },
  5063. //
  5064. //
  5065. // stopRemoteStatistics: function()
  5066. // {
  5067. // stopRemote();
  5068. // },
  5069. //
  5070. //// Already implemented with the constructor
  5071. // start: function () {
  5072. // APP.RTC.addStreamListener(onStreamCreated,
  5073. // StreamEventTypes.EVENT_TYPE_LOCAL_CREATED);
  5074. // APP.xmpp.addListener(XMPPEvents.DISPOSE_CONFERENCE, onDisposeConference);
  5075. // //FIXME: we may want to change CALL INCOMING event to onnegotiationneeded
  5076. // APP.xmpp.addListener(XMPPEvents.CALL_INCOMING, function (event) {
  5077. // startRemoteStats(event.peerconnection);
  5078. //// CallStats.init(event);
  5079. // });
  5080. //// APP.xmpp.addListener(XMPPEvents.PEERCONNECTION_READY, function (session) {
  5081. //// CallStats.init(session);
  5082. //// });
  5083. // //FIXME: that event is changed to TRACK_MUTE_CHANGED
  5084. //// APP.RTC.addListener(RTCEvents.AUDIO_MUTE, function (mute) {
  5085. //// CallStats.sendMuteEvent(mute, "audio");
  5086. //// });
  5087. //// APP.xmpp.addListener(XMPPEvents.CONFERENCE_SETUP_FAILED, function () {
  5088. //// CallStats.sendSetupFailedEvent();
  5089. //// });
  5090. // //FIXME: that event is changed to TRACK_MUTE_CHANGED
  5091. //// APP.RTC.addListener(RTCEvents.VIDEO_MUTE, function (mute) {
  5092. //// CallStats.sendMuteEvent(mute, "video");
  5093. //// });
  5094. // }
  5095. //};
  5096. module.exports = Statistics;
  5097. },{"../../service/statistics/Events":89,"../../service/statistics/constants":90,"./LocalStatsCollector.js":22,"./RTPStatsCollector.js":23,"events":44}],25:[function(require,module,exports){
  5098. /**
  5099. /**
  5100. * @const
  5101. */
  5102. var ALPHANUM = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
  5103. /**
  5104. * Hexadecimal digits.
  5105. * @const
  5106. */
  5107. var HEX_DIGITS = '0123456789abcdef';
  5108. /**
  5109. * Generates random int within the range [min, max]
  5110. * @param min the minimum value for the generated number
  5111. * @param max the maximum value for the generated number
  5112. * @returns random int number
  5113. */
  5114. function randomInt(min, max) {
  5115. return Math.floor(Math.random() * (max - min + 1)) + min;
  5116. }
  5117. /**
  5118. * Get random element from array or string.
  5119. * @param {Array|string} arr source
  5120. * @returns array element or string character
  5121. */
  5122. function randomElement(arr) {
  5123. return arr[randomInt(0, arr.length - 1)];
  5124. }
  5125. /**
  5126. * Generate random alphanumeric string.
  5127. * @param {number} length expected string length
  5128. * @returns {string} random string of specified length
  5129. */
  5130. function randomAlphanumStr(length) {
  5131. var result = '';
  5132. for (var i = 0; i < length; i += 1) {
  5133. result += randomElement(ALPHANUM);
  5134. }
  5135. return result;
  5136. }
  5137. /**
  5138. * Exported interface.
  5139. */
  5140. var RandomUtil = {
  5141. /**
  5142. * Returns a random hex digit.
  5143. * @returns {*}
  5144. */
  5145. randomHexDigit: function() {
  5146. return randomElement(HEX_DIGITS);
  5147. },
  5148. /**
  5149. * Returns a random string of hex digits with length 'len'.
  5150. * @param len the length.
  5151. */
  5152. randomHexString: function (len) {
  5153. var ret = '';
  5154. while (len--) {
  5155. ret += this.randomHexDigit();
  5156. }
  5157. return ret;
  5158. },
  5159. randomElement: randomElement,
  5160. randomAlphanumStr: randomAlphanumStr
  5161. };
  5162. module.exports = RandomUtil;
  5163. },{}],26:[function(require,module,exports){
  5164. (function (__filename){
  5165. /* global Strophe, $, $pres, $iq, $msg */
  5166. /* jshint -W101,-W069 */
  5167. var logger = require("jitsi-meet-logger").getLogger(__filename);
  5168. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  5169. var Moderator = require("./moderator");
  5170. var EventEmitter = require("events");
  5171. var Recorder = require("./recording");
  5172. var JIBRI_XMLNS = 'http://jitsi.org/protocol/jibri';
  5173. var parser = {
  5174. packet2JSON: function (packet, nodes) {
  5175. var self = this;
  5176. $(packet).children().each(function (index) {
  5177. var tagName = $(this).prop("tagName");
  5178. var node = {
  5179. tagName: tagName
  5180. };
  5181. node.attributes = {};
  5182. $($(this)[0].attributes).each(function( index, attr ) {
  5183. node.attributes[ attr.name ] = attr.value;
  5184. });
  5185. var text = Strophe.getText($(this)[0]);
  5186. if (text) {
  5187. node.value = text;
  5188. }
  5189. node.children = [];
  5190. nodes.push(node);
  5191. self.packet2JSON($(this), node.children);
  5192. });
  5193. },
  5194. JSON2packet: function (nodes, packet) {
  5195. for(var i = 0; i < nodes.length; i++) {
  5196. var node = nodes[i];
  5197. if(!node || node === null){
  5198. continue;
  5199. }
  5200. packet.c(node.tagName, node.attributes);
  5201. if(node.value)
  5202. packet.t(node.value);
  5203. if(node.children)
  5204. this.JSON2packet(node.children, packet);
  5205. packet.up();
  5206. }
  5207. // packet.up();
  5208. }
  5209. };
  5210. /**
  5211. * Returns array of JS objects from the presence JSON associated with the passed nodeName
  5212. * @param pres the presence JSON
  5213. * @param nodeName the name of the node (videomuted, audiomuted, etc)
  5214. */
  5215. function filterNodeFromPresenceJSON(pres, nodeName){
  5216. var res = [];
  5217. for(var i = 0; i < pres.length; i++)
  5218. if(pres[i].tagName === nodeName)
  5219. res.push(pres[i]);
  5220. return res;
  5221. }
  5222. function ChatRoom(connection, jid, password, XMPP, options) {
  5223. this.eventEmitter = new EventEmitter();
  5224. this.xmpp = XMPP;
  5225. this.connection = connection;
  5226. this.roomjid = Strophe.getBareJidFromJid(jid);
  5227. this.myroomjid = jid;
  5228. this.password = password;
  5229. logger.info("Joined MUC as " + this.myroomjid);
  5230. this.members = {};
  5231. this.presMap = {};
  5232. this.presHandlers = {};
  5233. this.joined = false;
  5234. this.role = 'none';
  5235. this.focusMucJid = null;
  5236. this.bridgeIsDown = false;
  5237. this.options = options || {};
  5238. this.moderator = new Moderator(this.roomjid, this.xmpp, this.eventEmitter);
  5239. this.initPresenceMap();
  5240. this.session = null;
  5241. var self = this;
  5242. this.lastPresences = {};
  5243. this.phoneNumber = null;
  5244. this.phonePin = null;
  5245. }
  5246. ChatRoom.prototype.initPresenceMap = function () {
  5247. this.presMap['to'] = this.myroomjid;
  5248. this.presMap['xns'] = 'http://jabber.org/protocol/muc';
  5249. this.presMap["nodes"] = [];
  5250. this.presMap["nodes"].push( {
  5251. "tagName": "user-agent",
  5252. "value": navigator.userAgent,
  5253. "attributes": {xmlns: 'http://jitsi.org/jitmeet/user-agent'}
  5254. });
  5255. };
  5256. ChatRoom.prototype.updateDeviceAvailability = function (devices) {
  5257. this.presMap["nodes"].push( {
  5258. "tagName": "devices",
  5259. "children": [
  5260. {
  5261. "tagName": "audio",
  5262. "value": devices.audio,
  5263. },
  5264. {
  5265. "tagName": "video",
  5266. "value": devices.video,
  5267. }
  5268. ]
  5269. });
  5270. };
  5271. ChatRoom.prototype.join = function (password, tokenPassword) {
  5272. if(password)
  5273. this.password = password;
  5274. var self = this;
  5275. this.moderator.allocateConferenceFocus(function()
  5276. {
  5277. self.sendPresence(tokenPassword);
  5278. }.bind(this));
  5279. };
  5280. ChatRoom.prototype.sendPresence = function (tokenPassword) {
  5281. if (!this.presMap['to']) {
  5282. // Too early to send presence - not initialized
  5283. return;
  5284. }
  5285. var pres = $pres({to: this.presMap['to'] });
  5286. pres.c('x', {xmlns: this.presMap['xns']});
  5287. if (this.password) {
  5288. pres.c('password').t(this.password).up();
  5289. }
  5290. pres.up();
  5291. // Send XEP-0115 'c' stanza that contains our capabilities info
  5292. if (this.connection.caps) {
  5293. this.connection.caps.node = this.xmpp.options.clientNode;
  5294. pres.c('c', this.connection.caps.generateCapsAttrs()).up();
  5295. }
  5296. if (tokenPassword) {
  5297. pres.c('token', { xmlns: 'http://jitsi.org/jitmeet/auth-token'})
  5298. .t(tokenPassword).up();
  5299. }
  5300. parser.JSON2packet(this.presMap.nodes, pres);
  5301. this.connection.send(pres);
  5302. };
  5303. ChatRoom.prototype.doLeave = function () {
  5304. logger.log("do leave", this.myroomjid);
  5305. var pres = $pres({to: this.myroomjid, type: 'unavailable' });
  5306. this.presMap.length = 0;
  5307. this.connection.send(pres);
  5308. };
  5309. ChatRoom.prototype.createNonAnonymousRoom = function () {
  5310. // http://xmpp.org/extensions/xep-0045.html#createroom-reserved
  5311. var getForm = $iq({type: 'get', to: this.roomjid})
  5312. .c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'})
  5313. .c('x', {xmlns: 'jabber:x:data', type: 'submit'});
  5314. var self = this;
  5315. this.connection.sendIQ(getForm, function (form) {
  5316. if (!$(form).find(
  5317. '>query>x[xmlns="jabber:x:data"]' +
  5318. '>field[var="muc#roomconfig_whois"]').length) {
  5319. logger.error('non-anonymous rooms not supported');
  5320. return;
  5321. }
  5322. var formSubmit = $iq({to: this.roomjid, type: 'set'})
  5323. .c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'});
  5324. formSubmit.c('x', {xmlns: 'jabber:x:data', type: 'submit'});
  5325. formSubmit.c('field', {'var': 'FORM_TYPE'})
  5326. .c('value')
  5327. .t('http://jabber.org/protocol/muc#roomconfig').up().up();
  5328. formSubmit.c('field', {'var': 'muc#roomconfig_whois'})
  5329. .c('value').t('anyone').up().up();
  5330. self.connection.sendIQ(formSubmit);
  5331. }, function (error) {
  5332. logger.error("Error getting room configuration form");
  5333. });
  5334. };
  5335. ChatRoom.prototype.onPresence = function (pres) {
  5336. console.log(pres);
  5337. var from = pres.getAttribute('from');
  5338. // Parse roles.
  5339. var member = {};
  5340. member.show = $(pres).find('>show').text();
  5341. member.status = $(pres).find('>status').text();
  5342. var tmp = $(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>item');
  5343. member.affiliation = tmp.attr('affiliation');
  5344. member.role = tmp.attr('role');
  5345. // Focus recognition
  5346. member.jid = tmp.attr('jid');
  5347. member.isFocus = false;
  5348. if (member.jid
  5349. && member.jid.indexOf(this.moderator.getFocusUserJid() + "/") === 0) {
  5350. member.isFocus = true;
  5351. }
  5352. $(pres).find(">x").remove();
  5353. var nodes = [];
  5354. parser.packet2JSON(pres, nodes);
  5355. this.lastPresences[from] = nodes;
  5356. var jibri = null;
  5357. for(var i = 0; i < nodes.length; i++)
  5358. {
  5359. var node = nodes[i];
  5360. switch(node.tagName)
  5361. {
  5362. case "nick":
  5363. member.nick = node.value;
  5364. if(!member.isFocus) {
  5365. var displayName = !this.xmpp.options.displayJids
  5366. ? member.nick : Strophe.getResourceFromJid(from);
  5367. if (displayName && displayName.length > 0) {
  5368. this.eventEmitter.emit(XMPPEvents.DISPLAY_NAME_CHANGED, from, displayName);
  5369. }
  5370. logger.info("Display name: " + displayName, pres);
  5371. }
  5372. break;
  5373. case "userId":
  5374. member.id = node.value;
  5375. break;
  5376. case "email":
  5377. member.email = node.value;
  5378. break;
  5379. case "bridgeIsDown":
  5380. if(!this.bridgeIsDown) {
  5381. this.bridgeIsDown = true;
  5382. this.eventEmitter.emit(XMPPEvents.BRIDGE_DOWN);
  5383. }
  5384. break;
  5385. case "jibri-recording-status":
  5386. var jibri = node;
  5387. break;
  5388. case "call-control":
  5389. console.log(pres);
  5390. var att = node.attributes;
  5391. if(!att)
  5392. break;
  5393. this.phoneNumber = att.phone || null;
  5394. this.phonePin = att.pin || null;
  5395. this.eventEmitter.emit(XMPPEvents.PHONE_NUMBER_CHANGED);
  5396. break;
  5397. default :
  5398. this.processNode(node, from);
  5399. }
  5400. }
  5401. if (from == this.myroomjid) {
  5402. if (member.affiliation == 'owner')
  5403. if (this.role !== member.role) {
  5404. this.role = member.role;
  5405. this.eventEmitter.emit(XMPPEvents.LOCAL_ROLE_CHANGED, this.role);
  5406. }
  5407. if (!this.joined) {
  5408. this.joined = true;
  5409. console.log("(TIME) MUC joined:\t", window.performance.now());
  5410. this.eventEmitter.emit(XMPPEvents.MUC_JOINED, from, member);
  5411. }
  5412. } else if (this.members[from] === undefined) {
  5413. // new participant
  5414. this.members[from] = member;
  5415. logger.log('entered', from, member);
  5416. if (member.isFocus) {
  5417. this.focusMucJid = from;
  5418. if(!this.recording) {
  5419. this.recording = new Recorder(this.eventEmitter, this.connection,
  5420. this.focusMucJid);
  5421. if(this.lastJibri)
  5422. this.recording.handleJibriPresence(this.lastJibri);
  5423. }
  5424. logger.info("Ignore focus: " + from + ", real JID: " + member.jid);
  5425. }
  5426. else {
  5427. this.eventEmitter.emit(XMPPEvents.MUC_MEMBER_JOINED, from, member.id || member.email, member.nick);
  5428. }
  5429. } else {
  5430. // Presence update for existing participant
  5431. // Watch role change:
  5432. if (this.members[from].role != member.role) {
  5433. this.members[from].role = member.role;
  5434. this.eventEmitter.emit(XMPPEvents.MUC_ROLE_CHANGED, from, member.role);
  5435. }
  5436. // store the new display name
  5437. if(member.displayName)
  5438. this.members[from].displayName = member.displayName;
  5439. }
  5440. if(!member.isFocus)
  5441. this.eventEmitter.emit(XMPPEvents.USER_ID_CHANGED, from, member.id || member.email);
  5442. // Trigger status message update
  5443. if (member.status) {
  5444. this.eventEmitter.emit(XMPPEvents.PRESENCE_STATUS, from, member);
  5445. }
  5446. if(jibri)
  5447. {
  5448. this.lastJibri = jibri;
  5449. if(this.recording)
  5450. this.recording.handleJibriPresence(jibri);
  5451. }
  5452. };
  5453. ChatRoom.prototype.processNode = function (node, from) {
  5454. if(this.presHandlers[node.tagName])
  5455. this.presHandlers[node.tagName](node, from);
  5456. };
  5457. ChatRoom.prototype.sendMessage = function (body, nickname) {
  5458. var msg = $msg({to: this.roomjid, type: 'groupchat'});
  5459. msg.c('body', body).up();
  5460. if (nickname) {
  5461. msg.c('nick', {xmlns: 'http://jabber.org/protocol/nick'}).t(nickname).up().up();
  5462. }
  5463. this.connection.send(msg);
  5464. this.eventEmitter.emit(XMPPEvents.SENDING_CHAT_MESSAGE, body);
  5465. };
  5466. ChatRoom.prototype.setSubject = function (subject) {
  5467. var msg = $msg({to: this.roomjid, type: 'groupchat'});
  5468. msg.c('subject', subject);
  5469. this.connection.send(msg);
  5470. logger.log("topic changed to " + subject);
  5471. };
  5472. ChatRoom.prototype.onParticipantLeft = function (jid) {
  5473. delete this.lastPresences[jid];
  5474. this.eventEmitter.emit(XMPPEvents.MUC_MEMBER_LEFT, jid);
  5475. this.moderator.onMucMemberLeft(jid);
  5476. };
  5477. ChatRoom.prototype.onPresenceUnavailable = function (pres, from) {
  5478. // room destroyed ?
  5479. if ($(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]' +
  5480. '>destroy').length) {
  5481. var reason;
  5482. var reasonSelect = $(pres).find(
  5483. '>x[xmlns="http://jabber.org/protocol/muc#user"]' +
  5484. '>destroy>reason');
  5485. if (reasonSelect.length) {
  5486. reason = reasonSelect.text();
  5487. }
  5488. this.xmpp.disposeConference(false);
  5489. this.eventEmitter.emit(XMPPEvents.MUC_DESTROYED, reason);
  5490. delete this.connection.emuc.rooms[Strophe.getBareJidFromJid(from)];
  5491. return true;
  5492. }
  5493. // Status code 110 indicates that this notification is "self-presence".
  5494. if (!$(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>status[code="110"]').length) {
  5495. delete this.members[from];
  5496. this.onParticipantLeft(from);
  5497. }
  5498. // If the status code is 110 this means we're leaving and we would like
  5499. // to remove everyone else from our view, so we trigger the event.
  5500. else if (Object.keys(this.members).length > 1) {
  5501. for (var i in this.members) {
  5502. var member = this.members[i];
  5503. delete this.members[i];
  5504. this.onParticipantLeft(member);
  5505. }
  5506. }
  5507. if ($(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>status[code="307"]').length) {
  5508. if (this.myroomjid === from) {
  5509. this.xmpp.disposeConference(false);
  5510. this.eventEmitter.emit(XMPPEvents.KICKED);
  5511. }
  5512. }
  5513. };
  5514. ChatRoom.prototype.onMessage = function (msg, from) {
  5515. var nick =
  5516. $(msg).find('>nick[xmlns="http://jabber.org/protocol/nick"]')
  5517. .text() ||
  5518. Strophe.getResourceFromJid(from);
  5519. var txt = $(msg).find('>body').text();
  5520. var type = msg.getAttribute("type");
  5521. if (type == "error") {
  5522. this.eventEmitter.emit(XMPPEvents.CHAT_ERROR_RECEIVED,
  5523. $(msg).find('>text').text(), txt);
  5524. return true;
  5525. }
  5526. var subject = $(msg).find('>subject');
  5527. if (subject.length) {
  5528. var subjectText = subject.text();
  5529. if (subjectText || subjectText === "") {
  5530. this.eventEmitter.emit(XMPPEvents.SUBJECT_CHANGED, subjectText);
  5531. logger.log("Subject is changed to " + subjectText);
  5532. }
  5533. }
  5534. // xep-0203 delay
  5535. var stamp = $(msg).find('>delay').attr('stamp');
  5536. if (!stamp) {
  5537. // or xep-0091 delay, UTC timestamp
  5538. stamp = $(msg).find('>[xmlns="jabber:x:delay"]').attr('stamp');
  5539. if (stamp) {
  5540. // the format is CCYYMMDDThh:mm:ss
  5541. var dateParts = stamp.match(/(\d{4})(\d{2})(\d{2}T\d{2}:\d{2}:\d{2})/);
  5542. stamp = dateParts[1] + "-" + dateParts[2] + "-" + dateParts[3] + "Z";
  5543. }
  5544. }
  5545. if (txt) {
  5546. logger.log('chat', nick, txt);
  5547. this.eventEmitter.emit(XMPPEvents.MESSAGE_RECEIVED,
  5548. from, nick, txt, this.myroomjid, stamp);
  5549. }
  5550. };
  5551. ChatRoom.prototype.onPresenceError = function (pres, from) {
  5552. if ($(pres).find('>error[type="auth"]>not-authorized[xmlns="urn:ietf:params:xml:ns:xmpp-stanzas"]').length) {
  5553. logger.log('on password required', from);
  5554. this.eventEmitter.emit(XMPPEvents.PASSWORD_REQUIRED);
  5555. } else if ($(pres).find(
  5556. '>error[type="cancel"]>not-allowed[xmlns="urn:ietf:params:xml:ns:xmpp-stanzas"]').length) {
  5557. var toDomain = Strophe.getDomainFromJid(pres.getAttribute('to'));
  5558. if (toDomain === this.xmpp.options.hosts.anonymousdomain) {
  5559. // enter the room by replying with 'not-authorized'. This would
  5560. // result in reconnection from authorized domain.
  5561. // We're either missing Jicofo/Prosody config for anonymous
  5562. // domains or something is wrong.
  5563. this.eventEmitter.emit(XMPPEvents.ROOM_JOIN_ERROR, pres);
  5564. } else {
  5565. logger.warn('onPresError ', pres);
  5566. this.eventEmitter.emit(XMPPEvents.ROOM_CONNECT_ERROR, pres);
  5567. }
  5568. } else {
  5569. logger.warn('onPresError ', pres);
  5570. this.eventEmitter.emit(XMPPEvents.ROOM_CONNECT_ERROR, pres);
  5571. }
  5572. };
  5573. ChatRoom.prototype.kick = function (jid) {
  5574. var kickIQ = $iq({to: this.roomjid, type: 'set'})
  5575. .c('query', {xmlns: 'http://jabber.org/protocol/muc#admin'})
  5576. .c('item', {nick: Strophe.getResourceFromJid(jid), role: 'none'})
  5577. .c('reason').t('You have been kicked.').up().up().up();
  5578. this.connection.sendIQ(
  5579. kickIQ,
  5580. function (result) {
  5581. logger.log('Kick participant with jid: ', jid, result);
  5582. },
  5583. function (error) {
  5584. logger.log('Kick participant error: ', error);
  5585. });
  5586. };
  5587. ChatRoom.prototype.lockRoom = function (key, onSuccess, onError, onNotSupported) {
  5588. //http://xmpp.org/extensions/xep-0045.html#roomconfig
  5589. var ob = this;
  5590. this.connection.sendIQ($iq({to: this.roomjid, type: 'get'}).c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'}),
  5591. function (res) {
  5592. if ($(res).find('>query>x[xmlns="jabber:x:data"]>field[var="muc#roomconfig_roomsecret"]').length) {
  5593. var formsubmit = $iq({to: ob.roomjid, type: 'set'}).c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'});
  5594. formsubmit.c('x', {xmlns: 'jabber:x:data', type: 'submit'});
  5595. formsubmit.c('field', {'var': 'FORM_TYPE'}).c('value').t('http://jabber.org/protocol/muc#roomconfig').up().up();
  5596. formsubmit.c('field', {'var': 'muc#roomconfig_roomsecret'}).c('value').t(key).up().up();
  5597. // Fixes a bug in prosody 0.9.+ https://code.google.com/p/lxmppd/issues/detail?id=373
  5598. formsubmit.c('field', {'var': 'muc#roomconfig_whois'}).c('value').t('anyone').up().up();
  5599. // FIXME: is muc#roomconfig_passwordprotectedroom required?
  5600. ob.connection.sendIQ(formsubmit,
  5601. onSuccess,
  5602. onError);
  5603. } else {
  5604. onNotSupported();
  5605. }
  5606. }, onError);
  5607. };
  5608. ChatRoom.prototype.addToPresence = function (key, values) {
  5609. values.tagName = key;
  5610. this.presMap["nodes"].push(values);
  5611. };
  5612. ChatRoom.prototype.removeFromPresence = function (key) {
  5613. for(var i = 0; i < this.presMap.nodes.length; i++)
  5614. {
  5615. if(key === this.presMap.nodes[i].tagName)
  5616. this.presMap.nodes.splice(i, 1);
  5617. }
  5618. };
  5619. ChatRoom.prototype.addPresenceListener = function (name, handler) {
  5620. this.presHandlers[name] = handler;
  5621. };
  5622. ChatRoom.prototype.removePresenceListener = function (name) {
  5623. delete this.presHandlers[name];
  5624. };
  5625. ChatRoom.prototype.isModerator = function () {
  5626. return this.role === 'moderator';
  5627. };
  5628. ChatRoom.prototype.getMemberRole = function (peerJid) {
  5629. if (this.members[peerJid]) {
  5630. return this.members[peerJid].role;
  5631. }
  5632. return null;
  5633. };
  5634. ChatRoom.prototype.setJingleSession = function(session){
  5635. this.session = session;
  5636. this.session.room = this;
  5637. };
  5638. ChatRoom.prototype.removeStream = function (stream, callback) {
  5639. if(!this.session)
  5640. return;
  5641. this.session.removeStream(stream, callback);
  5642. };
  5643. ChatRoom.prototype.switchStreams = function (stream, oldStream, callback, isAudio) {
  5644. if(this.session) {
  5645. // FIXME: will block switchInProgress on true value in case of exception
  5646. this.session.switchStreams(stream, oldStream, callback, isAudio);
  5647. } else {
  5648. // We are done immediately
  5649. logger.warn("No conference handler or conference not started yet");
  5650. callback();
  5651. }
  5652. };
  5653. ChatRoom.prototype.addStream = function (stream, callback) {
  5654. if(this.session) {
  5655. // FIXME: will block switchInProgress on true value in case of exception
  5656. this.session.addStream(stream, callback);
  5657. } else {
  5658. // We are done immediately
  5659. logger.warn("No conference handler or conference not started yet");
  5660. callback();
  5661. }
  5662. };
  5663. ChatRoom.prototype.setVideoMute = function (mute, callback, options) {
  5664. var self = this;
  5665. var localCallback = function (mute) {
  5666. self.sendVideoInfoPresence(mute);
  5667. if(callback)
  5668. callback(mute);
  5669. };
  5670. if(this.session)
  5671. {
  5672. this.session.setVideoMute(
  5673. mute, localCallback, options);
  5674. }
  5675. else {
  5676. localCallback(mute);
  5677. }
  5678. };
  5679. ChatRoom.prototype.setAudioMute = function (mute, callback) {
  5680. //This will be for remote streams only
  5681. // if (this.forceMuted && !mute) {
  5682. // logger.info("Asking focus for unmute");
  5683. // this.connection.moderate.setMute(this.connection.emuc.myroomjid, mute);
  5684. // // FIXME: wait for result before resetting muted status
  5685. // this.forceMuted = false;
  5686. // }
  5687. return this.sendAudioInfoPresence(mute, callback);
  5688. };
  5689. ChatRoom.prototype.addAudioInfoToPresence = function (mute) {
  5690. this.removeFromPresence("audiomuted");
  5691. this.addToPresence("audiomuted",
  5692. {attributes:
  5693. {"audions": "http://jitsi.org/jitmeet/audio"},
  5694. value: mute.toString()});
  5695. };
  5696. ChatRoom.prototype.sendAudioInfoPresence = function(mute, callback) {
  5697. this.addAudioInfoToPresence(mute);
  5698. if(this.connection) {
  5699. this.sendPresence();
  5700. }
  5701. if(callback)
  5702. callback();
  5703. };
  5704. ChatRoom.prototype.addVideoInfoToPresence = function (mute) {
  5705. this.removeFromPresence("videomuted");
  5706. this.addToPresence("videomuted",
  5707. {attributes:
  5708. {"videons": "http://jitsi.org/jitmeet/video"},
  5709. value: mute.toString()});
  5710. };
  5711. ChatRoom.prototype.sendVideoInfoPresence = function (mute) {
  5712. this.addVideoInfoToPresence(mute);
  5713. if(!this.connection)
  5714. return;
  5715. this.sendPresence();
  5716. };
  5717. ChatRoom.prototype.addListener = function(type, listener) {
  5718. this.eventEmitter.on(type, listener);
  5719. };
  5720. ChatRoom.prototype.removeListener = function (type, listener) {
  5721. this.eventEmitter.removeListener(type, listener);
  5722. };
  5723. ChatRoom.prototype.remoteStreamAdded = function(data, sid, thessrc) {
  5724. if(this.lastPresences[data.peerjid])
  5725. {
  5726. var pres = this.lastPresences[data.peerjid];
  5727. var audiomuted = filterNodeFromPresenceJSON(pres, "audiomuted");
  5728. var videomuted = filterNodeFromPresenceJSON(pres, "videomuted");
  5729. data.videomuted = ((videomuted.length > 0
  5730. && videomuted[0]
  5731. && videomuted[0]["value"] === "true")? true : false);
  5732. data.audiomuted = ((audiomuted.length > 0
  5733. && audiomuted[0]
  5734. && audiomuted[0]["value"] === "true")? true : false);
  5735. }
  5736. this.eventEmitter.emit(XMPPEvents.REMOTE_STREAM_RECEIVED, data, sid, thessrc);
  5737. };
  5738. ChatRoom.prototype.getJidBySSRC = function (ssrc) {
  5739. if (!this.session)
  5740. return null;
  5741. return this.session.getSsrcOwner(ssrc);
  5742. };
  5743. /**
  5744. * Returns true if the recording is supproted and false if not.
  5745. */
  5746. ChatRoom.prototype.isRecordingSupported = function () {
  5747. if(this.recording)
  5748. return this.recording.isSupported();
  5749. return false;
  5750. };
  5751. /**
  5752. * Returns null if the recording is not supported, "on" if the recording started
  5753. * and "off" if the recording is not started.
  5754. */
  5755. ChatRoom.prototype.getRecordingState = function () {
  5756. if(this.recording)
  5757. return this.recording.getState();
  5758. return "off";
  5759. }
  5760. /**
  5761. * Returns the url of the recorded video.
  5762. */
  5763. ChatRoom.prototype.getRecordingURL = function () {
  5764. if(this.recording)
  5765. return this.recording.getURL();
  5766. return null;
  5767. }
  5768. /**
  5769. * Starts/stops the recording
  5770. * @param token token for authentication
  5771. */
  5772. ChatRoom.prototype.toggleRecording = function (token, followEntity) {
  5773. if(this.recording)
  5774. return this.recording.toggleRecording(token, followEntity);
  5775. return new Promise(function(resolve, reject){
  5776. reject(new Error("The conference is not created yet!"))});
  5777. }
  5778. /**
  5779. * Dials a number.
  5780. * @param number the number
  5781. */
  5782. ChatRoom.prototype.dial = function (number) {
  5783. return this.connection.rayo.dial(number, "fromnumber",
  5784. Strophe.getNodeFromJid(this.myroomjid), this.password,
  5785. this.focusMucJid);
  5786. }
  5787. /**
  5788. * Hangup an existing call
  5789. */
  5790. ChatRoom.prototype.hangup = function () {
  5791. return this.connection.rayo.hangup();
  5792. }
  5793. /**
  5794. * Returns the phone number for joining the conference.
  5795. */
  5796. ChatRoom.prototype.getPhoneNumber = function () {
  5797. return this.phoneNumber;
  5798. }
  5799. /**
  5800. * Returns the pin for joining the conference with phone.
  5801. */
  5802. ChatRoom.prototype.getPhonePin = function () {
  5803. return this.phonePin;
  5804. }
  5805. /**
  5806. * Returns the connection state for the current session.
  5807. */
  5808. ChatRoom.prototype.getConnectionState = function () {
  5809. if(!this.session)
  5810. return null;
  5811. return this.session.getIceConnectionState();
  5812. }
  5813. module.exports = ChatRoom;
  5814. }).call(this,"/modules/xmpp/ChatRoom.js")
  5815. },{"../../service/xmpp/XMPPEvents":91,"./moderator":34,"./recording":35,"events":44,"jitsi-meet-logger":48}],27:[function(require,module,exports){
  5816. (function (__filename){
  5817. /*
  5818. * JingleSession provides an API to manage a single Jingle session. We will
  5819. * have different implementations depending on the underlying interface used
  5820. * (i.e. WebRTC and ORTC) and here we hold the code common to all of them.
  5821. */
  5822. var logger = require("jitsi-meet-logger").getLogger(__filename);
  5823. function JingleSession(me, sid, connection, service, eventEmitter) {
  5824. /**
  5825. * Our JID.
  5826. */
  5827. this.me = me;
  5828. /**
  5829. * The Jingle session identifier.
  5830. */
  5831. this.sid = sid;
  5832. /**
  5833. * The XMPP connection.
  5834. */
  5835. this.connection = connection;
  5836. /**
  5837. * The XMPP service.
  5838. */
  5839. this.service = service;
  5840. /**
  5841. * The event emitter.
  5842. */
  5843. this.eventEmitter = eventEmitter;
  5844. /**
  5845. * Whether to use dripping or not. Dripping is sending trickle candidates
  5846. * not one-by-one.
  5847. * Note: currently we do not support 'false'.
  5848. */
  5849. this.usedrip = true;
  5850. /**
  5851. * When dripping is used, stores ICE candidates which are to be sent.
  5852. */
  5853. this.drip_container = [];
  5854. // Media constraints. Is this WebRTC only?
  5855. this.media_constraints = null;
  5856. // ICE servers config (RTCConfiguration?).
  5857. this.ice_config = {};
  5858. // The chat room instance associated with the session.
  5859. this.room = null;
  5860. }
  5861. /**
  5862. * Prepares this object to initiate a session.
  5863. * @param peerjid the JID of the remote peer.
  5864. * @param isInitiator whether we will be the Jingle initiator.
  5865. * @param media_constraints
  5866. * @param ice_config
  5867. */
  5868. JingleSession.prototype.initialize = function(peerjid, isInitiator,
  5869. media_constraints, ice_config) {
  5870. this.media_constraints = media_constraints;
  5871. this.ice_config = ice_config;
  5872. if (this.state !== null) {
  5873. logger.error('attempt to initiate on session ' + this.sid +
  5874. 'in state ' + this.state);
  5875. return;
  5876. }
  5877. this.state = 'pending';
  5878. this.initiator = isInitiator ? this.me : peerjid;
  5879. this.responder = !isInitiator ? this.me : peerjid;
  5880. this.peerjid = peerjid;
  5881. this.doInitialize();
  5882. };
  5883. /**
  5884. * Finishes initialization.
  5885. */
  5886. JingleSession.prototype.doInitialize = function() {};
  5887. /**
  5888. * Adds the ICE candidates found in the 'contents' array as remote candidates?
  5889. * Note: currently only used on transport-info
  5890. */
  5891. JingleSession.prototype.addIceCandidates = function(contents) {};
  5892. /**
  5893. * Handles an 'add-source' event.
  5894. *
  5895. * @param contents an array of Jingle 'content' elements.
  5896. */
  5897. JingleSession.prototype.addSources = function(contents) {};
  5898. /**
  5899. * Handles a 'remove-source' event.
  5900. *
  5901. * @param contents an array of Jingle 'content' elements.
  5902. */
  5903. JingleSession.prototype.removeSources = function(contents) {};
  5904. /**
  5905. * Terminates this Jingle session (stops sending media and closes the streams?)
  5906. */
  5907. JingleSession.prototype.terminate = function() {};
  5908. /**
  5909. * Sends a Jingle session-terminate message to the peer and terminates the
  5910. * session.
  5911. * @param reason
  5912. * @param text
  5913. */
  5914. JingleSession.prototype.sendTerminate = function(reason, text) {};
  5915. /**
  5916. * Handles an offer from the remote peer (prepares to accept a session).
  5917. * @param jingle the 'jingle' XML element.
  5918. */
  5919. JingleSession.prototype.setOffer = function(jingle) {};
  5920. /**
  5921. * Handles an answer from the remote peer (prepares to accept a session).
  5922. * @param jingle the 'jingle' XML element.
  5923. */
  5924. JingleSession.prototype.setAnswer = function(jingle) {};
  5925. module.exports = JingleSession;
  5926. }).call(this,"/modules/xmpp/JingleSession.js")
  5927. },{"jitsi-meet-logger":48}],28:[function(require,module,exports){
  5928. (function (__filename){
  5929. /* jshint -W117 */
  5930. var logger = require("jitsi-meet-logger").getLogger(__filename);
  5931. var JingleSession = require("./JingleSession");
  5932. var TraceablePeerConnection = require("./TraceablePeerConnection");
  5933. var SDPDiffer = require("./SDPDiffer");
  5934. var SDPUtil = require("./SDPUtil");
  5935. var SDP = require("./SDP");
  5936. var async = require("async");
  5937. var transform = require("sdp-transform");
  5938. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  5939. var RTCBrowserType = require("../RTC/RTCBrowserType");
  5940. var SSRCReplacement = require("./LocalSSRCReplacement");
  5941. var RTC = require("../RTC/RTC");
  5942. // Jingle stuff
  5943. function JingleSessionPC(me, sid, connection, service) {
  5944. JingleSession.call(this, me, sid, connection, service);
  5945. this.initiator = null;
  5946. this.responder = null;
  5947. this.peerjid = null;
  5948. this.state = null;
  5949. this.localSDP = null;
  5950. this.remoteSDP = null;
  5951. this.relayedStreams = [];
  5952. this.usetrickle = true;
  5953. this.usepranswer = false; // early transport warmup -- mind you, this might fail. depends on webrtc issue 1718
  5954. this.hadstuncandidate = false;
  5955. this.hadturncandidate = false;
  5956. this.lasticecandidate = false;
  5957. this.statsinterval = null;
  5958. this.reason = null;
  5959. this.addssrc = [];
  5960. this.removessrc = [];
  5961. this.pendingop = null;
  5962. this.switchstreams = false;
  5963. this.addingStreams = false;
  5964. this.wait = true;
  5965. /**
  5966. * A map that stores SSRCs of local streams
  5967. * @type {{}} maps media type('audio' or 'video') to SSRC number
  5968. */
  5969. this.localStreamsSSRC = {};
  5970. this.ssrcOwners = {};
  5971. this.ssrcVideoTypes = {};
  5972. this.webrtcIceUdpDisable = !!this.service.options.webrtcIceUdpDisable;
  5973. this.webrtcIceTcpDisable = !!this.service.options.webrtcIceTcpDisable;
  5974. /**
  5975. * The indicator which determines whether the (local) video has been muted
  5976. * in response to a user command in contrast to an automatic decision made
  5977. * by the application logic.
  5978. */
  5979. this.videoMuteByUser = false;
  5980. this.modifySourcesQueue = async.queue(this._modifySources.bind(this), 1);
  5981. // We start with the queue paused. We resume it when the signaling state is
  5982. // stable and the ice connection state is connected.
  5983. this.modifySourcesQueue.pause();
  5984. }
  5985. //XXX this is badly broken...
  5986. JingleSessionPC.prototype = JingleSession.prototype;
  5987. JingleSessionPC.prototype.constructor = JingleSessionPC;
  5988. JingleSessionPC.prototype.setOffer = function(offer) {
  5989. this.setRemoteDescription(offer, 'offer');
  5990. };
  5991. JingleSessionPC.prototype.setAnswer = function(answer) {
  5992. this.setRemoteDescription(answer, 'answer');
  5993. };
  5994. JingleSessionPC.prototype.updateModifySourcesQueue = function() {
  5995. var signalingState = this.peerconnection.signalingState;
  5996. var iceConnectionState = this.peerconnection.iceConnectionState;
  5997. if (signalingState === 'stable' && iceConnectionState === 'connected') {
  5998. this.modifySourcesQueue.resume();
  5999. } else {
  6000. this.modifySourcesQueue.pause();
  6001. }
  6002. };
  6003. JingleSessionPC.prototype.doInitialize = function () {
  6004. var self = this;
  6005. this.hadstuncandidate = false;
  6006. this.hadturncandidate = false;
  6007. this.lasticecandidate = false;
  6008. // True if reconnect is in progress
  6009. this.isreconnect = false;
  6010. // Set to true if the connection was ever stable
  6011. this.wasstable = false;
  6012. this.peerconnection = new TraceablePeerConnection(
  6013. this.connection.jingle.ice_config,
  6014. RTC.getPCConstraints(),
  6015. this);
  6016. this.peerconnection.onicecandidate = function (event) {
  6017. var protocol;
  6018. if (event && event.candidate) {
  6019. protocol = (typeof event.candidate.protocol === 'string')
  6020. ? event.candidate.protocol.toLowerCase() : '';
  6021. if ((self.webrtcIceTcpDisable && protocol == 'tcp') ||
  6022. (self.webrtcIceUdpDisable && protocol == 'udp')) {
  6023. return;
  6024. }
  6025. }
  6026. self.sendIceCandidate(event.candidate);
  6027. };
  6028. this.peerconnection.onaddstream = function (event) {
  6029. if (event.stream.id !== 'default') {
  6030. logger.log("REMOTE STREAM ADDED: ", event.stream , event.stream.id);
  6031. self.remoteStreamAdded(event);
  6032. } else {
  6033. // This is a recvonly stream. Clients that implement Unified Plan,
  6034. // such as Firefox use recvonly "streams/channels/tracks" for
  6035. // receiving remote stream/tracks, as opposed to Plan B where there
  6036. // are only 3 channels: audio, video and data.
  6037. logger.log("RECVONLY REMOTE STREAM IGNORED: " + event.stream + " - " + event.stream.id);
  6038. }
  6039. };
  6040. this.peerconnection.onremovestream = function (event) {
  6041. // Remove the stream from remoteStreams
  6042. // FIXME: remotestreamremoved.jingle not defined anywhere(unused)
  6043. $(document).trigger('remotestreamremoved.jingle', [event, self.sid]);
  6044. };
  6045. this.peerconnection.onsignalingstatechange = function (event) {
  6046. if (!(self && self.peerconnection)) return;
  6047. if (self.peerconnection.signalingState === 'stable') {
  6048. self.wasstable = true;
  6049. }
  6050. self.updateModifySourcesQueue();
  6051. };
  6052. /**
  6053. * The oniceconnectionstatechange event handler contains the code to execute when the iceconnectionstatechange event,
  6054. * of type Event, is received by this RTCPeerConnection. Such an event is sent when the value of
  6055. * RTCPeerConnection.iceConnectionState changes.
  6056. *
  6057. * @param event the event containing information about the change
  6058. */
  6059. this.peerconnection.oniceconnectionstatechange = function (event) {
  6060. if (!(self && self.peerconnection)) return;
  6061. logger.log("(TIME) ICE " + self.peerconnection.iceConnectionState +
  6062. ":\t", window.performance.now());
  6063. self.updateModifySourcesQueue();
  6064. switch (self.peerconnection.iceConnectionState) {
  6065. case 'connected':
  6066. // Informs interested parties that the connection has been restored.
  6067. if (self.peerconnection.signalingState === 'stable' && self.isreconnect)
  6068. self.room.eventEmitter.emit(XMPPEvents.CONNECTION_RESTORED);
  6069. self.isreconnect = false;
  6070. break;
  6071. case 'disconnected':
  6072. self.isreconnect = true;
  6073. // Informs interested parties that the connection has been interrupted.
  6074. if (self.wasstable)
  6075. self.room.eventEmitter.emit(XMPPEvents.CONNECTION_INTERRUPTED);
  6076. break;
  6077. case 'failed':
  6078. self.room.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  6079. break;
  6080. }
  6081. onIceConnectionStateChange(self.sid, self);
  6082. };
  6083. this.peerconnection.onnegotiationneeded = function (event) {
  6084. self.room.eventEmitter.emit(XMPPEvents.PEERCONNECTION_READY, self);
  6085. };
  6086. this.relayedStreams.forEach(function(stream) {
  6087. self.peerconnection.addStream(stream);
  6088. });
  6089. };
  6090. function onIceConnectionStateChange(sid, session) {
  6091. switch (session.peerconnection.iceConnectionState) {
  6092. case 'checking':
  6093. session.timeChecking = (new Date()).getTime();
  6094. session.firstconnect = true;
  6095. break;
  6096. case 'completed': // on caller side
  6097. case 'connected':
  6098. if (session.firstconnect) {
  6099. session.firstconnect = false;
  6100. var metadata = {};
  6101. metadata.setupTime
  6102. = (new Date()).getTime() - session.timeChecking;
  6103. session.peerconnection.getStats(function (res) {
  6104. if(res && res.result) {
  6105. res.result().forEach(function (report) {
  6106. if (report.type == 'googCandidatePair' &&
  6107. report.stat('googActiveConnection') == 'true') {
  6108. metadata.localCandidateType
  6109. = report.stat('googLocalCandidateType');
  6110. metadata.remoteCandidateType
  6111. = report.stat('googRemoteCandidateType');
  6112. // log pair as well so we can get nice pie
  6113. // charts
  6114. metadata.candidatePair
  6115. = report.stat('googLocalCandidateType') +
  6116. ';' +
  6117. report.stat('googRemoteCandidateType');
  6118. if (report.stat('googRemoteAddress').indexOf('[') === 0)
  6119. {
  6120. metadata.ipv6 = true;
  6121. }
  6122. }
  6123. });
  6124. }
  6125. });
  6126. }
  6127. break;
  6128. }
  6129. }
  6130. JingleSessionPC.prototype.accept = function () {
  6131. this.state = 'active';
  6132. var pranswer = this.peerconnection.localDescription;
  6133. if (!pranswer || pranswer.type != 'pranswer') {
  6134. return;
  6135. }
  6136. logger.log('going from pranswer to answer');
  6137. if (this.usetrickle) {
  6138. // remove candidates already sent from session-accept
  6139. var lines = SDPUtil.find_lines(pranswer.sdp, 'a=candidate:');
  6140. for (var i = 0; i < lines.length; i++) {
  6141. pranswer.sdp = pranswer.sdp.replace(lines[i] + '\r\n', '');
  6142. }
  6143. }
  6144. while (SDPUtil.find_line(pranswer.sdp, 'a=inactive')) {
  6145. // FIXME: change any inactive to sendrecv or whatever they were originally
  6146. pranswer.sdp = pranswer.sdp.replace('a=inactive', 'a=sendrecv');
  6147. }
  6148. var prsdp = new SDP(pranswer.sdp);
  6149. if (self.webrtcIceTcpDisable) {
  6150. prsdp.removeTcpCandidates = true;
  6151. }
  6152. if (self.webrtcIceUdpDisable) {
  6153. prsdp.removeUdpCandidates = true;
  6154. }
  6155. var accept = $iq({to: this.peerjid,
  6156. type: 'set'})
  6157. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  6158. action: 'session-accept',
  6159. initiator: this.initiator,
  6160. responder: this.responder,
  6161. sid: this.sid });
  6162. // FIXME why do we generate session-accept in 3 different places ?
  6163. prsdp.toJingle(
  6164. accept,
  6165. this.initiator == this.me ? 'initiator' : 'responder');
  6166. var sdp = this.peerconnection.localDescription.sdp;
  6167. while (SDPUtil.find_line(sdp, 'a=inactive')) {
  6168. // FIXME: change any inactive to sendrecv or whatever they were originally
  6169. sdp = sdp.replace('a=inactive', 'a=sendrecv');
  6170. }
  6171. var self = this;
  6172. this.peerconnection.setLocalDescription(new RTCSessionDescription({type: 'answer', sdp: sdp}),
  6173. function () {
  6174. //logger.log('setLocalDescription success');
  6175. self.setLocalDescription();
  6176. SSRCReplacement.processSessionInit(accept);
  6177. self.connection.sendIQ(accept,
  6178. function () {
  6179. var ack = {};
  6180. ack.source = 'answer';
  6181. $(document).trigger('ack.jingle', [self.sid, ack]);
  6182. },
  6183. function (stanza) {
  6184. var error = ($(stanza).find('error').length) ? {
  6185. code: $(stanza).find('error').attr('code'),
  6186. reason: $(stanza).find('error :first')[0].tagName
  6187. }:{};
  6188. error.source = 'answer';
  6189. JingleSessionPC.onJingleError(self.sid, error);
  6190. },
  6191. 10000);
  6192. },
  6193. function (e) {
  6194. logger.error('setLocalDescription failed', e);
  6195. self.room.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  6196. }
  6197. );
  6198. };
  6199. JingleSessionPC.prototype.terminate = function (reason) {
  6200. this.state = 'ended';
  6201. this.reason = reason;
  6202. this.peerconnection.close();
  6203. if (this.statsinterval !== null) {
  6204. window.clearInterval(this.statsinterval);
  6205. this.statsinterval = null;
  6206. }
  6207. };
  6208. JingleSessionPC.prototype.active = function () {
  6209. return this.state == 'active';
  6210. };
  6211. JingleSessionPC.prototype.sendIceCandidate = function (candidate) {
  6212. var self = this;
  6213. if (candidate && !this.lasticecandidate) {
  6214. var ice = SDPUtil.iceparams(this.localSDP.media[candidate.sdpMLineIndex], this.localSDP.session);
  6215. var jcand = SDPUtil.candidateToJingle(candidate.candidate);
  6216. if (!(ice && jcand)) {
  6217. logger.error('failed to get ice && jcand');
  6218. return;
  6219. }
  6220. ice.xmlns = 'urn:xmpp:jingle:transports:ice-udp:1';
  6221. if (jcand.type === 'srflx') {
  6222. this.hadstuncandidate = true;
  6223. } else if (jcand.type === 'relay') {
  6224. this.hadturncandidate = true;
  6225. }
  6226. if (this.usetrickle) {
  6227. if (this.usedrip) {
  6228. if (this.drip_container.length === 0) {
  6229. // start 20ms callout
  6230. window.setTimeout(function () {
  6231. if (self.drip_container.length === 0) return;
  6232. self.sendIceCandidates(self.drip_container);
  6233. self.drip_container = [];
  6234. }, 20);
  6235. }
  6236. this.drip_container.push(candidate);
  6237. return;
  6238. } else {
  6239. self.sendIceCandidate([candidate]);
  6240. }
  6241. }
  6242. } else {
  6243. //logger.log('sendIceCandidate: last candidate.');
  6244. if (!this.usetrickle) {
  6245. //logger.log('should send full offer now...');
  6246. //FIXME why do we generate session-accept in 3 different places ?
  6247. var init = $iq({to: this.peerjid,
  6248. type: 'set'})
  6249. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  6250. action: this.peerconnection.localDescription.type == 'offer' ? 'session-initiate' : 'session-accept',
  6251. initiator: this.initiator,
  6252. sid: this.sid});
  6253. this.localSDP = new SDP(this.peerconnection.localDescription.sdp);
  6254. if (self.webrtcIceTcpDisable) {
  6255. this.localSDP.removeTcpCandidates = true;
  6256. }
  6257. if (self.webrtcIceUdpDisable) {
  6258. this.localSDP.removeUdpCandidates = true;
  6259. }
  6260. var sendJingle = function (ssrc) {
  6261. if(!ssrc)
  6262. ssrc = {};
  6263. self.localSDP.toJingle(
  6264. init,
  6265. self.initiator == self.me ? 'initiator' : 'responder',
  6266. ssrc);
  6267. SSRCReplacement.processSessionInit(init);
  6268. self.connection.sendIQ(init,
  6269. function () {
  6270. //logger.log('session initiate ack');
  6271. var ack = {};
  6272. ack.source = 'offer';
  6273. $(document).trigger('ack.jingle', [self.sid, ack]);
  6274. },
  6275. function (stanza) {
  6276. self.state = 'error';
  6277. self.peerconnection.close();
  6278. var error = ($(stanza).find('error').length) ? {
  6279. code: $(stanza).find('error').attr('code'),
  6280. reason: $(stanza).find('error :first')[0].tagName,
  6281. }:{};
  6282. error.source = 'offer';
  6283. JingleSessionPC.onJingleError(self.sid, error);
  6284. },
  6285. 10000);
  6286. };
  6287. sendJingle();
  6288. }
  6289. this.lasticecandidate = true;
  6290. logger.log('Have we encountered any srflx candidates? ' + this.hadstuncandidate);
  6291. logger.log('Have we encountered any relay candidates? ' + this.hadturncandidate);
  6292. if (!(this.hadstuncandidate || this.hadturncandidate) && this.peerconnection.signalingState != 'closed') {
  6293. $(document).trigger('nostuncandidates.jingle', [this.sid]);
  6294. }
  6295. }
  6296. };
  6297. JingleSessionPC.prototype.sendIceCandidates = function (candidates) {
  6298. logger.log('sendIceCandidates', candidates);
  6299. var cand = $iq({to: this.peerjid, type: 'set'})
  6300. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  6301. action: 'transport-info',
  6302. initiator: this.initiator,
  6303. sid: this.sid});
  6304. for (var mid = 0; mid < this.localSDP.media.length; mid++) {
  6305. var cands = candidates.filter(function (el) { return el.sdpMLineIndex == mid; });
  6306. var mline = SDPUtil.parse_mline(this.localSDP.media[mid].split('\r\n')[0]);
  6307. if (cands.length > 0) {
  6308. var ice = SDPUtil.iceparams(this.localSDP.media[mid], this.localSDP.session);
  6309. ice.xmlns = 'urn:xmpp:jingle:transports:ice-udp:1';
  6310. cand.c('content', {creator: this.initiator == this.me ? 'initiator' : 'responder',
  6311. name: (cands[0].sdpMid? cands[0].sdpMid : mline.media)
  6312. }).c('transport', ice);
  6313. for (var i = 0; i < cands.length; i++) {
  6314. cand.c('candidate', SDPUtil.candidateToJingle(cands[i].candidate)).up();
  6315. }
  6316. // add fingerprint
  6317. if (SDPUtil.find_line(this.localSDP.media[mid], 'a=fingerprint:', this.localSDP.session)) {
  6318. var tmp = SDPUtil.parse_fingerprint(SDPUtil.find_line(this.localSDP.media[mid], 'a=fingerprint:', this.localSDP.session));
  6319. tmp.required = true;
  6320. cand.c(
  6321. 'fingerprint',
  6322. {xmlns: 'urn:xmpp:jingle:apps:dtls:0'})
  6323. .t(tmp.fingerprint);
  6324. delete tmp.fingerprint;
  6325. cand.attrs(tmp);
  6326. cand.up();
  6327. }
  6328. cand.up(); // transport
  6329. cand.up(); // content
  6330. }
  6331. }
  6332. // might merge last-candidate notification into this, but it is called alot later. See webrtc issue #2340
  6333. //logger.log('was this the last candidate', this.lasticecandidate);
  6334. this.connection.sendIQ(cand,
  6335. function () {
  6336. var ack = {};
  6337. ack.source = 'transportinfo';
  6338. $(document).trigger('ack.jingle', [this.sid, ack]);
  6339. },
  6340. function (stanza) {
  6341. var error = ($(stanza).find('error').length) ? {
  6342. code: $(stanza).find('error').attr('code'),
  6343. reason: $(stanza).find('error :first')[0].tagName,
  6344. }:{};
  6345. error.source = 'transportinfo';
  6346. JingleSessionPC.onJingleError(this.sid, error);
  6347. },
  6348. 10000);
  6349. };
  6350. JingleSessionPC.prototype.sendOffer = function () {
  6351. //logger.log('sendOffer...');
  6352. var self = this;
  6353. this.peerconnection.createOffer(function (sdp) {
  6354. self.createdOffer(sdp);
  6355. },
  6356. function (e) {
  6357. logger.error('createOffer failed', e);
  6358. },
  6359. this.media_constraints
  6360. );
  6361. };
  6362. // FIXME createdOffer is never used in jitsi-meet
  6363. JingleSessionPC.prototype.createdOffer = function (sdp) {
  6364. //logger.log('createdOffer', sdp);
  6365. var self = this;
  6366. this.localSDP = new SDP(sdp.sdp);
  6367. //this.localSDP.mangle();
  6368. var sendJingle = function () {
  6369. var init = $iq({to: this.peerjid,
  6370. type: 'set'})
  6371. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  6372. action: 'session-initiate',
  6373. initiator: this.initiator,
  6374. sid: this.sid});
  6375. self.localSDP.toJingle(
  6376. init,
  6377. this.initiator == this.me ? 'initiator' : 'responder');
  6378. SSRCReplacement.processSessionInit(init);
  6379. self.connection.sendIQ(init,
  6380. function () {
  6381. var ack = {};
  6382. ack.source = 'offer';
  6383. $(document).trigger('ack.jingle', [self.sid, ack]);
  6384. },
  6385. function (stanza) {
  6386. self.state = 'error';
  6387. self.peerconnection.close();
  6388. var error = ($(stanza).find('error').length) ? {
  6389. code: $(stanza).find('error').attr('code'),
  6390. reason: $(stanza).find('error :first')[0].tagName,
  6391. }:{};
  6392. error.source = 'offer';
  6393. JingleSessionPC.onJingleError(self.sid, error);
  6394. },
  6395. 10000);
  6396. }
  6397. sdp.sdp = this.localSDP.raw;
  6398. this.peerconnection.setLocalDescription(sdp,
  6399. function () {
  6400. if(self.usetrickle)
  6401. {
  6402. sendJingle();
  6403. }
  6404. self.setLocalDescription();
  6405. //logger.log('setLocalDescription success');
  6406. },
  6407. function (e) {
  6408. logger.error('setLocalDescription failed', e);
  6409. self.room.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  6410. }
  6411. );
  6412. var cands = SDPUtil.find_lines(this.localSDP.raw, 'a=candidate:');
  6413. for (var i = 0; i < cands.length; i++) {
  6414. var cand = SDPUtil.parse_icecandidate(cands[i]);
  6415. if (cand.type == 'srflx') {
  6416. this.hadstuncandidate = true;
  6417. } else if (cand.type == 'relay') {
  6418. this.hadturncandidate = true;
  6419. }
  6420. }
  6421. };
  6422. JingleSessionPC.prototype.readSsrcInfo = function (contents) {
  6423. var self = this;
  6424. $(contents).each(function (idx, content) {
  6425. var name = $(content).attr('name');
  6426. var mediaType = this.getAttribute('name');
  6427. var ssrcs = $(content).find('description>source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]');
  6428. ssrcs.each(function () {
  6429. var ssrc = this.getAttribute('ssrc');
  6430. $(this).find('>ssrc-info[xmlns="http://jitsi.org/jitmeet"]').each(
  6431. function () {
  6432. var owner = this.getAttribute('owner');
  6433. self.ssrcOwners[ssrc] = owner;
  6434. }
  6435. );
  6436. });
  6437. });
  6438. };
  6439. /**
  6440. * Returns the SSRC of local audio stream.
  6441. * @param mediaType 'audio' or 'video' media type
  6442. * @returns {*} the SSRC number of local audio or video stream.
  6443. */
  6444. JingleSessionPC.prototype.getLocalSSRC = function (mediaType) {
  6445. return this.localStreamsSSRC[mediaType];
  6446. };
  6447. JingleSessionPC.prototype.getSsrcOwner = function (ssrc) {
  6448. return this.ssrcOwners[ssrc];
  6449. };
  6450. JingleSessionPC.prototype.setRemoteDescription = function (elem, desctype) {
  6451. //logger.log('setting remote description... ', desctype);
  6452. this.remoteSDP = new SDP('');
  6453. if (self.webrtcIceTcpDisable) {
  6454. this.remoteSDP.removeTcpCandidates = true;
  6455. }
  6456. if (self.webrtcIceUdpDisable) {
  6457. this.remoteSDP.removeUdpCandidates = true;
  6458. }
  6459. this.remoteSDP.fromJingle(elem);
  6460. this.readSsrcInfo($(elem).find(">content"));
  6461. if (this.peerconnection.remoteDescription) {
  6462. logger.log('setRemoteDescription when remote description is not null, should be pranswer', this.peerconnection.remoteDescription);
  6463. if (this.peerconnection.remoteDescription.type == 'pranswer') {
  6464. var pranswer = new SDP(this.peerconnection.remoteDescription.sdp);
  6465. for (var i = 0; i < pranswer.media.length; i++) {
  6466. // make sure we have ice ufrag and pwd
  6467. if (!SDPUtil.find_line(this.remoteSDP.media[i], 'a=ice-ufrag:', this.remoteSDP.session)) {
  6468. if (SDPUtil.find_line(pranswer.media[i], 'a=ice-ufrag:', pranswer.session)) {
  6469. this.remoteSDP.media[i] += SDPUtil.find_line(pranswer.media[i], 'a=ice-ufrag:', pranswer.session) + '\r\n';
  6470. } else {
  6471. logger.warn('no ice ufrag?');
  6472. }
  6473. if (SDPUtil.find_line(pranswer.media[i], 'a=ice-pwd:', pranswer.session)) {
  6474. this.remoteSDP.media[i] += SDPUtil.find_line(pranswer.media[i], 'a=ice-pwd:', pranswer.session) + '\r\n';
  6475. } else {
  6476. logger.warn('no ice pwd?');
  6477. }
  6478. }
  6479. // copy over candidates
  6480. var lines = SDPUtil.find_lines(pranswer.media[i], 'a=candidate:');
  6481. for (var j = 0; j < lines.length; j++) {
  6482. this.remoteSDP.media[i] += lines[j] + '\r\n';
  6483. }
  6484. }
  6485. this.remoteSDP.raw = this.remoteSDP.session + this.remoteSDP.media.join('');
  6486. }
  6487. }
  6488. var remotedesc = new RTCSessionDescription({type: desctype, sdp: this.remoteSDP.raw});
  6489. this.peerconnection.setRemoteDescription(remotedesc,
  6490. function () {
  6491. //logger.log('setRemoteDescription success');
  6492. },
  6493. function (e) {
  6494. logger.error('setRemoteDescription error', e);
  6495. JingleSessionPC.onJingleFatalError(self, e);
  6496. }
  6497. );
  6498. };
  6499. /**
  6500. * Adds remote ICE candidates to this Jingle session.
  6501. * @param elem An array of Jingle "content" elements?
  6502. */
  6503. JingleSessionPC.prototype.addIceCandidate = function (elem) {
  6504. var self = this;
  6505. if (this.peerconnection.signalingState == 'closed') {
  6506. return;
  6507. }
  6508. if (!this.peerconnection.remoteDescription && this.peerconnection.signalingState == 'have-local-offer') {
  6509. logger.log('trickle ice candidate arriving before session accept...');
  6510. // create a PRANSWER for setRemoteDescription
  6511. if (!this.remoteSDP) {
  6512. var cobbled = 'v=0\r\n' +
  6513. 'o=- 1923518516 2 IN IP4 0.0.0.0\r\n' +// FIXME
  6514. 's=-\r\n' +
  6515. 't=0 0\r\n';
  6516. // first, take some things from the local description
  6517. for (var i = 0; i < this.localSDP.media.length; i++) {
  6518. cobbled += SDPUtil.find_line(this.localSDP.media[i], 'm=') + '\r\n';
  6519. cobbled += SDPUtil.find_lines(this.localSDP.media[i], 'a=rtpmap:').join('\r\n') + '\r\n';
  6520. if (SDPUtil.find_line(this.localSDP.media[i], 'a=mid:')) {
  6521. cobbled += SDPUtil.find_line(this.localSDP.media[i], 'a=mid:') + '\r\n';
  6522. }
  6523. cobbled += 'a=inactive\r\n';
  6524. }
  6525. this.remoteSDP = new SDP(cobbled);
  6526. }
  6527. // then add things like ice and dtls from remote candidate
  6528. elem.each(function () {
  6529. for (var i = 0; i < self.remoteSDP.media.length; i++) {
  6530. if (SDPUtil.find_line(self.remoteSDP.media[i], 'a=mid:' + $(this).attr('name')) ||
  6531. self.remoteSDP.media[i].indexOf('m=' + $(this).attr('name')) === 0) {
  6532. if (!SDPUtil.find_line(self.remoteSDP.media[i], 'a=ice-ufrag:')) {
  6533. var tmp = $(this).find('transport');
  6534. self.remoteSDP.media[i] += 'a=ice-ufrag:' + tmp.attr('ufrag') + '\r\n';
  6535. self.remoteSDP.media[i] += 'a=ice-pwd:' + tmp.attr('pwd') + '\r\n';
  6536. tmp = $(this).find('transport>fingerprint');
  6537. if (tmp.length) {
  6538. self.remoteSDP.media[i] += 'a=fingerprint:' + tmp.attr('hash') + ' ' + tmp.text() + '\r\n';
  6539. } else {
  6540. logger.log('no dtls fingerprint (webrtc issue #1718?)');
  6541. self.remoteSDP.media[i] += 'a=crypto:1 AES_CM_128_HMAC_SHA1_80 inline:BAADBAADBAADBAADBAADBAADBAADBAADBAADBAAD\r\n';
  6542. }
  6543. break;
  6544. }
  6545. }
  6546. }
  6547. });
  6548. this.remoteSDP.raw = this.remoteSDP.session + this.remoteSDP.media.join('');
  6549. // we need a complete SDP with ice-ufrag/ice-pwd in all parts
  6550. // this makes the assumption that the PRANSWER is constructed such that the ice-ufrag is in all mediaparts
  6551. // but it could be in the session part as well. since the code above constructs this sdp this can't happen however
  6552. var iscomplete = this.remoteSDP.media.filter(function (mediapart) {
  6553. return SDPUtil.find_line(mediapart, 'a=ice-ufrag:');
  6554. }).length == this.remoteSDP.media.length;
  6555. if (iscomplete) {
  6556. logger.log('setting pranswer');
  6557. try {
  6558. this.peerconnection.setRemoteDescription(new RTCSessionDescription({type: 'pranswer', sdp: this.remoteSDP.raw }),
  6559. function() {
  6560. },
  6561. function(e) {
  6562. logger.log('setRemoteDescription pranswer failed', e.toString());
  6563. });
  6564. } catch (e) {
  6565. logger.error('setting pranswer failed', e);
  6566. }
  6567. } else {
  6568. //logger.log('not yet setting pranswer');
  6569. }
  6570. }
  6571. // operate on each content element
  6572. elem.each(function () {
  6573. // would love to deactivate this, but firefox still requires it
  6574. var idx = -1;
  6575. var i;
  6576. for (i = 0; i < self.remoteSDP.media.length; i++) {
  6577. if (SDPUtil.find_line(self.remoteSDP.media[i], 'a=mid:' + $(this).attr('name')) ||
  6578. self.remoteSDP.media[i].indexOf('m=' + $(this).attr('name')) === 0) {
  6579. idx = i;
  6580. break;
  6581. }
  6582. }
  6583. if (idx == -1) { // fall back to localdescription
  6584. for (i = 0; i < self.localSDP.media.length; i++) {
  6585. if (SDPUtil.find_line(self.localSDP.media[i], 'a=mid:' + $(this).attr('name')) ||
  6586. self.localSDP.media[i].indexOf('m=' + $(this).attr('name')) === 0) {
  6587. idx = i;
  6588. break;
  6589. }
  6590. }
  6591. }
  6592. var name = $(this).attr('name');
  6593. // TODO: check ice-pwd and ice-ufrag?
  6594. $(this).find('transport>candidate').each(function () {
  6595. var line, candidate;
  6596. var protocol = this.getAttribute('protocol');
  6597. protocol =
  6598. (typeof protocol === 'string') ? protocol.toLowerCase() : '';
  6599. if ((self.webrtcIceTcpDisable && protocol == 'tcp') ||
  6600. (self.webrtcIceUdpDisable && protocol == 'udp')) {
  6601. return;
  6602. }
  6603. line = SDPUtil.candidateFromJingle(this);
  6604. candidate = new RTCIceCandidate({sdpMLineIndex: idx,
  6605. sdpMid: name,
  6606. candidate: line});
  6607. try {
  6608. self.peerconnection.addIceCandidate(candidate);
  6609. } catch (e) {
  6610. logger.error('addIceCandidate failed', e.toString(), line);
  6611. }
  6612. });
  6613. });
  6614. };
  6615. JingleSessionPC.prototype.sendAnswer = function (provisional) {
  6616. //logger.log('createAnswer', provisional);
  6617. var self = this;
  6618. this.peerconnection.createAnswer(
  6619. function (sdp) {
  6620. self.createdAnswer(sdp, provisional);
  6621. },
  6622. function (e) {
  6623. logger.error('createAnswer failed', e);
  6624. self.room.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  6625. },
  6626. this.media_constraints
  6627. );
  6628. };
  6629. JingleSessionPC.prototype.createdAnswer = function (sdp, provisional) {
  6630. //logger.log('createAnswer callback');
  6631. var self = this;
  6632. this.localSDP = new SDP(sdp.sdp);
  6633. //this.localSDP.mangle();
  6634. this.usepranswer = provisional === true;
  6635. if (this.usetrickle) {
  6636. if (this.usepranswer) {
  6637. sdp.type = 'pranswer';
  6638. for (var i = 0; i < this.localSDP.media.length; i++) {
  6639. this.localSDP.media[i] = this.localSDP.media[i].replace('a=sendrecv\r\n', 'a=inactive\r\n');
  6640. }
  6641. this.localSDP.raw = this.localSDP.session + '\r\n' + this.localSDP.media.join('');
  6642. }
  6643. }
  6644. var self = this;
  6645. var sendJingle = function (ssrcs) {
  6646. // FIXME why do we generate session-accept in 3 different places ?
  6647. var accept = $iq({to: self.peerjid,
  6648. type: 'set'})
  6649. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  6650. action: 'session-accept',
  6651. initiator: self.initiator,
  6652. responder: self.responder,
  6653. sid: self.sid });
  6654. if (self.webrtcIceTcpDisable) {
  6655. self.localSDP.removeTcpCandidates = true;
  6656. }
  6657. if (self.webrtcIceUdpDisable) {
  6658. self.localSDP.removeUdpCandidates = true;
  6659. }
  6660. self.localSDP.toJingle(
  6661. accept,
  6662. self.initiator == self.me ? 'initiator' : 'responder',
  6663. ssrcs);
  6664. SSRCReplacement.processSessionInit(accept);
  6665. self.connection.sendIQ(accept,
  6666. function () {
  6667. var ack = {};
  6668. ack.source = 'answer';
  6669. $(document).trigger('ack.jingle', [self.sid, ack]);
  6670. },
  6671. function (stanza) {
  6672. var error = ($(stanza).find('error').length) ? {
  6673. code: $(stanza).find('error').attr('code'),
  6674. reason: $(stanza).find('error :first')[0].tagName,
  6675. }:{};
  6676. error.source = 'answer';
  6677. JingleSessionPC.onJingleError(self.sid, error);
  6678. },
  6679. 10000);
  6680. }
  6681. sdp.sdp = this.localSDP.raw;
  6682. this.peerconnection.setLocalDescription(sdp,
  6683. function () {
  6684. //logger.log('setLocalDescription success');
  6685. if (self.usetrickle && !self.usepranswer) {
  6686. sendJingle();
  6687. }
  6688. self.setLocalDescription();
  6689. },
  6690. function (e) {
  6691. logger.error('setLocalDescription failed', e);
  6692. self.room.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  6693. }
  6694. );
  6695. var cands = SDPUtil.find_lines(this.localSDP.raw, 'a=candidate:');
  6696. for (var j = 0; j < cands.length; j++) {
  6697. var cand = SDPUtil.parse_icecandidate(cands[j]);
  6698. if (cand.type == 'srflx') {
  6699. this.hadstuncandidate = true;
  6700. } else if (cand.type == 'relay') {
  6701. this.hadturncandidate = true;
  6702. }
  6703. }
  6704. };
  6705. JingleSessionPC.prototype.sendTerminate = function (reason, text) {
  6706. var self = this,
  6707. term = $iq({to: this.peerjid,
  6708. type: 'set'})
  6709. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  6710. action: 'session-terminate',
  6711. initiator: this.initiator,
  6712. sid: this.sid})
  6713. .c('reason')
  6714. .c(reason || 'success');
  6715. if (text) {
  6716. term.up().c('text').t(text);
  6717. }
  6718. this.connection.sendIQ(term,
  6719. function () {
  6720. self.peerconnection.close();
  6721. self.peerconnection = null;
  6722. self.terminate();
  6723. var ack = {};
  6724. ack.source = 'terminate';
  6725. $(document).trigger('ack.jingle', [self.sid, ack]);
  6726. },
  6727. function (stanza) {
  6728. var error = ($(stanza).find('error').length) ? {
  6729. code: $(stanza).find('error').attr('code'),
  6730. reason: $(stanza).find('error :first')[0].tagName,
  6731. }:{};
  6732. $(document).trigger('ack.jingle', [self.sid, error]);
  6733. },
  6734. 10000);
  6735. if (this.statsinterval !== null) {
  6736. window.clearInterval(this.statsinterval);
  6737. this.statsinterval = null;
  6738. }
  6739. };
  6740. /**
  6741. * Handles a Jingle source-add message for this Jingle session.
  6742. * @param elem An array of Jingle "content" elements.
  6743. */
  6744. JingleSessionPC.prototype.addSource = function (elem) {
  6745. var self = this;
  6746. // FIXME: dirty waiting
  6747. if (!this.peerconnection.localDescription)
  6748. {
  6749. logger.warn("addSource - localDescription not ready yet")
  6750. setTimeout(function()
  6751. {
  6752. self.addSource(elem);
  6753. },
  6754. 200
  6755. );
  6756. return;
  6757. }
  6758. logger.log('addssrc', new Date().getTime());
  6759. logger.log('ice', this.peerconnection.iceConnectionState);
  6760. this.readSsrcInfo(elem);
  6761. var sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  6762. var mySdp = new SDP(this.peerconnection.localDescription.sdp);
  6763. $(elem).each(function (idx, content) {
  6764. var name = $(content).attr('name');
  6765. var lines = '';
  6766. $(content).find('ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]').each(function() {
  6767. var semantics = this.getAttribute('semantics');
  6768. var ssrcs = $(this).find('>source').map(function () {
  6769. return this.getAttribute('ssrc');
  6770. }).get();
  6771. if (ssrcs.length) {
  6772. lines += 'a=ssrc-group:' + semantics + ' ' + ssrcs.join(' ') + '\r\n';
  6773. }
  6774. });
  6775. var tmp = $(content).find('source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]'); // can handle both >source and >description>source
  6776. tmp.each(function () {
  6777. var ssrc = $(this).attr('ssrc');
  6778. if(mySdp.containsSSRC(ssrc)){
  6779. /**
  6780. * This happens when multiple participants change their streams at the same time and
  6781. * ColibriFocus.modifySources have to wait for stable state. In the meantime multiple
  6782. * addssrc are scheduled for update IQ. See
  6783. */
  6784. logger.warn("Got add stream request for my own ssrc: "+ssrc);
  6785. return;
  6786. }
  6787. if (sdp.containsSSRC(ssrc)) {
  6788. logger.warn("Source-add request for existing SSRC: " + ssrc);
  6789. return;
  6790. }
  6791. $(this).find('>parameter').each(function () {
  6792. lines += 'a=ssrc:' + ssrc + ' ' + $(this).attr('name');
  6793. if ($(this).attr('value') && $(this).attr('value').length)
  6794. lines += ':' + $(this).attr('value');
  6795. lines += '\r\n';
  6796. });
  6797. });
  6798. sdp.media.forEach(function(media, idx) {
  6799. if (!SDPUtil.find_line(media, 'a=mid:' + name))
  6800. return;
  6801. sdp.media[idx] += lines;
  6802. if (!self.addssrc[idx]) self.addssrc[idx] = '';
  6803. self.addssrc[idx] += lines;
  6804. });
  6805. sdp.raw = sdp.session + sdp.media.join('');
  6806. });
  6807. this.modifySourcesQueue.push(function() {
  6808. // When a source is added and if this is FF, a new channel is allocated
  6809. // for receiving the added source. We need to diffuse the SSRC of this
  6810. // new recvonly channel to the rest of the peers.
  6811. logger.log('modify sources done');
  6812. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  6813. logger.log("SDPs", mySdp, newSdp);
  6814. self.notifyMySSRCUpdate(mySdp, newSdp);
  6815. });
  6816. };
  6817. /**
  6818. * Handles a Jingle source-remove message for this Jingle session.
  6819. * @param elem An array of Jingle "content" elements.
  6820. */
  6821. JingleSessionPC.prototype.removeSource = function (elem) {
  6822. var self = this;
  6823. // FIXME: dirty waiting
  6824. if (!this.peerconnection.localDescription) {
  6825. logger.warn("removeSource - localDescription not ready yet");
  6826. setTimeout(function() {
  6827. self.removeSource(elem);
  6828. },
  6829. 200
  6830. );
  6831. return;
  6832. }
  6833. logger.log('removessrc', new Date().getTime());
  6834. logger.log('ice', this.peerconnection.iceConnectionState);
  6835. var sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  6836. var mySdp = new SDP(this.peerconnection.localDescription.sdp);
  6837. $(elem).each(function (idx, content) {
  6838. var name = $(content).attr('name');
  6839. var lines = '';
  6840. $(content).find('ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]').each(function() {
  6841. var semantics = this.getAttribute('semantics');
  6842. var ssrcs = $(this).find('>source').map(function () {
  6843. return this.getAttribute('ssrc');
  6844. }).get();
  6845. if (ssrcs.length) {
  6846. lines += 'a=ssrc-group:' + semantics + ' ' + ssrcs.join(' ') + '\r\n';
  6847. }
  6848. });
  6849. var tmp = $(content).find('source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]'); // can handle both >source and >description>source
  6850. tmp.each(function () {
  6851. var ssrc = $(this).attr('ssrc');
  6852. // This should never happen, but can be useful for bug detection
  6853. if(mySdp.containsSSRC(ssrc)){
  6854. logger.error("Got remove stream request for my own ssrc: "+ssrc);
  6855. return;
  6856. }
  6857. $(this).find('>parameter').each(function () {
  6858. lines += 'a=ssrc:' + ssrc + ' ' + $(this).attr('name');
  6859. if ($(this).attr('value') && $(this).attr('value').length)
  6860. lines += ':' + $(this).attr('value');
  6861. lines += '\r\n';
  6862. });
  6863. });
  6864. sdp.media.forEach(function(media, idx) {
  6865. if (!SDPUtil.find_line(media, 'a=mid:' + name))
  6866. return;
  6867. sdp.media[idx] += lines;
  6868. if (!self.removessrc[idx]) self.removessrc[idx] = '';
  6869. self.removessrc[idx] += lines;
  6870. });
  6871. sdp.raw = sdp.session + sdp.media.join('');
  6872. });
  6873. this.modifySourcesQueue.push(function() {
  6874. // When a source is removed and if this is FF, the recvonly channel that
  6875. // receives the remote stream is deactivated . We need to diffuse the
  6876. // recvonly SSRC removal to the rest of the peers.
  6877. logger.log('modify sources done');
  6878. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  6879. logger.log("SDPs", mySdp, newSdp);
  6880. self.notifyMySSRCUpdate(mySdp, newSdp);
  6881. });
  6882. };
  6883. JingleSessionPC.prototype._modifySources = function (successCallback, queueCallback) {
  6884. var self = this;
  6885. if (this.peerconnection.signalingState == 'closed') return;
  6886. if (!(this.addssrc.length || this.removessrc.length || this.pendingop !== null
  6887. || this.switchstreams || this.addingStreams)){
  6888. // There is nothing to do since scheduled job might have been executed by another succeeding call
  6889. this.setLocalDescription();
  6890. if(successCallback){
  6891. successCallback();
  6892. }
  6893. queueCallback();
  6894. return;
  6895. }
  6896. // Reset switch streams flags
  6897. this.switchstreams = false;
  6898. this.addingStreams = false;
  6899. var sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  6900. // add sources
  6901. this.addssrc.forEach(function(lines, idx) {
  6902. sdp.media[idx] += lines;
  6903. });
  6904. this.addssrc = [];
  6905. // remove sources
  6906. this.removessrc.forEach(function(lines, idx) {
  6907. lines = lines.split('\r\n');
  6908. lines.pop(); // remove empty last element;
  6909. lines.forEach(function(line) {
  6910. sdp.media[idx] = sdp.media[idx].replace(line + '\r\n', '');
  6911. });
  6912. });
  6913. this.removessrc = [];
  6914. sdp.raw = sdp.session + sdp.media.join('');
  6915. this.peerconnection.setRemoteDescription(new RTCSessionDescription({type: 'offer', sdp: sdp.raw}),
  6916. function() {
  6917. if(self.signalingState == 'closed') {
  6918. logger.error("createAnswer attempt on closed state");
  6919. queueCallback("createAnswer attempt on closed state");
  6920. return;
  6921. }
  6922. self.peerconnection.createAnswer(
  6923. function(modifiedAnswer) {
  6924. // change video direction, see https://github.com/jitsi/jitmeet/issues/41
  6925. if (self.pendingop !== null) {
  6926. var sdp = new SDP(modifiedAnswer.sdp);
  6927. if (sdp.media.length > 1) {
  6928. switch(self.pendingop) {
  6929. case 'mute':
  6930. sdp.media[1] = sdp.media[1].replace('a=sendrecv', 'a=recvonly');
  6931. break;
  6932. case 'unmute':
  6933. sdp.media[1] = sdp.media[1].replace('a=recvonly', 'a=sendrecv');
  6934. break;
  6935. }
  6936. sdp.raw = sdp.session + sdp.media.join('');
  6937. modifiedAnswer.sdp = sdp.raw;
  6938. }
  6939. self.pendingop = null;
  6940. }
  6941. // FIXME: pushing down an answer while ice connection state
  6942. // is still checking is bad...
  6943. //logger.log(self.peerconnection.iceConnectionState);
  6944. // trying to work around another chrome bug
  6945. //modifiedAnswer.sdp = modifiedAnswer.sdp.replace(/a=setup:active/g, 'a=setup:actpass');
  6946. self.peerconnection.setLocalDescription(modifiedAnswer,
  6947. function() {
  6948. //logger.log('modified setLocalDescription ok');
  6949. self.setLocalDescription();
  6950. if(successCallback){
  6951. successCallback();
  6952. }
  6953. queueCallback();
  6954. },
  6955. function(error) {
  6956. logger.error('modified setLocalDescription failed', error);
  6957. queueCallback(error);
  6958. }
  6959. );
  6960. },
  6961. function(error) {
  6962. logger.error('modified answer failed', error);
  6963. queueCallback(error);
  6964. }
  6965. );
  6966. },
  6967. function(error) {
  6968. logger.error('modify failed', error);
  6969. queueCallback(error);
  6970. }
  6971. );
  6972. };
  6973. /**
  6974. * Switches video streams.
  6975. * @param newStream new stream that will be used as video of this session.
  6976. * @param oldStream old video stream of this session.
  6977. * @param successCallback callback executed after successful stream switch.
  6978. * @param isAudio whether the streams are audio (if true) or video (if false).
  6979. */
  6980. JingleSessionPC.prototype.switchStreams =
  6981. function (newStream, oldStream, successCallback, isAudio) {
  6982. var self = this;
  6983. var sender, newTrack;
  6984. var senderKind = isAudio ? 'audio' : 'video';
  6985. // Remember SDP to figure out added/removed SSRCs
  6986. var oldSdp = null;
  6987. if (self.peerconnection) {
  6988. if (self.peerconnection.localDescription) {
  6989. oldSdp = new SDP(self.peerconnection.localDescription.sdp);
  6990. }
  6991. if (RTCBrowserType.getBrowserType() ===
  6992. RTCBrowserType.RTC_BROWSER_FIREFOX) {
  6993. // On Firefox we don't replace MediaStreams as this messes up the
  6994. // m-lines (which can't be removed in Plan Unified) and brings a lot
  6995. // of complications. Instead, we use the RTPSender and replace just
  6996. // the track.
  6997. // Find the right sender (for audio or video)
  6998. self.peerconnection.peerconnection.getSenders().some(function (s) {
  6999. if (s.track && s.track.kind === senderKind) {
  7000. sender = s;
  7001. return true;
  7002. }
  7003. });
  7004. if (sender) {
  7005. // We assume that our streams have a single track, either audio
  7006. // or video.
  7007. newTrack = isAudio ? newStream.getAudioTracks()[0] :
  7008. newStream.getVideoTracks()[0];
  7009. sender.replaceTrack(newTrack)
  7010. .then(function() {
  7011. console.log("Replaced a track, isAudio=" + isAudio);
  7012. })
  7013. .catch(function(err) {
  7014. console.log("Failed to replace a track: " + err);
  7015. });
  7016. } else {
  7017. console.log("Cannot switch tracks: no RTPSender.");
  7018. }
  7019. } else {
  7020. self.peerconnection.removeStream(oldStream, true);
  7021. if (newStream) {
  7022. self.peerconnection.addStream(newStream);
  7023. }
  7024. }
  7025. }
  7026. // Conference is not active
  7027. if (!oldSdp) {
  7028. successCallback();
  7029. return;
  7030. }
  7031. self.switchstreams = true;
  7032. self.modifySourcesQueue.push(function() {
  7033. logger.log('modify sources done');
  7034. successCallback();
  7035. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  7036. logger.log("SDPs", oldSdp, newSdp);
  7037. self.notifyMySSRCUpdate(oldSdp, newSdp);
  7038. });
  7039. };
  7040. /**
  7041. * Adds streams.
  7042. * @param stream new stream that will be added.
  7043. * @param success_callback callback executed after successful stream addition.
  7044. */
  7045. JingleSessionPC.prototype.addStream = function (stream, callback) {
  7046. var self = this;
  7047. // Remember SDP to figure out added/removed SSRCs
  7048. var oldSdp = null;
  7049. if(this.peerconnection) {
  7050. if(this.peerconnection.localDescription) {
  7051. oldSdp = new SDP(this.peerconnection.localDescription.sdp);
  7052. }
  7053. if(stream)
  7054. this.peerconnection.addStream(stream);
  7055. }
  7056. // Conference is not active
  7057. if(!oldSdp || !this.peerconnection) {
  7058. callback();
  7059. return;
  7060. }
  7061. this.addingStreams = true;
  7062. this.modifySourcesQueue.push(function() {
  7063. logger.log('modify sources done');
  7064. callback();
  7065. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  7066. logger.log("SDPs", oldSdp, newSdp);
  7067. self.notifyMySSRCUpdate(oldSdp, newSdp);
  7068. });
  7069. }
  7070. /**
  7071. * Remove streams.
  7072. * @param stream stream that will be removed.
  7073. * @param success_callback callback executed after successful stream addition.
  7074. */
  7075. JingleSessionPC.prototype.removeStream = function (stream, callback) {
  7076. var self = this;
  7077. // Remember SDP to figure out added/removed SSRCs
  7078. var oldSdp = null;
  7079. if(this.peerconnection) {
  7080. if(this.peerconnection.localDescription) {
  7081. oldSdp = new SDP(this.peerconnection.localDescription.sdp);
  7082. }
  7083. if(stream)
  7084. this.peerconnection.removeStream(stream);
  7085. }
  7086. // Conference is not active
  7087. if(!oldSdp || !this.peerconnection) {
  7088. callback();
  7089. return;
  7090. }
  7091. this.addingStreams = true;
  7092. this.modifySourcesQueue.push(function() {
  7093. logger.log('modify sources done');
  7094. callback();
  7095. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  7096. logger.log("SDPs", oldSdp, newSdp);
  7097. self.notifyMySSRCUpdate(oldSdp, newSdp);
  7098. });
  7099. }
  7100. /**
  7101. * Figures out added/removed ssrcs and send update IQs.
  7102. * @param old_sdp SDP object for old description.
  7103. * @param new_sdp SDP object for new description.
  7104. */
  7105. JingleSessionPC.prototype.notifyMySSRCUpdate = function (old_sdp, new_sdp) {
  7106. if (!(this.peerconnection.signalingState == 'stable' &&
  7107. this.peerconnection.iceConnectionState == 'connected')){
  7108. logger.log("Too early to send updates");
  7109. return;
  7110. }
  7111. // send source-remove IQ.
  7112. sdpDiffer = new SDPDiffer(new_sdp, old_sdp);
  7113. var remove = $iq({to: this.peerjid, type: 'set'})
  7114. .c('jingle', {
  7115. xmlns: 'urn:xmpp:jingle:1',
  7116. action: 'source-remove',
  7117. initiator: this.initiator,
  7118. sid: this.sid
  7119. }
  7120. );
  7121. var removed = sdpDiffer.toJingle(remove);
  7122. // Let 'source-remove' IQ through the hack and see if we're allowed to send
  7123. // it in the current form
  7124. if (removed)
  7125. remove = SSRCReplacement.processSourceRemove(remove);
  7126. if (removed && remove) {
  7127. logger.info("Sending source-remove", remove);
  7128. this.connection.sendIQ(remove,
  7129. function (res) {
  7130. logger.info('got remove result', res);
  7131. },
  7132. function (err) {
  7133. logger.error('got remove error', err);
  7134. }
  7135. );
  7136. } else {
  7137. logger.log('removal not necessary');
  7138. }
  7139. // send source-add IQ.
  7140. var sdpDiffer = new SDPDiffer(old_sdp, new_sdp);
  7141. var add = $iq({to: this.peerjid, type: 'set'})
  7142. .c('jingle', {
  7143. xmlns: 'urn:xmpp:jingle:1',
  7144. action: 'source-add',
  7145. initiator: this.initiator,
  7146. sid: this.sid
  7147. }
  7148. );
  7149. var added = sdpDiffer.toJingle(add);
  7150. // Let 'source-add' IQ through the hack and see if we're allowed to send
  7151. // it in the current form
  7152. if (added)
  7153. add = SSRCReplacement.processSourceAdd(add);
  7154. if (added && add) {
  7155. logger.info("Sending source-add", add);
  7156. this.connection.sendIQ(add,
  7157. function (res) {
  7158. logger.info('got add result', res);
  7159. },
  7160. function (err) {
  7161. logger.error('got add error', err);
  7162. }
  7163. );
  7164. } else {
  7165. logger.log('addition not necessary');
  7166. }
  7167. };
  7168. /**
  7169. * Mutes/unmutes the (local) video i.e. enables/disables all video tracks.
  7170. *
  7171. * @param mute <tt>true</tt> to mute the (local) video i.e. to disable all video
  7172. * tracks; otherwise, <tt>false</tt>
  7173. * @param callback a function to be invoked with <tt>mute</tt> after all video
  7174. * tracks have been enabled/disabled. The function may, optionally, return
  7175. * another function which is to be invoked after the whole mute/unmute operation
  7176. * has completed successfully.
  7177. * @param options an object which specifies optional arguments such as the
  7178. * <tt>boolean</tt> key <tt>byUser</tt> with default value <tt>true</tt> which
  7179. * specifies whether the method was initiated in response to a user command (in
  7180. * contrast to an automatic decision made by the application logic)
  7181. */
  7182. JingleSessionPC.prototype.setVideoMute = function (mute, callback, options) {
  7183. var byUser;
  7184. if (options) {
  7185. byUser = options.byUser;
  7186. if (typeof byUser === 'undefined') {
  7187. byUser = true;
  7188. }
  7189. } else {
  7190. byUser = true;
  7191. }
  7192. // The user's command to mute the (local) video takes precedence over any
  7193. // automatic decision made by the application logic.
  7194. if (byUser) {
  7195. this.videoMuteByUser = mute;
  7196. } else if (this.videoMuteByUser) {
  7197. return;
  7198. }
  7199. this.hardMuteVideo(mute);
  7200. var self = this;
  7201. var oldSdp = null;
  7202. if(self.peerconnection) {
  7203. if(self.peerconnection.localDescription) {
  7204. oldSdp = new SDP(self.peerconnection.localDescription.sdp);
  7205. }
  7206. }
  7207. this.modifySourcesQueue.push(function() {
  7208. logger.log('modify sources done');
  7209. callback(mute);
  7210. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  7211. logger.log("SDPs", oldSdp, newSdp);
  7212. self.notifyMySSRCUpdate(oldSdp, newSdp);
  7213. });
  7214. };
  7215. JingleSessionPC.prototype.hardMuteVideo = function (muted) {
  7216. this.pendingop = muted ? 'mute' : 'unmute';
  7217. };
  7218. JingleSessionPC.prototype.sendMute = function (muted, content) {
  7219. var info = $iq({to: this.peerjid,
  7220. type: 'set'})
  7221. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  7222. action: 'session-info',
  7223. initiator: this.initiator,
  7224. sid: this.sid });
  7225. info.c(muted ? 'mute' : 'unmute', {xmlns: 'urn:xmpp:jingle:apps:rtp:info:1'});
  7226. info.attrs({'creator': this.me == this.initiator ? 'creator' : 'responder'});
  7227. if (content) {
  7228. info.attrs({'name': content});
  7229. }
  7230. this.connection.send(info);
  7231. };
  7232. JingleSessionPC.prototype.sendRinging = function () {
  7233. var info = $iq({to: this.peerjid,
  7234. type: 'set'})
  7235. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  7236. action: 'session-info',
  7237. initiator: this.initiator,
  7238. sid: this.sid });
  7239. info.c('ringing', {xmlns: 'urn:xmpp:jingle:apps:rtp:info:1'});
  7240. this.connection.send(info);
  7241. };
  7242. JingleSessionPC.prototype.getStats = function (interval) {
  7243. var self = this;
  7244. var recv = {audio: 0, video: 0};
  7245. var lost = {audio: 0, video: 0};
  7246. var lastrecv = {audio: 0, video: 0};
  7247. var lastlost = {audio: 0, video: 0};
  7248. var loss = {audio: 0, video: 0};
  7249. var delta = {audio: 0, video: 0};
  7250. this.statsinterval = window.setInterval(function () {
  7251. if (self && self.peerconnection && self.peerconnection.getStats) {
  7252. self.peerconnection.getStats(function (stats) {
  7253. var results = stats.result();
  7254. // TODO: there are so much statistics you can get from this..
  7255. for (var i = 0; i < results.length; ++i) {
  7256. if (results[i].type == 'ssrc') {
  7257. var packetsrecv = results[i].stat('packetsReceived');
  7258. var packetslost = results[i].stat('packetsLost');
  7259. if (packetsrecv && packetslost) {
  7260. packetsrecv = parseInt(packetsrecv, 10);
  7261. packetslost = parseInt(packetslost, 10);
  7262. if (results[i].stat('googFrameRateReceived')) {
  7263. lastlost.video = lost.video;
  7264. lastrecv.video = recv.video;
  7265. recv.video = packetsrecv;
  7266. lost.video = packetslost;
  7267. } else {
  7268. lastlost.audio = lost.audio;
  7269. lastrecv.audio = recv.audio;
  7270. recv.audio = packetsrecv;
  7271. lost.audio = packetslost;
  7272. }
  7273. }
  7274. }
  7275. }
  7276. delta.audio = recv.audio - lastrecv.audio;
  7277. delta.video = recv.video - lastrecv.video;
  7278. loss.audio = (delta.audio > 0) ? Math.ceil(100 * (lost.audio - lastlost.audio) / delta.audio) : 0;
  7279. loss.video = (delta.video > 0) ? Math.ceil(100 * (lost.video - lastlost.video) / delta.video) : 0;
  7280. $(document).trigger('packetloss.jingle', [self.sid, loss]);
  7281. });
  7282. }
  7283. }, interval || 3000);
  7284. return this.statsinterval;
  7285. };
  7286. JingleSessionPC.onJingleError = function (session, error)
  7287. {
  7288. logger.error("Jingle error", error);
  7289. }
  7290. JingleSessionPC.onJingleFatalError = function (session, error)
  7291. {
  7292. this.room.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  7293. this.room.eventEmitter.emit(XMPPEvents.JINGLE_FATAL_ERROR, session, error);
  7294. }
  7295. JingleSessionPC.prototype.setLocalDescription = function () {
  7296. var self = this;
  7297. var newssrcs = [];
  7298. if(!this.peerconnection.localDescription)
  7299. return;
  7300. var session = transform.parse(this.peerconnection.localDescription.sdp);
  7301. var i;
  7302. session.media.forEach(function (media) {
  7303. if (media.ssrcs && media.ssrcs.length > 0) {
  7304. // TODO(gp) maybe exclude FID streams?
  7305. media.ssrcs.forEach(function (ssrc) {
  7306. if (ssrc.attribute !== 'cname') {
  7307. return;
  7308. }
  7309. newssrcs.push({
  7310. 'ssrc': ssrc.id,
  7311. 'type': media.type
  7312. });
  7313. // FIXME allows for only one SSRC per media type
  7314. self.localStreamsSSRC[media.type] = ssrc.id;
  7315. });
  7316. }
  7317. });
  7318. logger.log('new ssrcs', newssrcs);
  7319. // Bind us as local SSRCs owner
  7320. if (newssrcs.length > 0) {
  7321. for (i = 0; i < newssrcs.length; i++) {
  7322. var ssrc = newssrcs[i].ssrc;
  7323. var myJid = self.connection.emuc.myroomjid;
  7324. self.ssrcOwners[ssrc] = myJid;
  7325. }
  7326. }
  7327. }
  7328. // an attempt to work around https://github.com/jitsi/jitmeet/issues/32
  7329. JingleSessionPC.prototype.sendKeyframe = function () {
  7330. var pc = this.peerconnection;
  7331. logger.log('sendkeyframe', pc.iceConnectionState);
  7332. if (pc.iceConnectionState !== 'connected') return; // safe...
  7333. var self = this;
  7334. pc.setRemoteDescription(
  7335. pc.remoteDescription,
  7336. function () {
  7337. pc.createAnswer(
  7338. function (modifiedAnswer) {
  7339. pc.setLocalDescription(
  7340. modifiedAnswer,
  7341. function () {
  7342. // noop
  7343. },
  7344. function (error) {
  7345. logger.log('triggerKeyframe setLocalDescription failed', error);
  7346. self.room.eventEmitter.emit(XMPPEvents.SET_LOCAL_DESCRIPTION_ERROR);
  7347. }
  7348. );
  7349. },
  7350. function (error) {
  7351. logger.log('triggerKeyframe createAnswer failed', error);
  7352. self.room.eventEmitter.emit(XMPPEvents.CREATE_ANSWER_ERROR);
  7353. }
  7354. );
  7355. },
  7356. function (error) {
  7357. logger.log('triggerKeyframe setRemoteDescription failed', error);
  7358. eventEmitter.emit(XMPPEvents.SET_REMOTE_DESCRIPTION_ERROR);
  7359. }
  7360. );
  7361. }
  7362. JingleSessionPC.prototype.remoteStreamAdded = function (data, times) {
  7363. var self = this;
  7364. var thessrc;
  7365. var streamId = RTC.getStreamID(data.stream);
  7366. // look up an associated JID for a stream id
  7367. if (!streamId) {
  7368. logger.error("No stream ID for", data.stream);
  7369. } else if (streamId && streamId.indexOf('mixedmslabel') === -1) {
  7370. // look only at a=ssrc: and _not_ at a=ssrc-group: lines
  7371. var ssrclines = this.peerconnection.remoteDescription?
  7372. SDPUtil.find_lines(this.peerconnection.remoteDescription.sdp, 'a=ssrc:') : [];
  7373. ssrclines = ssrclines.filter(function (line) {
  7374. // NOTE(gp) previously we filtered on the mslabel, but that property
  7375. // is not always present.
  7376. // return line.indexOf('mslabel:' + data.stream.label) !== -1;
  7377. if (RTCBrowserType.isTemasysPluginUsed()) {
  7378. return ((line.indexOf('mslabel:' + streamId) !== -1));
  7379. } else {
  7380. return ((line.indexOf('msid:' + streamId) !== -1));
  7381. }
  7382. });
  7383. if (ssrclines.length) {
  7384. thessrc = ssrclines[0].substring(7).split(' ')[0];
  7385. if (!self.ssrcOwners[thessrc]) {
  7386. logger.error("No SSRC owner known for: " + thessrc);
  7387. return;
  7388. }
  7389. data.peerjid = self.ssrcOwners[thessrc];
  7390. logger.log('associated jid', self.ssrcOwners[thessrc]);
  7391. } else {
  7392. logger.error("No SSRC lines for ", streamId);
  7393. }
  7394. }
  7395. this.room.remoteStreamAdded(data, this.sid, thessrc);
  7396. var isVideo = data.stream.getVideoTracks().length > 0;
  7397. // an attempt to work around https://github.com/jitsi/jitmeet/issues/32
  7398. if (isVideo &&
  7399. data.peerjid && this.peerjid === data.peerjid &&
  7400. data.stream.getVideoTracks().length === 0 &&
  7401. RTC.localVideo.getTracks().length > 0) {
  7402. window.setTimeout(function () {
  7403. self.sendKeyframe();
  7404. }, 3000);
  7405. }
  7406. }
  7407. /**
  7408. * Returns the ice connection state for the peer connection.
  7409. * @returns the ice connection state for the peer connection.
  7410. */
  7411. JingleSessionPC.prototype.getIceConnectionState = function () {
  7412. return this.peerconnection.iceConnectionState;
  7413. }
  7414. module.exports = JingleSessionPC;
  7415. }).call(this,"/modules/xmpp/JingleSessionPC.js")
  7416. },{"../../service/xmpp/XMPPEvents":91,"../RTC/RTC":16,"../RTC/RTCBrowserType":17,"./JingleSession":27,"./LocalSSRCReplacement":29,"./SDP":30,"./SDPDiffer":31,"./SDPUtil":32,"./TraceablePeerConnection":33,"async":43,"jitsi-meet-logger":48,"sdp-transform":80}],29:[function(require,module,exports){
  7417. (function (__filename){
  7418. /* global $ */
  7419. var logger = require("jitsi-meet-logger").getLogger(__filename);
  7420. /*
  7421. Here we do modifications of local video SSRCs. There are 2 situations we have
  7422. to handle:
  7423. 1. We generate SSRC for local recvonly video stream. This is the case when we
  7424. have no local camera and it is not generated automatically, but SSRC=1 is
  7425. used implicitly. If that happens RTCP packets will be dropped by the JVB
  7426. and we won't be able to request video key frames correctly.
  7427. 2. A hack to re-use SSRC of the first video stream for any new stream created
  7428. in future. It turned out that Chrome may keep on using the SSRC of removed
  7429. video stream in RTCP even though a new one has been created. So we just
  7430. want to avoid that by re-using it. Jingle 'source-remove'/'source-add'
  7431. notifications are blocked once first video SSRC is advertised to the focus.
  7432. What this hack does:
  7433. 1. Stores the SSRC of the first video stream created by
  7434. a) scanning Jingle session-accept/session-invite for existing video SSRC
  7435. b) watching for 'source-add' for new video stream if it has not been
  7436. created in step a)
  7437. 2. Exposes method 'mungeLocalVideoSSRC' which replaces any new video SSRC with
  7438. the stored one. It is called by 'TracablePeerConnection' before local SDP is
  7439. returned to the other parts of the application.
  7440. 3. Scans 'source-remove'/'source-add' notifications for stored video SSRC and
  7441. blocks those notifications. This makes Jicofo and all participants think
  7442. that it exists all the time even if the video stream has been removed or
  7443. replaced locally. Thanks to that there is no additional signaling activity
  7444. on video mute or when switching to the desktop stream.
  7445. */
  7446. var SDP = require('./SDP');
  7447. var RandomUtil = require('../util/RandomUtil');
  7448. var RTCBrowserType = require('../RTC/RTCBrowserType');
  7449. /**
  7450. * The hack is enabled on all browsers except FF by default
  7451. * FIXME finish the hack once removeStream method is implemented in FF
  7452. * @type {boolean}
  7453. */
  7454. var isEnabled = !RTCBrowserType.isFirefox();
  7455. /**
  7456. * Stored SSRC of local video stream.
  7457. */
  7458. var localVideoSSRC;
  7459. /**
  7460. * SSRC, msid, mslabel, label used for recvonly video stream when we have no local camera.
  7461. * This is in order to tell Chrome what SSRC should be used in RTCP requests
  7462. * instead of 1.
  7463. */
  7464. var localRecvOnlySSRC, localRecvOnlyMSID, localRecvOnlyMSLabel, localRecvOnlyLabel;
  7465. /**
  7466. * cname for <tt>localRecvOnlySSRC</tt>
  7467. */
  7468. var localRecvOnlyCName;
  7469. /**
  7470. * Method removes <source> element which describes <tt>localVideoSSRC</tt>
  7471. * from given Jingle IQ.
  7472. * @param modifyIq 'source-add' or 'source-remove' Jingle IQ.
  7473. * @param actionName display name of the action which will be printed in log
  7474. * messages.
  7475. * @returns {*} modified Jingle IQ, so that it does not contain <source> element
  7476. * corresponding to <tt>localVideoSSRC</tt> or <tt>null</tt> if no
  7477. * other SSRCs left to be signaled after removing it.
  7478. */
  7479. var filterOutSource = function (modifyIq, actionName) {
  7480. var modifyIqTree = $(modifyIq.tree());
  7481. if (!localVideoSSRC)
  7482. return modifyIqTree[0];
  7483. var videoSSRC = modifyIqTree.find(
  7484. '>jingle>content[name="video"]' +
  7485. '>description>source[ssrc="' + localVideoSSRC + '"]');
  7486. if (!videoSSRC.length) {
  7487. return modifyIqTree[0];
  7488. }
  7489. logger.info(
  7490. 'Blocking ' + actionName + ' for local video SSRC: ' + localVideoSSRC);
  7491. videoSSRC.remove();
  7492. // Check if any sources still left to be added/removed
  7493. if (modifyIqTree.find('>jingle>content>description>source').length) {
  7494. return modifyIqTree[0];
  7495. } else {
  7496. return null;
  7497. }
  7498. };
  7499. /**
  7500. * Scans given Jingle IQ for video SSRC and stores it.
  7501. * @param jingleIq the Jingle IQ to be scanned for video SSRC.
  7502. */
  7503. var storeLocalVideoSSRC = function (jingleIq) {
  7504. var videoSSRCs =
  7505. $(jingleIq.tree())
  7506. .find('>jingle>content[name="video"]>description>source');
  7507. videoSSRCs.each(function (idx, ssrcElem) {
  7508. if (localVideoSSRC)
  7509. return;
  7510. // We consider SSRC real only if it has msid attribute
  7511. // recvonly streams in FF do not have it as well as local SSRCs
  7512. // we generate for recvonly streams in Chrome
  7513. var ssrSel = $(ssrcElem);
  7514. var msid = ssrSel.find('>parameter[name="msid"]');
  7515. if (msid.length) {
  7516. var ssrcVal = ssrSel.attr('ssrc');
  7517. if (ssrcVal) {
  7518. localVideoSSRC = ssrcVal;
  7519. logger.info('Stored local video SSRC' +
  7520. ' for future re-use: ' + localVideoSSRC);
  7521. }
  7522. }
  7523. });
  7524. };
  7525. /**
  7526. * Generates new label/mslabel attribute
  7527. * @returns {string} label/mslabel attribute
  7528. */
  7529. function generateLabel() {
  7530. return RandomUtil.randomHexString(8) + "-" + RandomUtil.randomHexString(4) +
  7531. "-" + RandomUtil.randomHexString(4) + "-" +
  7532. RandomUtil.randomHexString(4) + "-" + RandomUtil.randomHexString(12);
  7533. }
  7534. /**
  7535. * Generates new SSRC, CNAME, mslabel, label and msid for local video recvonly stream.
  7536. * FIXME what about eventual SSRC collision ?
  7537. */
  7538. function generateRecvonlySSRC() {
  7539. localRecvOnlySSRC =
  7540. Math.random().toString(10).substring(2, 11);
  7541. localRecvOnlyCName =
  7542. Math.random().toString(36).substring(2);
  7543. localRecvOnlyMSLabel = generateLabel();
  7544. localRecvOnlyLabel = generateLabel();
  7545. localRecvOnlyMSID = localRecvOnlyMSLabel + " " + localRecvOnlyLabel;
  7546. logger.info(
  7547. "Generated local recvonly SSRC: " + localRecvOnlySSRC +
  7548. ", cname: " + localRecvOnlyCName);
  7549. }
  7550. var LocalSSRCReplacement = {
  7551. /**
  7552. * Method must be called before 'session-initiate' or 'session-invite' is
  7553. * sent. Scans the IQ for local video SSRC and stores it if detected.
  7554. *
  7555. * @param sessionInit our 'session-initiate' or 'session-accept' Jingle IQ
  7556. * which will be scanned for local video SSRC.
  7557. */
  7558. processSessionInit: function (sessionInit) {
  7559. if (!isEnabled)
  7560. return;
  7561. if (localVideoSSRC) {
  7562. logger.error("Local SSRC stored already: " + localVideoSSRC);
  7563. return;
  7564. }
  7565. storeLocalVideoSSRC(sessionInit);
  7566. },
  7567. /**
  7568. * If we have local video SSRC stored searched given
  7569. * <tt>localDescription</tt> for video SSRC and makes sure it is replaced
  7570. * with the stored one.
  7571. * @param localDescription local description object that will have local
  7572. * video SSRC replaced with the stored one
  7573. * @returns modified <tt>localDescription</tt> object.
  7574. */
  7575. mungeLocalVideoSSRC: function (localDescription) {
  7576. if (!isEnabled)
  7577. return localDescription;
  7578. if (!localDescription) {
  7579. logger.warn("localDescription is null or undefined");
  7580. return localDescription;
  7581. }
  7582. // IF we have local video SSRC stored make sure it is replaced
  7583. // with old SSRC
  7584. if (localVideoSSRC) {
  7585. var newSdp = new SDP(localDescription.sdp);
  7586. if (newSdp.media[1].indexOf("a=ssrc:") !== -1 &&
  7587. !newSdp.containsSSRC(localVideoSSRC)) {
  7588. // Get new video SSRC
  7589. var map = newSdp.getMediaSsrcMap();
  7590. var videoPart = map[1];
  7591. var videoSSRCs = videoPart.ssrcs;
  7592. var newSSRC = Object.keys(videoSSRCs)[0];
  7593. logger.info(
  7594. "Replacing new video SSRC: " + newSSRC +
  7595. " with " + localVideoSSRC);
  7596. localDescription.sdp =
  7597. newSdp.raw.replace(
  7598. new RegExp('a=ssrc:' + newSSRC, 'g'),
  7599. 'a=ssrc:' + localVideoSSRC);
  7600. }
  7601. } else {
  7602. // Make sure we have any SSRC for recvonly video stream
  7603. var sdp = new SDP(localDescription.sdp);
  7604. if (sdp.media[1] && sdp.media[1].indexOf('a=ssrc:') === -1 &&
  7605. sdp.media[1].indexOf('a=recvonly') !== -1) {
  7606. if (!localRecvOnlySSRC) {
  7607. generateRecvonlySSRC();
  7608. }
  7609. localVideoSSRC = localRecvOnlySSRC;
  7610. logger.info('No SSRC in video recvonly stream' +
  7611. ' - adding SSRC: ' + localRecvOnlySSRC);
  7612. sdp.media[1] += 'a=ssrc:' + localRecvOnlySSRC +
  7613. ' cname:' + localRecvOnlyCName + '\r\n' +
  7614. 'a=ssrc:' + localRecvOnlySSRC +
  7615. ' msid:' + localRecvOnlyMSID + '\r\n' +
  7616. 'a=ssrc:' + localRecvOnlySSRC +
  7617. ' mslabel:' + localRecvOnlyMSLabel + '\r\n' +
  7618. 'a=ssrc:' + localRecvOnlySSRC +
  7619. ' label:' + localRecvOnlyLabel + '\r\n';
  7620. localDescription.sdp = sdp.session + sdp.media.join('');
  7621. }
  7622. }
  7623. return localDescription;
  7624. },
  7625. /**
  7626. * Method must be called before 'source-add' notification is sent. In case
  7627. * we have local video SSRC advertised already it will be removed from the
  7628. * notification. If no other SSRCs are described by given IQ null will be
  7629. * returned which means that there is no point in sending the notification.
  7630. * @param sourceAdd 'source-add' Jingle IQ to be processed
  7631. * @returns modified 'source-add' IQ which can be sent to the focus or
  7632. * <tt>null</tt> if no notification shall be sent. It is no longer
  7633. * a Strophe IQ Builder instance, but DOM element tree.
  7634. */
  7635. processSourceAdd: function (sourceAdd) {
  7636. if (!isEnabled)
  7637. return sourceAdd;
  7638. if (!localVideoSSRC) {
  7639. // Store local SSRC if available
  7640. storeLocalVideoSSRC(sourceAdd);
  7641. return sourceAdd;
  7642. } else {
  7643. return filterOutSource(sourceAdd, 'source-add');
  7644. }
  7645. },
  7646. /**
  7647. * Method must be called before 'source-remove' notification is sent.
  7648. * Removes local video SSRC from the notification. If there are no other
  7649. * SSRCs described in the given IQ <tt>null</tt> will be returned which
  7650. * means that there is no point in sending the notification.
  7651. * @param sourceRemove 'source-remove' Jingle IQ to be processed
  7652. * @returns modified 'source-remove' IQ which can be sent to the focus or
  7653. * <tt>null</tt> if no notification shall be sent. It is no longer
  7654. * a Strophe IQ Builder instance, but DOM element tree.
  7655. */
  7656. processSourceRemove: function (sourceRemove) {
  7657. if (!isEnabled)
  7658. return sourceRemove;
  7659. return filterOutSource(sourceRemove, 'source-remove');
  7660. },
  7661. /**
  7662. * Turns the hack on or off
  7663. * @param enabled <tt>true</tt> to enable the hack or <tt>false</tt>
  7664. * to disable it
  7665. */
  7666. setEnabled: function (enabled) {
  7667. isEnabled = enabled;
  7668. }
  7669. };
  7670. module.exports = LocalSSRCReplacement;
  7671. }).call(this,"/modules/xmpp/LocalSSRCReplacement.js")
  7672. },{"../RTC/RTCBrowserType":17,"../util/RandomUtil":25,"./SDP":30,"jitsi-meet-logger":48}],30:[function(require,module,exports){
  7673. (function (__filename){
  7674. /* jshint -W117 */
  7675. var logger = require("jitsi-meet-logger").getLogger(__filename);
  7676. var SDPUtil = require("./SDPUtil");
  7677. // SDP STUFF
  7678. function SDP(sdp) {
  7679. /**
  7680. * Whether or not to remove TCP ice candidates when translating from/to jingle.
  7681. * @type {boolean}
  7682. */
  7683. this.removeTcpCandidates = false;
  7684. /**
  7685. * Whether or not to remove UDP ice candidates when translating from/to jingle.
  7686. * @type {boolean}
  7687. */
  7688. this.removeUdpCandidates = false;
  7689. this.media = sdp.split('\r\nm=');
  7690. for (var i = 1; i < this.media.length; i++) {
  7691. this.media[i] = 'm=' + this.media[i];
  7692. if (i != this.media.length - 1) {
  7693. this.media[i] += '\r\n';
  7694. }
  7695. }
  7696. this.session = this.media.shift() + '\r\n';
  7697. this.raw = this.session + this.media.join('');
  7698. }
  7699. /**
  7700. * Returns map of MediaChannel mapped per channel idx.
  7701. */
  7702. SDP.prototype.getMediaSsrcMap = function() {
  7703. var self = this;
  7704. var media_ssrcs = {};
  7705. var tmp;
  7706. for (var mediaindex = 0; mediaindex < self.media.length; mediaindex++) {
  7707. tmp = SDPUtil.find_lines(self.media[mediaindex], 'a=ssrc:');
  7708. var mid = SDPUtil.parse_mid(SDPUtil.find_line(self.media[mediaindex], 'a=mid:'));
  7709. var media = {
  7710. mediaindex: mediaindex,
  7711. mid: mid,
  7712. ssrcs: {},
  7713. ssrcGroups: []
  7714. };
  7715. media_ssrcs[mediaindex] = media;
  7716. tmp.forEach(function (line) {
  7717. var linessrc = line.substring(7).split(' ')[0];
  7718. // allocate new ChannelSsrc
  7719. if(!media.ssrcs[linessrc]) {
  7720. media.ssrcs[linessrc] = {
  7721. ssrc: linessrc,
  7722. lines: []
  7723. };
  7724. }
  7725. media.ssrcs[linessrc].lines.push(line);
  7726. });
  7727. tmp = SDPUtil.find_lines(self.media[mediaindex], 'a=ssrc-group:');
  7728. tmp.forEach(function(line){
  7729. var idx = line.indexOf(' ');
  7730. var semantics = line.substr(0, idx).substr(13);
  7731. var ssrcs = line.substr(14 + semantics.length).split(' ');
  7732. if (ssrcs.length) {
  7733. media.ssrcGroups.push({
  7734. semantics: semantics,
  7735. ssrcs: ssrcs
  7736. });
  7737. }
  7738. });
  7739. }
  7740. return media_ssrcs;
  7741. };
  7742. /**
  7743. * Returns <tt>true</tt> if this SDP contains given SSRC.
  7744. * @param ssrc the ssrc to check.
  7745. * @returns {boolean} <tt>true</tt> if this SDP contains given SSRC.
  7746. */
  7747. SDP.prototype.containsSSRC = function(ssrc) {
  7748. var medias = this.getMediaSsrcMap();
  7749. Object.keys(medias).forEach(function(mediaindex){
  7750. var media = medias[mediaindex];
  7751. //logger.log("Check", channel, ssrc);
  7752. if(Object.keys(media.ssrcs).indexOf(ssrc) != -1){
  7753. return true;
  7754. }
  7755. });
  7756. return false;
  7757. };
  7758. // remove iSAC and CN from SDP
  7759. SDP.prototype.mangle = function () {
  7760. var i, j, mline, lines, rtpmap, newdesc;
  7761. for (i = 0; i < this.media.length; i++) {
  7762. lines = this.media[i].split('\r\n');
  7763. lines.pop(); // remove empty last element
  7764. mline = SDPUtil.parse_mline(lines.shift());
  7765. if (mline.media != 'audio')
  7766. continue;
  7767. newdesc = '';
  7768. mline.fmt.length = 0;
  7769. for (j = 0; j < lines.length; j++) {
  7770. if (lines[j].substr(0, 9) == 'a=rtpmap:') {
  7771. rtpmap = SDPUtil.parse_rtpmap(lines[j]);
  7772. if (rtpmap.name == 'CN' || rtpmap.name == 'ISAC')
  7773. continue;
  7774. mline.fmt.push(rtpmap.id);
  7775. newdesc += lines[j] + '\r\n';
  7776. } else {
  7777. newdesc += lines[j] + '\r\n';
  7778. }
  7779. }
  7780. this.media[i] = SDPUtil.build_mline(mline) + '\r\n';
  7781. this.media[i] += newdesc;
  7782. }
  7783. this.raw = this.session + this.media.join('');
  7784. };
  7785. // remove lines matching prefix from session section
  7786. SDP.prototype.removeSessionLines = function(prefix) {
  7787. var self = this;
  7788. var lines = SDPUtil.find_lines(this.session, prefix);
  7789. lines.forEach(function(line) {
  7790. self.session = self.session.replace(line + '\r\n', '');
  7791. });
  7792. this.raw = this.session + this.media.join('');
  7793. return lines;
  7794. }
  7795. // remove lines matching prefix from a media section specified by mediaindex
  7796. // TODO: non-numeric mediaindex could match mid
  7797. SDP.prototype.removeMediaLines = function(mediaindex, prefix) {
  7798. var self = this;
  7799. var lines = SDPUtil.find_lines(this.media[mediaindex], prefix);
  7800. lines.forEach(function(line) {
  7801. self.media[mediaindex] = self.media[mediaindex].replace(line + '\r\n', '');
  7802. });
  7803. this.raw = this.session + this.media.join('');
  7804. return lines;
  7805. }
  7806. // add content's to a jingle element
  7807. SDP.prototype.toJingle = function (elem, thecreator) {
  7808. // logger.log("SSRC" + ssrcs["audio"] + " - " + ssrcs["video"]);
  7809. var self = this;
  7810. var i, j, k, mline, ssrc, rtpmap, tmp, lines;
  7811. // new bundle plan
  7812. if (SDPUtil.find_line(this.session, 'a=group:')) {
  7813. lines = SDPUtil.find_lines(this.session, 'a=group:');
  7814. for (i = 0; i < lines.length; i++) {
  7815. tmp = lines[i].split(' ');
  7816. var semantics = tmp.shift().substr(8);
  7817. elem.c('group', {xmlns: 'urn:xmpp:jingle:apps:grouping:0', semantics:semantics});
  7818. for (j = 0; j < tmp.length; j++) {
  7819. elem.c('content', {name: tmp[j]}).up();
  7820. }
  7821. elem.up();
  7822. }
  7823. }
  7824. for (i = 0; i < this.media.length; i++) {
  7825. mline = SDPUtil.parse_mline(this.media[i].split('\r\n')[0]);
  7826. if (!(mline.media === 'audio' ||
  7827. mline.media === 'video' ||
  7828. mline.media === 'application'))
  7829. {
  7830. continue;
  7831. }
  7832. if (SDPUtil.find_line(this.media[i], 'a=ssrc:')) {
  7833. ssrc = SDPUtil.find_line(this.media[i], 'a=ssrc:').substring(7).split(' ')[0]; // take the first
  7834. } else {
  7835. ssrc = false;
  7836. }
  7837. elem.c('content', {creator: thecreator, name: mline.media});
  7838. if (SDPUtil.find_line(this.media[i], 'a=mid:')) {
  7839. // prefer identifier from a=mid if present
  7840. var mid = SDPUtil.parse_mid(SDPUtil.find_line(this.media[i], 'a=mid:'));
  7841. elem.attrs({ name: mid });
  7842. }
  7843. if (SDPUtil.find_line(this.media[i], 'a=rtpmap:').length) {
  7844. elem.c('description',
  7845. {xmlns: 'urn:xmpp:jingle:apps:rtp:1',
  7846. media: mline.media });
  7847. if (ssrc) {
  7848. elem.attrs({ssrc: ssrc});
  7849. }
  7850. for (j = 0; j < mline.fmt.length; j++) {
  7851. rtpmap = SDPUtil.find_line(this.media[i], 'a=rtpmap:' + mline.fmt[j]);
  7852. elem.c('payload-type', SDPUtil.parse_rtpmap(rtpmap));
  7853. // put any 'a=fmtp:' + mline.fmt[j] lines into <param name=foo value=bar/>
  7854. if (SDPUtil.find_line(this.media[i], 'a=fmtp:' + mline.fmt[j])) {
  7855. tmp = SDPUtil.parse_fmtp(SDPUtil.find_line(this.media[i], 'a=fmtp:' + mline.fmt[j]));
  7856. for (k = 0; k < tmp.length; k++) {
  7857. elem.c('parameter', tmp[k]).up();
  7858. }
  7859. }
  7860. this.rtcpFbToJingle(i, elem, mline.fmt[j]); // XEP-0293 -- map a=rtcp-fb
  7861. elem.up();
  7862. }
  7863. if (SDPUtil.find_line(this.media[i], 'a=crypto:', this.session)) {
  7864. elem.c('encryption', {required: 1});
  7865. var crypto = SDPUtil.find_lines(this.media[i], 'a=crypto:', this.session);
  7866. crypto.forEach(function(line) {
  7867. elem.c('crypto', SDPUtil.parse_crypto(line)).up();
  7868. });
  7869. elem.up(); // end of encryption
  7870. }
  7871. if (ssrc) {
  7872. // new style mapping
  7873. elem.c('source', { ssrc: ssrc, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  7874. // FIXME: group by ssrc and support multiple different ssrcs
  7875. var ssrclines = SDPUtil.find_lines(this.media[i], 'a=ssrc:');
  7876. if(ssrclines.length > 0) {
  7877. ssrclines.forEach(function (line) {
  7878. var idx = line.indexOf(' ');
  7879. var linessrc = line.substr(0, idx).substr(7);
  7880. if (linessrc != ssrc) {
  7881. elem.up();
  7882. ssrc = linessrc;
  7883. elem.c('source', { ssrc: ssrc, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  7884. }
  7885. var kv = line.substr(idx + 1);
  7886. elem.c('parameter');
  7887. if (kv.indexOf(':') == -1) {
  7888. elem.attrs({ name: kv });
  7889. } else {
  7890. var k = kv.split(':', 2)[0];
  7891. elem.attrs({ name: k });
  7892. var v = kv.split(':', 2)[1];
  7893. v = SDPUtil.filter_special_chars(v);
  7894. elem.attrs({ value: v });
  7895. }
  7896. elem.up();
  7897. });
  7898. } else {
  7899. elem.up();
  7900. elem.c('source', { ssrc: ssrc, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  7901. elem.c('parameter');
  7902. elem.attrs({name: "cname", value:Math.random().toString(36).substring(7)});
  7903. elem.up();
  7904. var msid = null;
  7905. if(mline.media == "audio")
  7906. {
  7907. msid = APP.RTC.localAudio.getId();
  7908. }
  7909. else
  7910. {
  7911. msid = APP.RTC.localVideo.getId();
  7912. }
  7913. if(msid != null)
  7914. {
  7915. msid = SDPUtil.filter_special_chars(msid);
  7916. elem.c('parameter');
  7917. elem.attrs({name: "msid", value:msid});
  7918. elem.up();
  7919. elem.c('parameter');
  7920. elem.attrs({name: "mslabel", value:msid});
  7921. elem.up();
  7922. elem.c('parameter');
  7923. elem.attrs({name: "label", value:msid});
  7924. elem.up();
  7925. }
  7926. }
  7927. elem.up();
  7928. // XEP-0339 handle ssrc-group attributes
  7929. var ssrc_group_lines = SDPUtil.find_lines(this.media[i], 'a=ssrc-group:');
  7930. ssrc_group_lines.forEach(function(line) {
  7931. var idx = line.indexOf(' ');
  7932. var semantics = line.substr(0, idx).substr(13);
  7933. var ssrcs = line.substr(14 + semantics.length).split(' ');
  7934. if (ssrcs.length) {
  7935. elem.c('ssrc-group', { semantics: semantics, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  7936. ssrcs.forEach(function(ssrc) {
  7937. elem.c('source', { ssrc: ssrc })
  7938. .up();
  7939. });
  7940. elem.up();
  7941. }
  7942. });
  7943. }
  7944. if (SDPUtil.find_line(this.media[i], 'a=rtcp-mux')) {
  7945. elem.c('rtcp-mux').up();
  7946. }
  7947. // XEP-0293 -- map a=rtcp-fb:*
  7948. this.rtcpFbToJingle(i, elem, '*');
  7949. // XEP-0294
  7950. if (SDPUtil.find_line(this.media[i], 'a=extmap:')) {
  7951. lines = SDPUtil.find_lines(this.media[i], 'a=extmap:');
  7952. for (j = 0; j < lines.length; j++) {
  7953. tmp = SDPUtil.parse_extmap(lines[j]);
  7954. elem.c('rtp-hdrext', { xmlns: 'urn:xmpp:jingle:apps:rtp:rtp-hdrext:0',
  7955. uri: tmp.uri,
  7956. id: tmp.value });
  7957. if (tmp.hasOwnProperty('direction')) {
  7958. switch (tmp.direction) {
  7959. case 'sendonly':
  7960. elem.attrs({senders: 'responder'});
  7961. break;
  7962. case 'recvonly':
  7963. elem.attrs({senders: 'initiator'});
  7964. break;
  7965. case 'sendrecv':
  7966. elem.attrs({senders: 'both'});
  7967. break;
  7968. case 'inactive':
  7969. elem.attrs({senders: 'none'});
  7970. break;
  7971. }
  7972. }
  7973. // TODO: handle params
  7974. elem.up();
  7975. }
  7976. }
  7977. elem.up(); // end of description
  7978. }
  7979. // map ice-ufrag/pwd, dtls fingerprint, candidates
  7980. this.transportToJingle(i, elem);
  7981. if (SDPUtil.find_line(this.media[i], 'a=sendrecv', this.session)) {
  7982. elem.attrs({senders: 'both'});
  7983. } else if (SDPUtil.find_line(this.media[i], 'a=sendonly', this.session)) {
  7984. elem.attrs({senders: 'initiator'});
  7985. } else if (SDPUtil.find_line(this.media[i], 'a=recvonly', this.session)) {
  7986. elem.attrs({senders: 'responder'});
  7987. } else if (SDPUtil.find_line(this.media[i], 'a=inactive', this.session)) {
  7988. elem.attrs({senders: 'none'});
  7989. }
  7990. if (mline.port == '0') {
  7991. // estos hack to reject an m-line
  7992. elem.attrs({senders: 'rejected'});
  7993. }
  7994. elem.up(); // end of content
  7995. }
  7996. elem.up();
  7997. return elem;
  7998. };
  7999. SDP.prototype.transportToJingle = function (mediaindex, elem) {
  8000. var tmp, sctpmap, sctpAttrs, fingerprints;
  8001. var self = this;
  8002. elem.c('transport');
  8003. // XEP-0343 DTLS/SCTP
  8004. if (SDPUtil.find_line(this.media[mediaindex], 'a=sctpmap:').length)
  8005. {
  8006. sctpmap = SDPUtil.find_line(
  8007. this.media[mediaindex], 'a=sctpmap:', self.session);
  8008. if (sctpmap)
  8009. {
  8010. sctpAttrs = SDPUtil.parse_sctpmap(sctpmap);
  8011. elem.c('sctpmap',
  8012. {
  8013. xmlns: 'urn:xmpp:jingle:transports:dtls-sctp:1',
  8014. number: sctpAttrs[0], /* SCTP port */
  8015. protocol: sctpAttrs[1] /* protocol */
  8016. });
  8017. // Optional stream count attribute
  8018. if (sctpAttrs.length > 2)
  8019. elem.attrs({ streams: sctpAttrs[2]});
  8020. elem.up();
  8021. }
  8022. }
  8023. // XEP-0320
  8024. fingerprints = SDPUtil.find_lines(this.media[mediaindex], 'a=fingerprint:', this.session);
  8025. fingerprints.forEach(function(line) {
  8026. tmp = SDPUtil.parse_fingerprint(line);
  8027. tmp.xmlns = 'urn:xmpp:jingle:apps:dtls:0';
  8028. elem.c('fingerprint').t(tmp.fingerprint);
  8029. delete tmp.fingerprint;
  8030. line = SDPUtil.find_line(self.media[mediaindex], 'a=setup:', self.session);
  8031. if (line) {
  8032. tmp.setup = line.substr(8);
  8033. }
  8034. elem.attrs(tmp);
  8035. elem.up(); // end of fingerprint
  8036. });
  8037. tmp = SDPUtil.iceparams(this.media[mediaindex], this.session);
  8038. if (tmp) {
  8039. tmp.xmlns = 'urn:xmpp:jingle:transports:ice-udp:1';
  8040. elem.attrs(tmp);
  8041. // XEP-0176
  8042. if (SDPUtil.find_line(this.media[mediaindex], 'a=candidate:', this.session)) { // add any a=candidate lines
  8043. var lines = SDPUtil.find_lines(this.media[mediaindex], 'a=candidate:', this.session);
  8044. lines.forEach(function (line) {
  8045. var candidate = SDPUtil.candidateToJingle(line);
  8046. var protocol = (candidate &&
  8047. typeof candidate.protocol === 'string')
  8048. ? candidate.protocol.toLowerCase() : '';
  8049. if ((self.removeTcpCandidates && protocol === 'tcp') ||
  8050. (self.removeUdpCandidates && protocol === 'udp')) {
  8051. return;
  8052. }
  8053. elem.c('candidate', candidate).up();
  8054. });
  8055. }
  8056. }
  8057. elem.up(); // end of transport
  8058. }
  8059. SDP.prototype.rtcpFbToJingle = function (mediaindex, elem, payloadtype) { // XEP-0293
  8060. var lines = SDPUtil.find_lines(this.media[mediaindex], 'a=rtcp-fb:' + payloadtype);
  8061. lines.forEach(function (line) {
  8062. var tmp = SDPUtil.parse_rtcpfb(line);
  8063. if (tmp.type == 'trr-int') {
  8064. elem.c('rtcp-fb-trr-int', {xmlns: 'urn:xmpp:jingle:apps:rtp:rtcp-fb:0', value: tmp.params[0]});
  8065. elem.up();
  8066. } else {
  8067. elem.c('rtcp-fb', {xmlns: 'urn:xmpp:jingle:apps:rtp:rtcp-fb:0', type: tmp.type});
  8068. if (tmp.params.length > 0) {
  8069. elem.attrs({'subtype': tmp.params[0]});
  8070. }
  8071. elem.up();
  8072. }
  8073. });
  8074. };
  8075. SDP.prototype.rtcpFbFromJingle = function (elem, payloadtype) { // XEP-0293
  8076. var media = '';
  8077. var tmp = elem.find('>rtcp-fb-trr-int[xmlns="urn:xmpp:jingle:apps:rtp:rtcp-fb:0"]');
  8078. if (tmp.length) {
  8079. media += 'a=rtcp-fb:' + '*' + ' ' + 'trr-int' + ' ';
  8080. if (tmp.attr('value')) {
  8081. media += tmp.attr('value');
  8082. } else {
  8083. media += '0';
  8084. }
  8085. media += '\r\n';
  8086. }
  8087. tmp = elem.find('>rtcp-fb[xmlns="urn:xmpp:jingle:apps:rtp:rtcp-fb:0"]');
  8088. tmp.each(function () {
  8089. media += 'a=rtcp-fb:' + payloadtype + ' ' + $(this).attr('type');
  8090. if ($(this).attr('subtype')) {
  8091. media += ' ' + $(this).attr('subtype');
  8092. }
  8093. media += '\r\n';
  8094. });
  8095. return media;
  8096. };
  8097. // construct an SDP from a jingle stanza
  8098. SDP.prototype.fromJingle = function (jingle) {
  8099. var self = this;
  8100. this.raw = 'v=0\r\n' +
  8101. 'o=- 1923518516 2 IN IP4 0.0.0.0\r\n' +// FIXME
  8102. 's=-\r\n' +
  8103. 't=0 0\r\n';
  8104. // http://tools.ietf.org/html/draft-ietf-mmusic-sdp-bundle-negotiation-04#section-8
  8105. if ($(jingle).find('>group[xmlns="urn:xmpp:jingle:apps:grouping:0"]').length) {
  8106. $(jingle).find('>group[xmlns="urn:xmpp:jingle:apps:grouping:0"]').each(function (idx, group) {
  8107. var contents = $(group).find('>content').map(function (idx, content) {
  8108. return content.getAttribute('name');
  8109. }).get();
  8110. if (contents.length > 0) {
  8111. self.raw += 'a=group:' + (group.getAttribute('semantics') || group.getAttribute('type')) + ' ' + contents.join(' ') + '\r\n';
  8112. }
  8113. });
  8114. }
  8115. this.session = this.raw;
  8116. jingle.find('>content').each(function () {
  8117. var m = self.jingle2media($(this));
  8118. self.media.push(m);
  8119. });
  8120. // reconstruct msid-semantic -- apparently not necessary
  8121. /*
  8122. var msid = SDPUtil.parse_ssrc(this.raw);
  8123. if (msid.hasOwnProperty('mslabel')) {
  8124. this.session += "a=msid-semantic: WMS " + msid.mslabel + "\r\n";
  8125. }
  8126. */
  8127. this.raw = this.session + this.media.join('');
  8128. };
  8129. // translate a jingle content element into an an SDP media part
  8130. SDP.prototype.jingle2media = function (content) {
  8131. var media = '',
  8132. desc = content.find('description'),
  8133. ssrc = desc.attr('ssrc'),
  8134. self = this,
  8135. tmp;
  8136. var sctp = content.find(
  8137. '>transport>sctpmap[xmlns="urn:xmpp:jingle:transports:dtls-sctp:1"]');
  8138. tmp = { media: desc.attr('media') };
  8139. tmp.port = '1';
  8140. if (content.attr('senders') == 'rejected') {
  8141. // estos hack to reject an m-line.
  8142. tmp.port = '0';
  8143. }
  8144. if (content.find('>transport>fingerprint').length || desc.find('encryption').length) {
  8145. if (sctp.length)
  8146. tmp.proto = 'DTLS/SCTP';
  8147. else
  8148. tmp.proto = 'RTP/SAVPF';
  8149. } else {
  8150. tmp.proto = 'RTP/AVPF';
  8151. }
  8152. if (!sctp.length) {
  8153. tmp.fmt = desc.find('payload-type').map(
  8154. function () { return this.getAttribute('id'); }).get();
  8155. media += SDPUtil.build_mline(tmp) + '\r\n';
  8156. } else {
  8157. media += 'm=application 1 DTLS/SCTP ' + sctp.attr('number') + '\r\n';
  8158. media += 'a=sctpmap:' + sctp.attr('number') +
  8159. ' ' + sctp.attr('protocol');
  8160. var streamCount = sctp.attr('streams');
  8161. if (streamCount)
  8162. media += ' ' + streamCount + '\r\n';
  8163. else
  8164. media += '\r\n';
  8165. }
  8166. media += 'c=IN IP4 0.0.0.0\r\n';
  8167. if (!sctp.length)
  8168. media += 'a=rtcp:1 IN IP4 0.0.0.0\r\n';
  8169. tmp = content.find('>transport[xmlns="urn:xmpp:jingle:transports:ice-udp:1"]');
  8170. if (tmp.length) {
  8171. if (tmp.attr('ufrag')) {
  8172. media += SDPUtil.build_iceufrag(tmp.attr('ufrag')) + '\r\n';
  8173. }
  8174. if (tmp.attr('pwd')) {
  8175. media += SDPUtil.build_icepwd(tmp.attr('pwd')) + '\r\n';
  8176. }
  8177. tmp.find('>fingerprint').each(function () {
  8178. // FIXME: check namespace at some point
  8179. media += 'a=fingerprint:' + this.getAttribute('hash');
  8180. media += ' ' + $(this).text();
  8181. media += '\r\n';
  8182. if (this.getAttribute('setup')) {
  8183. media += 'a=setup:' + this.getAttribute('setup') + '\r\n';
  8184. }
  8185. });
  8186. }
  8187. switch (content.attr('senders')) {
  8188. case 'initiator':
  8189. media += 'a=sendonly\r\n';
  8190. break;
  8191. case 'responder':
  8192. media += 'a=recvonly\r\n';
  8193. break;
  8194. case 'none':
  8195. media += 'a=inactive\r\n';
  8196. break;
  8197. case 'both':
  8198. media += 'a=sendrecv\r\n';
  8199. break;
  8200. }
  8201. media += 'a=mid:' + content.attr('name') + '\r\n';
  8202. // <description><rtcp-mux/></description>
  8203. // see http://code.google.com/p/libjingle/issues/detail?id=309 -- no spec though
  8204. // and http://mail.jabber.org/pipermail/jingle/2011-December/001761.html
  8205. if (desc.find('rtcp-mux').length) {
  8206. media += 'a=rtcp-mux\r\n';
  8207. }
  8208. if (desc.find('encryption').length) {
  8209. desc.find('encryption>crypto').each(function () {
  8210. media += 'a=crypto:' + this.getAttribute('tag');
  8211. media += ' ' + this.getAttribute('crypto-suite');
  8212. media += ' ' + this.getAttribute('key-params');
  8213. if (this.getAttribute('session-params')) {
  8214. media += ' ' + this.getAttribute('session-params');
  8215. }
  8216. media += '\r\n';
  8217. });
  8218. }
  8219. desc.find('payload-type').each(function () {
  8220. media += SDPUtil.build_rtpmap(this) + '\r\n';
  8221. if ($(this).find('>parameter').length) {
  8222. media += 'a=fmtp:' + this.getAttribute('id') + ' ';
  8223. media += $(this).find('parameter').map(function () {
  8224. return (this.getAttribute('name')
  8225. ? (this.getAttribute('name') + '=') : '') +
  8226. this.getAttribute('value');
  8227. }).get().join('; ');
  8228. media += '\r\n';
  8229. }
  8230. // xep-0293
  8231. media += self.rtcpFbFromJingle($(this), this.getAttribute('id'));
  8232. });
  8233. // xep-0293
  8234. media += self.rtcpFbFromJingle(desc, '*');
  8235. // xep-0294
  8236. tmp = desc.find('>rtp-hdrext[xmlns="urn:xmpp:jingle:apps:rtp:rtp-hdrext:0"]');
  8237. tmp.each(function () {
  8238. media += 'a=extmap:' + this.getAttribute('id') + ' ' + this.getAttribute('uri') + '\r\n';
  8239. });
  8240. content.find('>transport[xmlns="urn:xmpp:jingle:transports:ice-udp:1"]>candidate').each(function () {
  8241. var protocol = this.getAttribute('protocol');
  8242. protocol = (typeof protocol === 'string') ? protocol.toLowerCase(): '';
  8243. if ((self.removeTcpCandidates && protocol === 'tcp') ||
  8244. (self.removeUdpCandidates && protocol === 'udp')) {
  8245. return;
  8246. }
  8247. media += SDPUtil.candidateFromJingle(this);
  8248. });
  8249. // XEP-0339 handle ssrc-group attributes
  8250. content.find('description>ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]').each(function() {
  8251. var semantics = this.getAttribute('semantics');
  8252. var ssrcs = $(this).find('>source').map(function() {
  8253. return this.getAttribute('ssrc');
  8254. }).get();
  8255. if (ssrcs.length) {
  8256. media += 'a=ssrc-group:' + semantics + ' ' + ssrcs.join(' ') + '\r\n';
  8257. }
  8258. });
  8259. tmp = content.find('description>source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]');
  8260. tmp.each(function () {
  8261. var ssrc = this.getAttribute('ssrc');
  8262. $(this).find('>parameter').each(function () {
  8263. var name = this.getAttribute('name');
  8264. var value = this.getAttribute('value');
  8265. value = SDPUtil.filter_special_chars(value);
  8266. media += 'a=ssrc:' + ssrc + ' ' + name;
  8267. if (value && value.length)
  8268. media += ':' + value;
  8269. media += '\r\n';
  8270. });
  8271. });
  8272. return media;
  8273. };
  8274. module.exports = SDP;
  8275. }).call(this,"/modules/xmpp/SDP.js")
  8276. },{"./SDPUtil":32,"jitsi-meet-logger":48}],31:[function(require,module,exports){
  8277. var SDPUtil = require("./SDPUtil");
  8278. function SDPDiffer(mySDP, otherSDP)
  8279. {
  8280. this.mySDP = mySDP;
  8281. this.otherSDP = otherSDP;
  8282. }
  8283. /**
  8284. * Returns map of MediaChannel that contains media contained in
  8285. * 'mySDP', but not contained in 'otherSdp'. Mapped by channel idx.
  8286. */
  8287. SDPDiffer.prototype.getNewMedia = function() {
  8288. // this could be useful in Array.prototype.
  8289. function arrayEquals(array) {
  8290. // if the other array is a falsy value, return
  8291. if (!array)
  8292. return false;
  8293. // compare lengths - can save a lot of time
  8294. if (this.length != array.length)
  8295. return false;
  8296. for (var i = 0, l=this.length; i < l; i++) {
  8297. // Check if we have nested arrays
  8298. if (this[i] instanceof Array && array[i] instanceof Array) {
  8299. // recurse into the nested arrays
  8300. if (!this[i].equals(array[i]))
  8301. return false;
  8302. }
  8303. else if (this[i] != array[i]) {
  8304. // Warning - two different object instances will never be
  8305. // equal: {x:20} != {x:20}
  8306. return false;
  8307. }
  8308. }
  8309. return true;
  8310. }
  8311. var myMedias = this.mySDP.getMediaSsrcMap();
  8312. var othersMedias = this.otherSDP.getMediaSsrcMap();
  8313. var newMedia = {};
  8314. Object.keys(othersMedias).forEach(function(othersMediaIdx) {
  8315. var myMedia = myMedias[othersMediaIdx];
  8316. var othersMedia = othersMedias[othersMediaIdx];
  8317. if(!myMedia && othersMedia) {
  8318. // Add whole channel
  8319. newMedia[othersMediaIdx] = othersMedia;
  8320. return;
  8321. }
  8322. // Look for new ssrcs across the channel
  8323. Object.keys(othersMedia.ssrcs).forEach(function(ssrc) {
  8324. if(Object.keys(myMedia.ssrcs).indexOf(ssrc) === -1) {
  8325. // Allocate channel if we've found ssrc that doesn't exist in
  8326. // our channel
  8327. if(!newMedia[othersMediaIdx]){
  8328. newMedia[othersMediaIdx] = {
  8329. mediaindex: othersMedia.mediaindex,
  8330. mid: othersMedia.mid,
  8331. ssrcs: {},
  8332. ssrcGroups: []
  8333. };
  8334. }
  8335. newMedia[othersMediaIdx].ssrcs[ssrc] = othersMedia.ssrcs[ssrc];
  8336. }
  8337. });
  8338. // Look for new ssrc groups across the channels
  8339. othersMedia.ssrcGroups.forEach(function(otherSsrcGroup){
  8340. // try to match the other ssrc-group with an ssrc-group of ours
  8341. var matched = false;
  8342. for (var i = 0; i < myMedia.ssrcGroups.length; i++) {
  8343. var mySsrcGroup = myMedia.ssrcGroups[i];
  8344. if (otherSsrcGroup.semantics == mySsrcGroup.semantics &&
  8345. arrayEquals.apply(otherSsrcGroup.ssrcs,
  8346. [mySsrcGroup.ssrcs])) {
  8347. matched = true;
  8348. break;
  8349. }
  8350. }
  8351. if (!matched) {
  8352. // Allocate channel if we've found an ssrc-group that doesn't
  8353. // exist in our channel
  8354. if(!newMedia[othersMediaIdx]){
  8355. newMedia[othersMediaIdx] = {
  8356. mediaindex: othersMedia.mediaindex,
  8357. mid: othersMedia.mid,
  8358. ssrcs: {},
  8359. ssrcGroups: []
  8360. };
  8361. }
  8362. newMedia[othersMediaIdx].ssrcGroups.push(otherSsrcGroup);
  8363. }
  8364. });
  8365. });
  8366. return newMedia;
  8367. };
  8368. /**
  8369. * TODO: document!
  8370. */
  8371. SDPDiffer.prototype.toJingle = function(modify) {
  8372. var sdpMediaSsrcs = this.getNewMedia();
  8373. var modified = false;
  8374. Object.keys(sdpMediaSsrcs).forEach(function(mediaindex){
  8375. modified = true;
  8376. var media = sdpMediaSsrcs[mediaindex];
  8377. modify.c('content', {name: media.mid});
  8378. modify.c('description',
  8379. {xmlns:'urn:xmpp:jingle:apps:rtp:1', media: media.mid});
  8380. // FIXME: not completely sure this operates on blocks and / or handles
  8381. // different ssrcs correctly
  8382. // generate sources from lines
  8383. Object.keys(media.ssrcs).forEach(function(ssrcNum) {
  8384. var mediaSsrc = media.ssrcs[ssrcNum];
  8385. modify.c('source', { xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  8386. modify.attrs({ssrc: mediaSsrc.ssrc});
  8387. // iterate over ssrc lines
  8388. mediaSsrc.lines.forEach(function (line) {
  8389. var idx = line.indexOf(' ');
  8390. var kv = line.substr(idx + 1);
  8391. modify.c('parameter');
  8392. if (kv.indexOf(':') == -1) {
  8393. modify.attrs({ name: kv });
  8394. } else {
  8395. var nv = kv.split(':', 2);
  8396. var name = nv[0];
  8397. var value = SDPUtil.filter_special_chars(nv[1]);
  8398. modify.attrs({ name: name });
  8399. modify.attrs({ value: value });
  8400. }
  8401. modify.up(); // end of parameter
  8402. });
  8403. modify.up(); // end of source
  8404. });
  8405. // generate source groups from lines
  8406. media.ssrcGroups.forEach(function(ssrcGroup) {
  8407. if (ssrcGroup.ssrcs.length) {
  8408. modify.c('ssrc-group', {
  8409. semantics: ssrcGroup.semantics,
  8410. xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0'
  8411. });
  8412. ssrcGroup.ssrcs.forEach(function (ssrc) {
  8413. modify.c('source', { ssrc: ssrc })
  8414. .up(); // end of source
  8415. });
  8416. modify.up(); // end of ssrc-group
  8417. }
  8418. });
  8419. modify.up(); // end of description
  8420. modify.up(); // end of content
  8421. });
  8422. return modified;
  8423. };
  8424. module.exports = SDPDiffer;
  8425. },{"./SDPUtil":32}],32:[function(require,module,exports){
  8426. (function (__filename){
  8427. var logger = require("jitsi-meet-logger").getLogger(__filename);
  8428. var RTCBrowserType = require("../RTC/RTCBrowserType");
  8429. SDPUtil = {
  8430. filter_special_chars: function (text) {
  8431. return text.replace(/[\\\/\{,\}\+]/g, "");
  8432. },
  8433. iceparams: function (mediadesc, sessiondesc) {
  8434. var data = null;
  8435. if (SDPUtil.find_line(mediadesc, 'a=ice-ufrag:', sessiondesc) &&
  8436. SDPUtil.find_line(mediadesc, 'a=ice-pwd:', sessiondesc)) {
  8437. data = {
  8438. ufrag: SDPUtil.parse_iceufrag(SDPUtil.find_line(mediadesc, 'a=ice-ufrag:', sessiondesc)),
  8439. pwd: SDPUtil.parse_icepwd(SDPUtil.find_line(mediadesc, 'a=ice-pwd:', sessiondesc))
  8440. };
  8441. }
  8442. return data;
  8443. },
  8444. parse_iceufrag: function (line) {
  8445. return line.substring(12);
  8446. },
  8447. build_iceufrag: function (frag) {
  8448. return 'a=ice-ufrag:' + frag;
  8449. },
  8450. parse_icepwd: function (line) {
  8451. return line.substring(10);
  8452. },
  8453. build_icepwd: function (pwd) {
  8454. return 'a=ice-pwd:' + pwd;
  8455. },
  8456. parse_mid: function (line) {
  8457. return line.substring(6);
  8458. },
  8459. parse_mline: function (line) {
  8460. var parts = line.substring(2).split(' '),
  8461. data = {};
  8462. data.media = parts.shift();
  8463. data.port = parts.shift();
  8464. data.proto = parts.shift();
  8465. if (parts[parts.length - 1] === '') { // trailing whitespace
  8466. parts.pop();
  8467. }
  8468. data.fmt = parts;
  8469. return data;
  8470. },
  8471. build_mline: function (mline) {
  8472. return 'm=' + mline.media + ' ' + mline.port + ' ' + mline.proto + ' ' + mline.fmt.join(' ');
  8473. },
  8474. parse_rtpmap: function (line) {
  8475. var parts = line.substring(9).split(' '),
  8476. data = {};
  8477. data.id = parts.shift();
  8478. parts = parts[0].split('/');
  8479. data.name = parts.shift();
  8480. data.clockrate = parts.shift();
  8481. data.channels = parts.length ? parts.shift() : '1';
  8482. return data;
  8483. },
  8484. /**
  8485. * Parses SDP line "a=sctpmap:..." and extracts SCTP port from it.
  8486. * @param line eg. "a=sctpmap:5000 webrtc-datachannel"
  8487. * @returns [SCTP port number, protocol, streams]
  8488. */
  8489. parse_sctpmap: function (line)
  8490. {
  8491. var parts = line.substring(10).split(' ');
  8492. var sctpPort = parts[0];
  8493. var protocol = parts[1];
  8494. // Stream count is optional
  8495. var streamCount = parts.length > 2 ? parts[2] : null;
  8496. return [sctpPort, protocol, streamCount];// SCTP port
  8497. },
  8498. build_rtpmap: function (el) {
  8499. var line = 'a=rtpmap:' + el.getAttribute('id') + ' ' + el.getAttribute('name') + '/' + el.getAttribute('clockrate');
  8500. if (el.getAttribute('channels') && el.getAttribute('channels') != '1') {
  8501. line += '/' + el.getAttribute('channels');
  8502. }
  8503. return line;
  8504. },
  8505. parse_crypto: function (line) {
  8506. var parts = line.substring(9).split(' '),
  8507. data = {};
  8508. data.tag = parts.shift();
  8509. data['crypto-suite'] = parts.shift();
  8510. data['key-params'] = parts.shift();
  8511. if (parts.length) {
  8512. data['session-params'] = parts.join(' ');
  8513. }
  8514. return data;
  8515. },
  8516. parse_fingerprint: function (line) { // RFC 4572
  8517. var parts = line.substring(14).split(' '),
  8518. data = {};
  8519. data.hash = parts.shift();
  8520. data.fingerprint = parts.shift();
  8521. // TODO assert that fingerprint satisfies 2UHEX *(":" 2UHEX) ?
  8522. return data;
  8523. },
  8524. parse_fmtp: function (line) {
  8525. var parts = line.split(' '),
  8526. i, key, value,
  8527. data = [];
  8528. parts.shift();
  8529. parts = parts.join(' ').split(';');
  8530. for (i = 0; i < parts.length; i++) {
  8531. key = parts[i].split('=')[0];
  8532. while (key.length && key[0] == ' ') {
  8533. key = key.substring(1);
  8534. }
  8535. value = parts[i].split('=')[1];
  8536. if (key && value) {
  8537. data.push({name: key, value: value});
  8538. } else if (key) {
  8539. // rfc 4733 (DTMF) style stuff
  8540. data.push({name: '', value: key});
  8541. }
  8542. }
  8543. return data;
  8544. },
  8545. parse_icecandidate: function (line) {
  8546. var candidate = {},
  8547. elems = line.split(' ');
  8548. candidate.foundation = elems[0].substring(12);
  8549. candidate.component = elems[1];
  8550. candidate.protocol = elems[2].toLowerCase();
  8551. candidate.priority = elems[3];
  8552. candidate.ip = elems[4];
  8553. candidate.port = elems[5];
  8554. // elems[6] => "typ"
  8555. candidate.type = elems[7];
  8556. candidate.generation = 0; // default value, may be overwritten below
  8557. for (var i = 8; i < elems.length; i += 2) {
  8558. switch (elems[i]) {
  8559. case 'raddr':
  8560. candidate['rel-addr'] = elems[i + 1];
  8561. break;
  8562. case 'rport':
  8563. candidate['rel-port'] = elems[i + 1];
  8564. break;
  8565. case 'generation':
  8566. candidate.generation = elems[i + 1];
  8567. break;
  8568. case 'tcptype':
  8569. candidate.tcptype = elems[i + 1];
  8570. break;
  8571. default: // TODO
  8572. logger.log('parse_icecandidate not translating "' + elems[i] + '" = "' + elems[i + 1] + '"');
  8573. }
  8574. }
  8575. candidate.network = '1';
  8576. candidate.id = Math.random().toString(36).substr(2, 10); // not applicable to SDP -- FIXME: should be unique, not just random
  8577. return candidate;
  8578. },
  8579. build_icecandidate: function (cand) {
  8580. var line = ['a=candidate:' + cand.foundation, cand.component, cand.protocol, cand.priority, cand.ip, cand.port, 'typ', cand.type].join(' ');
  8581. line += ' ';
  8582. switch (cand.type) {
  8583. case 'srflx':
  8584. case 'prflx':
  8585. case 'relay':
  8586. if (cand.hasOwnAttribute('rel-addr') && cand.hasOwnAttribute('rel-port')) {
  8587. line += 'raddr';
  8588. line += ' ';
  8589. line += cand['rel-addr'];
  8590. line += ' ';
  8591. line += 'rport';
  8592. line += ' ';
  8593. line += cand['rel-port'];
  8594. line += ' ';
  8595. }
  8596. break;
  8597. }
  8598. if (cand.hasOwnAttribute('tcptype')) {
  8599. line += 'tcptype';
  8600. line += ' ';
  8601. line += cand.tcptype;
  8602. line += ' ';
  8603. }
  8604. line += 'generation';
  8605. line += ' ';
  8606. line += cand.hasOwnAttribute('generation') ? cand.generation : '0';
  8607. return line;
  8608. },
  8609. parse_ssrc: function (desc) {
  8610. // proprietary mapping of a=ssrc lines
  8611. // TODO: see "Jingle RTP Source Description" by Juberti and P. Thatcher on google docs
  8612. // and parse according to that
  8613. var lines = desc.split('\r\n'),
  8614. data = {};
  8615. for (var i = 0; i < lines.length; i++) {
  8616. if (lines[i].substring(0, 7) == 'a=ssrc:') {
  8617. var idx = lines[i].indexOf(' ');
  8618. data[lines[i].substr(idx + 1).split(':', 2)[0]] = lines[i].substr(idx + 1).split(':', 2)[1];
  8619. }
  8620. }
  8621. return data;
  8622. },
  8623. parse_rtcpfb: function (line) {
  8624. var parts = line.substr(10).split(' ');
  8625. var data = {};
  8626. data.pt = parts.shift();
  8627. data.type = parts.shift();
  8628. data.params = parts;
  8629. return data;
  8630. },
  8631. parse_extmap: function (line) {
  8632. var parts = line.substr(9).split(' ');
  8633. var data = {};
  8634. data.value = parts.shift();
  8635. if (data.value.indexOf('/') != -1) {
  8636. data.direction = data.value.substr(data.value.indexOf('/') + 1);
  8637. data.value = data.value.substr(0, data.value.indexOf('/'));
  8638. } else {
  8639. data.direction = 'both';
  8640. }
  8641. data.uri = parts.shift();
  8642. data.params = parts;
  8643. return data;
  8644. },
  8645. find_line: function (haystack, needle, sessionpart) {
  8646. var lines = haystack.split('\r\n');
  8647. for (var i = 0; i < lines.length; i++) {
  8648. if (lines[i].substring(0, needle.length) == needle) {
  8649. return lines[i];
  8650. }
  8651. }
  8652. if (!sessionpart) {
  8653. return false;
  8654. }
  8655. // search session part
  8656. lines = sessionpart.split('\r\n');
  8657. for (var j = 0; j < lines.length; j++) {
  8658. if (lines[j].substring(0, needle.length) == needle) {
  8659. return lines[j];
  8660. }
  8661. }
  8662. return false;
  8663. },
  8664. find_lines: function (haystack, needle, sessionpart) {
  8665. var lines = haystack.split('\r\n'),
  8666. needles = [];
  8667. for (var i = 0; i < lines.length; i++) {
  8668. if (lines[i].substring(0, needle.length) == needle)
  8669. needles.push(lines[i]);
  8670. }
  8671. if (needles.length || !sessionpart) {
  8672. return needles;
  8673. }
  8674. // search session part
  8675. lines = sessionpart.split('\r\n');
  8676. for (var j = 0; j < lines.length; j++) {
  8677. if (lines[j].substring(0, needle.length) == needle) {
  8678. needles.push(lines[j]);
  8679. }
  8680. }
  8681. return needles;
  8682. },
  8683. candidateToJingle: function (line) {
  8684. // a=candidate:2979166662 1 udp 2113937151 192.168.2.100 57698 typ host generation 0
  8685. // <candidate component=... foundation=... generation=... id=... ip=... network=... port=... priority=... protocol=... type=.../>
  8686. if (line.indexOf('candidate:') === 0) {
  8687. line = 'a=' + line;
  8688. } else if (line.substring(0, 12) != 'a=candidate:') {
  8689. logger.log('parseCandidate called with a line that is not a candidate line');
  8690. logger.log(line);
  8691. return null;
  8692. }
  8693. if (line.substring(line.length - 2) == '\r\n') // chomp it
  8694. line = line.substring(0, line.length - 2);
  8695. var candidate = {},
  8696. elems = line.split(' '),
  8697. i;
  8698. if (elems[6] != 'typ') {
  8699. logger.log('did not find typ in the right place');
  8700. logger.log(line);
  8701. return null;
  8702. }
  8703. candidate.foundation = elems[0].substring(12);
  8704. candidate.component = elems[1];
  8705. candidate.protocol = elems[2].toLowerCase();
  8706. candidate.priority = elems[3];
  8707. candidate.ip = elems[4];
  8708. candidate.port = elems[5];
  8709. // elems[6] => "typ"
  8710. candidate.type = elems[7];
  8711. candidate.generation = '0'; // default, may be overwritten below
  8712. for (i = 8; i < elems.length; i += 2) {
  8713. switch (elems[i]) {
  8714. case 'raddr':
  8715. candidate['rel-addr'] = elems[i + 1];
  8716. break;
  8717. case 'rport':
  8718. candidate['rel-port'] = elems[i + 1];
  8719. break;
  8720. case 'generation':
  8721. candidate.generation = elems[i + 1];
  8722. break;
  8723. case 'tcptype':
  8724. candidate.tcptype = elems[i + 1];
  8725. break;
  8726. default: // TODO
  8727. logger.log('not translating "' + elems[i] + '" = "' + elems[i + 1] + '"');
  8728. }
  8729. }
  8730. candidate.network = '1';
  8731. candidate.id = Math.random().toString(36).substr(2, 10); // not applicable to SDP -- FIXME: should be unique, not just random
  8732. return candidate;
  8733. },
  8734. candidateFromJingle: function (cand) {
  8735. var line = 'a=candidate:';
  8736. line += cand.getAttribute('foundation');
  8737. line += ' ';
  8738. line += cand.getAttribute('component');
  8739. line += ' ';
  8740. var protocol = cand.getAttribute('protocol');
  8741. // use tcp candidates for FF
  8742. if (RTCBrowserType.isFirefox() && protocol.toLowerCase() == 'ssltcp') {
  8743. protocol = 'tcp';
  8744. }
  8745. line += protocol; //.toUpperCase(); // chrome M23 doesn't like this
  8746. line += ' ';
  8747. line += cand.getAttribute('priority');
  8748. line += ' ';
  8749. line += cand.getAttribute('ip');
  8750. line += ' ';
  8751. line += cand.getAttribute('port');
  8752. line += ' ';
  8753. line += 'typ';
  8754. line += ' ' + cand.getAttribute('type');
  8755. line += ' ';
  8756. switch (cand.getAttribute('type')) {
  8757. case 'srflx':
  8758. case 'prflx':
  8759. case 'relay':
  8760. if (cand.getAttribute('rel-addr') && cand.getAttribute('rel-port')) {
  8761. line += 'raddr';
  8762. line += ' ';
  8763. line += cand.getAttribute('rel-addr');
  8764. line += ' ';
  8765. line += 'rport';
  8766. line += ' ';
  8767. line += cand.getAttribute('rel-port');
  8768. line += ' ';
  8769. }
  8770. break;
  8771. }
  8772. if (protocol.toLowerCase() == 'tcp') {
  8773. line += 'tcptype';
  8774. line += ' ';
  8775. line += cand.getAttribute('tcptype');
  8776. line += ' ';
  8777. }
  8778. line += 'generation';
  8779. line += ' ';
  8780. line += cand.getAttribute('generation') || '0';
  8781. return line + '\r\n';
  8782. }
  8783. };
  8784. module.exports = SDPUtil;
  8785. }).call(this,"/modules/xmpp/SDPUtil.js")
  8786. },{"../RTC/RTCBrowserType":17,"jitsi-meet-logger":48}],33:[function(require,module,exports){
  8787. (function (__filename){
  8788. /* global $ */
  8789. var RTC = require('../RTC/RTC');
  8790. var logger = require("jitsi-meet-logger").getLogger(__filename);
  8791. var RTCBrowserType = require("../RTC/RTCBrowserType.js");
  8792. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  8793. var SSRCReplacement = require("./LocalSSRCReplacement");
  8794. function TraceablePeerConnection(ice_config, constraints, session) {
  8795. var self = this;
  8796. this.session = session;
  8797. var RTCPeerConnectionType = null;
  8798. if (RTCBrowserType.isFirefox()) {
  8799. RTCPeerConnectionType = mozRTCPeerConnection;
  8800. } else if (RTCBrowserType.isTemasysPluginUsed()) {
  8801. RTCPeerConnectionType = RTCPeerConnection;
  8802. } else {
  8803. RTCPeerConnectionType = webkitRTCPeerConnection;
  8804. }
  8805. this.peerconnection = new RTCPeerConnectionType(ice_config, constraints);
  8806. this.updateLog = [];
  8807. this.stats = {};
  8808. this.statsinterval = null;
  8809. this.maxstats = 0; // limit to 300 values, i.e. 5 minutes; set to 0 to disable
  8810. var Interop = require('sdp-interop').Interop;
  8811. this.interop = new Interop();
  8812. var Simulcast = require('sdp-simulcast');
  8813. this.simulcast = new Simulcast({numOfLayers: 2, explodeRemoteSimulcast: false});
  8814. // override as desired
  8815. this.trace = function (what, info) {
  8816. /*logger.warn('WTRACE', what, info);
  8817. if (info && RTCBrowserType.isIExplorer()) {
  8818. if (info.length > 1024) {
  8819. logger.warn('WTRACE', what, info.substr(1024));
  8820. }
  8821. if (info.length > 2048) {
  8822. logger.warn('WTRACE', what, info.substr(2048));
  8823. }
  8824. }*/
  8825. self.updateLog.push({
  8826. time: new Date(),
  8827. type: what,
  8828. value: info || ""
  8829. });
  8830. };
  8831. this.onicecandidate = null;
  8832. this.peerconnection.onicecandidate = function (event) {
  8833. // FIXME: this causes stack overflow with Temasys Plugin
  8834. if (!RTCBrowserType.isTemasysPluginUsed())
  8835. self.trace('onicecandidate', JSON.stringify(event.candidate, null, ' '));
  8836. if (self.onicecandidate !== null) {
  8837. self.onicecandidate(event);
  8838. }
  8839. };
  8840. this.onaddstream = null;
  8841. this.peerconnection.onaddstream = function (event) {
  8842. self.trace('onaddstream', event.stream.id);
  8843. if (self.onaddstream !== null) {
  8844. self.onaddstream(event);
  8845. }
  8846. };
  8847. this.onremovestream = null;
  8848. this.peerconnection.onremovestream = function (event) {
  8849. self.trace('onremovestream', event.stream.id);
  8850. if (self.onremovestream !== null) {
  8851. self.onremovestream(event);
  8852. }
  8853. };
  8854. this.onsignalingstatechange = null;
  8855. this.peerconnection.onsignalingstatechange = function (event) {
  8856. self.trace('onsignalingstatechange', self.signalingState);
  8857. if (self.onsignalingstatechange !== null) {
  8858. self.onsignalingstatechange(event);
  8859. }
  8860. };
  8861. this.oniceconnectionstatechange = null;
  8862. this.peerconnection.oniceconnectionstatechange = function (event) {
  8863. self.trace('oniceconnectionstatechange', self.iceConnectionState);
  8864. if (self.oniceconnectionstatechange !== null) {
  8865. self.oniceconnectionstatechange(event);
  8866. }
  8867. };
  8868. this.onnegotiationneeded = null;
  8869. this.peerconnection.onnegotiationneeded = function (event) {
  8870. self.trace('onnegotiationneeded');
  8871. if (self.onnegotiationneeded !== null) {
  8872. self.onnegotiationneeded(event);
  8873. }
  8874. };
  8875. self.ondatachannel = null;
  8876. this.peerconnection.ondatachannel = function (event) {
  8877. self.trace('ondatachannel', event);
  8878. if (self.ondatachannel !== null) {
  8879. self.ondatachannel(event);
  8880. }
  8881. };
  8882. // XXX: do all non-firefox browsers which we support also support this?
  8883. if (!RTCBrowserType.isFirefox() && this.maxstats) {
  8884. this.statsinterval = window.setInterval(function() {
  8885. self.peerconnection.getStats(function(stats) {
  8886. var results = stats.result();
  8887. var now = new Date();
  8888. for (var i = 0; i < results.length; ++i) {
  8889. results[i].names().forEach(function (name) {
  8890. var id = results[i].id + '-' + name;
  8891. if (!self.stats[id]) {
  8892. self.stats[id] = {
  8893. startTime: now,
  8894. endTime: now,
  8895. values: [],
  8896. times: []
  8897. };
  8898. }
  8899. self.stats[id].values.push(results[i].stat(name));
  8900. self.stats[id].times.push(now.getTime());
  8901. if (self.stats[id].values.length > self.maxstats) {
  8902. self.stats[id].values.shift();
  8903. self.stats[id].times.shift();
  8904. }
  8905. self.stats[id].endTime = now;
  8906. });
  8907. }
  8908. });
  8909. }, 1000);
  8910. }
  8911. }
  8912. /**
  8913. * Returns a string representation of a SessionDescription object.
  8914. */
  8915. var dumpSDP = function(description) {
  8916. if (typeof description === 'undefined' || description == null) {
  8917. return '';
  8918. }
  8919. return 'type: ' + description.type + '\r\n' + description.sdp;
  8920. };
  8921. /**
  8922. * Takes a SessionDescription object and returns a "normalized" version.
  8923. * Currently it only takes care of ordering the a=ssrc lines.
  8924. */
  8925. var normalizePlanB = function(desc) {
  8926. if (typeof desc !== 'object' || desc === null ||
  8927. typeof desc.sdp !== 'string') {
  8928. logger.warn('An empty description was passed as an argument.');
  8929. return desc;
  8930. }
  8931. var transform = require('sdp-transform');
  8932. var session = transform.parse(desc.sdp);
  8933. if (typeof session !== 'undefined' && typeof session.media !== 'undefined' &&
  8934. Array.isArray(session.media)) {
  8935. session.media.forEach(function (mLine) {
  8936. // Chrome appears to be picky about the order in which a=ssrc lines
  8937. // are listed in an m-line when rtx is enabled (and thus there are
  8938. // a=ssrc-group lines with FID semantics). Specifically if we have
  8939. // "a=ssrc-group:FID S1 S2" and the "a=ssrc:S2" lines appear before
  8940. // the "a=ssrc:S1" lines, SRD fails.
  8941. // So, put SSRC which appear as the first SSRC in an FID ssrc-group
  8942. // first.
  8943. var firstSsrcs = [];
  8944. var newSsrcLines = [];
  8945. if (typeof mLine.ssrcGroups !== 'undefined' && Array.isArray(mLine.ssrcGroups)) {
  8946. mLine.ssrcGroups.forEach(function (group) {
  8947. if (typeof group.semantics !== 'undefined' &&
  8948. group.semantics === 'FID') {
  8949. if (typeof group.ssrcs !== 'undefined') {
  8950. firstSsrcs.push(Number(group.ssrcs.split(' ')[0]));
  8951. }
  8952. }
  8953. });
  8954. }
  8955. if (typeof mLine.ssrcs !== 'undefined' && Array.isArray(mLine.ssrcs)) {
  8956. var i;
  8957. for (i = 0; i<mLine.ssrcs.length; i++){
  8958. if (typeof mLine.ssrcs[i] === 'object'
  8959. && typeof mLine.ssrcs[i].id !== 'undefined'
  8960. && !$.inArray(mLine.ssrcs[i].id, firstSsrcs)) {
  8961. newSsrcLines.push(mLine.ssrcs[i]);
  8962. delete mLine.ssrcs[i];
  8963. }
  8964. }
  8965. for (i = 0; i<mLine.ssrcs.length; i++){
  8966. if (typeof mLine.ssrcs[i] !== 'undefined') {
  8967. newSsrcLines.push(mLine.ssrcs[i]);
  8968. }
  8969. }
  8970. mLine.ssrcs = newSsrcLines;
  8971. }
  8972. });
  8973. }
  8974. var resStr = transform.write(session);
  8975. return new RTCSessionDescription({
  8976. type: desc.type,
  8977. sdp: resStr
  8978. });
  8979. };
  8980. var getters = {
  8981. signalingState: function () {
  8982. return this.peerconnection.signalingState;
  8983. },
  8984. iceConnectionState: function () {
  8985. return this.peerconnection.iceConnectionState;
  8986. },
  8987. localDescription: function() {
  8988. var desc = this.peerconnection.localDescription;
  8989. // FIXME this should probably be after the Unified Plan -> Plan B
  8990. // transformation.
  8991. desc = SSRCReplacement.mungeLocalVideoSSRC(desc);
  8992. this.trace('getLocalDescription::preTransform', dumpSDP(desc));
  8993. // if we're running on FF, transform to Plan B first.
  8994. if (RTCBrowserType.usesUnifiedPlan()) {
  8995. desc = this.interop.toPlanB(desc);
  8996. this.trace('getLocalDescription::postTransform (Plan B)', dumpSDP(desc));
  8997. }
  8998. return desc;
  8999. },
  9000. remoteDescription: function() {
  9001. var desc = this.peerconnection.remoteDescription;
  9002. this.trace('getRemoteDescription::preTransform', dumpSDP(desc));
  9003. // if we're running on FF, transform to Plan B first.
  9004. if (RTCBrowserType.usesUnifiedPlan()) {
  9005. desc = this.interop.toPlanB(desc);
  9006. this.trace('getRemoteDescription::postTransform (Plan B)', dumpSDP(desc));
  9007. }
  9008. return desc;
  9009. }
  9010. };
  9011. Object.keys(getters).forEach(function (prop) {
  9012. Object.defineProperty(
  9013. TraceablePeerConnection.prototype,
  9014. prop, {
  9015. get: getters[prop]
  9016. }
  9017. );
  9018. });
  9019. TraceablePeerConnection.prototype.addStream = function (stream) {
  9020. this.trace('addStream', stream.id);
  9021. try
  9022. {
  9023. this.peerconnection.addStream(stream);
  9024. }
  9025. catch (e)
  9026. {
  9027. logger.error(e);
  9028. }
  9029. };
  9030. TraceablePeerConnection.prototype.removeStream = function (stream, stopStreams) {
  9031. this.trace('removeStream', stream.id);
  9032. if(stopStreams) {
  9033. RTC.stopMediaStream(stream);
  9034. }
  9035. try {
  9036. // FF doesn't support this yet.
  9037. if (this.peerconnection.removeStream)
  9038. this.peerconnection.removeStream(stream);
  9039. } catch (e) {
  9040. logger.error(e);
  9041. }
  9042. };
  9043. TraceablePeerConnection.prototype.createDataChannel = function (label, opts) {
  9044. this.trace('createDataChannel', label, opts);
  9045. return this.peerconnection.createDataChannel(label, opts);
  9046. };
  9047. TraceablePeerConnection.prototype.setLocalDescription
  9048. = function (description, successCallback, failureCallback) {
  9049. this.trace('setLocalDescription::preTransform', dumpSDP(description));
  9050. // if we're running on FF, transform to Plan A first.
  9051. if (RTCBrowserType.usesUnifiedPlan()) {
  9052. description = this.interop.toUnifiedPlan(description);
  9053. this.trace('setLocalDescription::postTransform (Plan A)', dumpSDP(description));
  9054. }
  9055. var self = this;
  9056. this.peerconnection.setLocalDescription(description,
  9057. function () {
  9058. self.trace('setLocalDescriptionOnSuccess');
  9059. successCallback();
  9060. },
  9061. function (err) {
  9062. self.trace('setLocalDescriptionOnFailure', err);
  9063. failureCallback(err);
  9064. }
  9065. );
  9066. /*
  9067. if (this.statsinterval === null && this.maxstats > 0) {
  9068. // start gathering stats
  9069. }
  9070. */
  9071. };
  9072. TraceablePeerConnection.prototype.setRemoteDescription
  9073. = function (description, successCallback, failureCallback) {
  9074. this.trace('setRemoteDescription::preTransform', dumpSDP(description));
  9075. // TODO the focus should squeze or explode the remote simulcast
  9076. description = this.simulcast.mungeRemoteDescription(description);
  9077. this.trace('setRemoteDescription::postTransform (simulcast)', dumpSDP(description));
  9078. // if we're running on FF, transform to Plan A first.
  9079. if (RTCBrowserType.usesUnifiedPlan()) {
  9080. description = this.interop.toUnifiedPlan(description);
  9081. this.trace('setRemoteDescription::postTransform (Plan A)', dumpSDP(description));
  9082. }
  9083. if (RTCBrowserType.usesPlanB()) {
  9084. description = normalizePlanB(description);
  9085. }
  9086. var self = this;
  9087. this.peerconnection.setRemoteDescription(description,
  9088. function () {
  9089. self.trace('setRemoteDescriptionOnSuccess');
  9090. successCallback();
  9091. },
  9092. function (err) {
  9093. self.trace('setRemoteDescriptionOnFailure', err);
  9094. failureCallback(err);
  9095. }
  9096. );
  9097. /*
  9098. if (this.statsinterval === null && this.maxstats > 0) {
  9099. // start gathering stats
  9100. }
  9101. */
  9102. };
  9103. TraceablePeerConnection.prototype.close = function () {
  9104. this.trace('stop');
  9105. if (this.statsinterval !== null) {
  9106. window.clearInterval(this.statsinterval);
  9107. this.statsinterval = null;
  9108. }
  9109. this.peerconnection.close();
  9110. };
  9111. TraceablePeerConnection.prototype.createOffer
  9112. = function (successCallback, failureCallback, constraints) {
  9113. var self = this;
  9114. this.trace('createOffer', JSON.stringify(constraints, null, ' '));
  9115. this.peerconnection.createOffer(
  9116. function (offer) {
  9117. self.trace('createOfferOnSuccess::preTransform', dumpSDP(offer));
  9118. // NOTE this is not tested because in meet the focus generates the
  9119. // offer.
  9120. // if we're running on FF, transform to Plan B first.
  9121. if (RTCBrowserType.usesUnifiedPlan()) {
  9122. offer = self.interop.toPlanB(offer);
  9123. self.trace('createOfferOnSuccess::postTransform (Plan B)', dumpSDP(offer));
  9124. }
  9125. offer = SSRCReplacement.mungeLocalVideoSSRC(offer);
  9126. if (self.session.room.options.enableSimulcast && self.simulcast.isSupported()) {
  9127. offer = self.simulcast.mungeLocalDescription(offer);
  9128. self.trace('createOfferOnSuccess::postTransform (simulcast)', dumpSDP(offer));
  9129. }
  9130. successCallback(offer);
  9131. },
  9132. function(err) {
  9133. self.trace('createOfferOnFailure', err);
  9134. failureCallback(err);
  9135. },
  9136. constraints
  9137. );
  9138. };
  9139. TraceablePeerConnection.prototype.createAnswer
  9140. = function (successCallback, failureCallback, constraints) {
  9141. var self = this;
  9142. this.trace('createAnswer', JSON.stringify(constraints, null, ' '));
  9143. this.peerconnection.createAnswer(
  9144. function (answer) {
  9145. self.trace('createAnswerOnSuccess::preTransform', dumpSDP(answer));
  9146. // if we're running on FF, transform to Plan A first.
  9147. if (RTCBrowserType.usesUnifiedPlan()) {
  9148. answer = self.interop.toPlanB(answer);
  9149. self.trace('createAnswerOnSuccess::postTransform (Plan B)', dumpSDP(answer));
  9150. }
  9151. // munge local video SSRC
  9152. answer = SSRCReplacement.mungeLocalVideoSSRC(answer);
  9153. if (self.session.room.options.enableSimulcast && self.simulcast.isSupported()) {
  9154. answer = self.simulcast.mungeLocalDescription(answer);
  9155. self.trace('createAnswerOnSuccess::postTransform (simulcast)', dumpSDP(answer));
  9156. }
  9157. successCallback(answer);
  9158. },
  9159. function(err) {
  9160. self.trace('createAnswerOnFailure', err);
  9161. failureCallback(err);
  9162. },
  9163. constraints
  9164. );
  9165. };
  9166. TraceablePeerConnection.prototype.addIceCandidate
  9167. = function (candidate, successCallback, failureCallback) {
  9168. //var self = this;
  9169. this.trace('addIceCandidate', JSON.stringify(candidate, null, ' '));
  9170. this.peerconnection.addIceCandidate(candidate);
  9171. /* maybe later
  9172. this.peerconnection.addIceCandidate(candidate,
  9173. function () {
  9174. self.trace('addIceCandidateOnSuccess');
  9175. successCallback();
  9176. },
  9177. function (err) {
  9178. self.trace('addIceCandidateOnFailure', err);
  9179. failureCallback(err);
  9180. }
  9181. );
  9182. */
  9183. };
  9184. TraceablePeerConnection.prototype.getStats = function(callback, errback) {
  9185. // TODO: Is this the correct way to handle Opera, Temasys?
  9186. if (RTCBrowserType.isFirefox()) {
  9187. // ignore for now...
  9188. if(!errback)
  9189. errback = function () {};
  9190. this.peerconnection.getStats(null, callback, errback);
  9191. } else {
  9192. this.peerconnection.getStats(callback);
  9193. }
  9194. };
  9195. module.exports = TraceablePeerConnection;
  9196. }).call(this,"/modules/xmpp/TraceablePeerConnection.js")
  9197. },{"../../service/xmpp/XMPPEvents":91,"../RTC/RTC":16,"../RTC/RTCBrowserType.js":17,"./LocalSSRCReplacement":29,"jitsi-meet-logger":48,"sdp-interop":66,"sdp-simulcast":73,"sdp-transform":80}],34:[function(require,module,exports){
  9198. (function (__filename){
  9199. /* global $, $iq, APP, config, messageHandler,
  9200. roomName, sessionTerminated, Strophe, Util */
  9201. var logger = require("jitsi-meet-logger").getLogger(__filename);
  9202. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  9203. var Settings = require("../settings/Settings");
  9204. var AuthenticationEvents
  9205. = require("../../service/authentication/AuthenticationEvents");
  9206. function createExpBackoffTimer(step) {
  9207. var count = 1;
  9208. return function (reset) {
  9209. // Reset call
  9210. if (reset) {
  9211. count = 1;
  9212. return;
  9213. }
  9214. // Calculate next timeout
  9215. var timeout = Math.pow(2, count - 1);
  9216. count += 1;
  9217. return timeout * step;
  9218. };
  9219. }
  9220. function Moderator(roomName, xmpp, emitter) {
  9221. this.roomName = roomName;
  9222. this.xmppService = xmpp;
  9223. this.getNextTimeout = createExpBackoffTimer(1000);
  9224. this.getNextErrorTimeout = createExpBackoffTimer(1000);
  9225. // External authentication stuff
  9226. this.externalAuthEnabled = false;
  9227. this.settings = new Settings(roomName);
  9228. // Sip gateway can be enabled by configuring Jigasi host in config.js or
  9229. // it will be enabled automatically if focus detects the component through
  9230. // service discovery.
  9231. this.sipGatewayEnabled =
  9232. this.xmppService.options.hosts.call_control !== undefined;
  9233. this.eventEmitter = emitter;
  9234. this.connection = this.xmppService.connection;
  9235. this.focusUserJid;
  9236. //FIXME:
  9237. // Message listener that talks to POPUP window
  9238. function listener(event) {
  9239. if (event.data && event.data.sessionId) {
  9240. if (event.origin !== window.location.origin) {
  9241. logger.warn("Ignoring sessionId from different origin: " +
  9242. event.origin);
  9243. return;
  9244. }
  9245. localStorage.setItem('sessionId', event.data.sessionId);
  9246. // After popup is closed we will authenticate
  9247. }
  9248. }
  9249. // Register
  9250. if (window.addEventListener) {
  9251. window.addEventListener("message", listener, false);
  9252. } else {
  9253. window.attachEvent("onmessage", listener);
  9254. }
  9255. }
  9256. Moderator.prototype.isExternalAuthEnabled = function () {
  9257. return this.externalAuthEnabled;
  9258. };
  9259. Moderator.prototype.isSipGatewayEnabled = function () {
  9260. return this.sipGatewayEnabled;
  9261. };
  9262. Moderator.prototype.onMucMemberLeft = function (jid) {
  9263. logger.info("Someone left is it focus ? " + jid);
  9264. var resource = Strophe.getResourceFromJid(jid);
  9265. if (resource === 'focus' && !this.xmppService.sessionTerminated) {
  9266. logger.info(
  9267. "Focus has left the room - leaving conference");
  9268. //hangUp();
  9269. // We'd rather reload to have everything re-initialized
  9270. //FIXME: show some message before reload
  9271. this.eventEmitter.emit(XMPPEvents.FOCUS_LEFT);
  9272. }
  9273. };
  9274. Moderator.prototype.setFocusUserJid = function (focusJid) {
  9275. if (!this.focusUserJid) {
  9276. this.focusUserJid = focusJid;
  9277. logger.info("Focus jid set to: " + this.focusUserJid);
  9278. }
  9279. };
  9280. Moderator.prototype.getFocusUserJid = function () {
  9281. return this.focusUserJid;
  9282. };
  9283. Moderator.prototype.getFocusComponent = function () {
  9284. // Get focus component address
  9285. var focusComponent = this.xmppService.options.hosts.focus;
  9286. // If not specified use default: 'focus.domain'
  9287. if (!focusComponent) {
  9288. focusComponent = 'focus.' + this.xmppService.options.hosts.domain;
  9289. }
  9290. return focusComponent;
  9291. };
  9292. Moderator.prototype.createConferenceIq = function () {
  9293. // Generate create conference IQ
  9294. var elem = $iq({to: this.getFocusComponent(), type: 'set'});
  9295. // Session Id used for authentication
  9296. var sessionId = localStorage.getItem('sessionId');
  9297. var machineUID = this.settings.getSettings().uid;
  9298. logger.info(
  9299. "Session ID: " + sessionId + " machine UID: " + machineUID);
  9300. elem.c('conference', {
  9301. xmlns: 'http://jitsi.org/protocol/focus',
  9302. room: this.roomName,
  9303. 'machine-uid': machineUID
  9304. });
  9305. if (sessionId) {
  9306. elem.attrs({ 'session-id': sessionId});
  9307. }
  9308. if (this.xmppService.options.hosts.bridge !== undefined) {
  9309. elem.c(
  9310. 'property', {
  9311. name: 'bridge',
  9312. value: this.xmppService.options.hosts.bridge
  9313. }).up();
  9314. }
  9315. if (this.xmppService.options.enforcedBridge !== undefined) {
  9316. elem.c(
  9317. 'property', {
  9318. name: 'enforcedBridge',
  9319. value: this.xmppService.options.enforcedBridge
  9320. }).up();
  9321. }
  9322. // Tell the focus we have Jigasi configured
  9323. if (this.xmppService.options.hosts.call_control !== undefined) {
  9324. elem.c(
  9325. 'property', {
  9326. name: 'call_control',
  9327. value: this.xmppService.options.hosts.call_control
  9328. }).up();
  9329. }
  9330. if (this.xmppService.options.channelLastN !== undefined) {
  9331. elem.c(
  9332. 'property', {
  9333. name: 'channelLastN',
  9334. value: this.xmppService.options.channelLastN
  9335. }).up();
  9336. }
  9337. if (this.xmppService.options.adaptiveLastN !== undefined) {
  9338. elem.c(
  9339. 'property', {
  9340. name: 'adaptiveLastN',
  9341. value: this.xmppService.options.adaptiveLastN
  9342. }).up();
  9343. }
  9344. if (this.xmppService.options.adaptiveSimulcast !== undefined) {
  9345. elem.c(
  9346. 'property', {
  9347. name: 'adaptiveSimulcast',
  9348. value: this.xmppService.options.adaptiveSimulcast
  9349. }).up();
  9350. }
  9351. if (this.xmppService.options.openSctp !== undefined) {
  9352. elem.c(
  9353. 'property', {
  9354. name: 'openSctp',
  9355. value: this.xmppService.options.openSctp
  9356. }).up();
  9357. }
  9358. if (this.xmppService.options.startAudioMuted !== undefined)
  9359. {
  9360. elem.c(
  9361. 'property', {
  9362. name: 'startAudioMuted',
  9363. value: this.xmppService.options.startAudioMuted
  9364. }).up();
  9365. }
  9366. if (this.xmppService.options.startVideoMuted !== undefined)
  9367. {
  9368. elem.c(
  9369. 'property', {
  9370. name: 'startVideoMuted',
  9371. value: this.xmppService.options.startVideoMuted
  9372. }).up();
  9373. }
  9374. elem.c(
  9375. 'property', {
  9376. name: 'simulcastMode',
  9377. value: 'rewriting'
  9378. }).up();
  9379. elem.up();
  9380. return elem;
  9381. };
  9382. Moderator.prototype.parseSessionId = function (resultIq) {
  9383. var sessionId = $(resultIq).find('conference').attr('session-id');
  9384. if (sessionId) {
  9385. logger.info('Received sessionId: ' + sessionId);
  9386. localStorage.setItem('sessionId', sessionId);
  9387. }
  9388. };
  9389. Moderator.prototype.parseConfigOptions = function (resultIq) {
  9390. this.setFocusUserJid(
  9391. $(resultIq).find('conference').attr('focusjid'));
  9392. var authenticationEnabled
  9393. = $(resultIq).find(
  9394. '>conference>property' +
  9395. '[name=\'authentication\'][value=\'true\']').length > 0;
  9396. logger.info("Authentication enabled: " + authenticationEnabled);
  9397. this.externalAuthEnabled = $(resultIq).find(
  9398. '>conference>property' +
  9399. '[name=\'externalAuth\'][value=\'true\']').length > 0;
  9400. console.info(
  9401. 'External authentication enabled: ' + this.externalAuthEnabled);
  9402. if (!this.externalAuthEnabled) {
  9403. // We expect to receive sessionId in 'internal' authentication mode
  9404. this.parseSessionId(resultIq);
  9405. }
  9406. var authIdentity = $(resultIq).find('>conference').attr('identity');
  9407. this.eventEmitter.emit(AuthenticationEvents.IDENTITY_UPDATED,
  9408. authenticationEnabled, authIdentity);
  9409. // Check if focus has auto-detected Jigasi component(this will be also
  9410. // included if we have passed our host from the config)
  9411. if ($(resultIq).find(
  9412. '>conference>property' +
  9413. '[name=\'sipGatewayEnabled\'][value=\'true\']').length) {
  9414. this.sipGatewayEnabled = true;
  9415. }
  9416. logger.info("Sip gateway enabled: " + this.sipGatewayEnabled);
  9417. };
  9418. // FIXME = we need to show the fact that we're waiting for the focus
  9419. // to the user(or that focus is not available)
  9420. Moderator.prototype.allocateConferenceFocus = function (callback) {
  9421. // Try to use focus user JID from the config
  9422. this.setFocusUserJid(this.xmppService.options.focusUserJid);
  9423. // Send create conference IQ
  9424. var iq = this.createConferenceIq();
  9425. var self = this;
  9426. this.connection.sendIQ(
  9427. iq,
  9428. function (result) {
  9429. // Setup config options
  9430. self.parseConfigOptions(result);
  9431. if ('true' === $(result).find('conference').attr('ready')) {
  9432. // Reset both timers
  9433. self.getNextTimeout(true);
  9434. self.getNextErrorTimeout(true);
  9435. // Exec callback
  9436. callback();
  9437. } else {
  9438. var waitMs = self.getNextTimeout();
  9439. logger.info("Waiting for the focus... " + waitMs);
  9440. // Reset error timeout
  9441. self.getNextErrorTimeout(true);
  9442. window.setTimeout(
  9443. function () {
  9444. self.allocateConferenceFocus(callback);
  9445. }, waitMs);
  9446. }
  9447. },
  9448. function (error) {
  9449. // Invalid session ? remove and try again
  9450. // without session ID to get a new one
  9451. var invalidSession
  9452. = $(error).find('>error>session-invalid').length;
  9453. if (invalidSession) {
  9454. logger.info("Session expired! - removing");
  9455. localStorage.removeItem("sessionId");
  9456. }
  9457. if ($(error).find('>error>graceful-shutdown').length) {
  9458. self.eventEmitter.emit(XMPPEvents.GRACEFUL_SHUTDOWN);
  9459. return;
  9460. }
  9461. // Check for error returned by the reservation system
  9462. var reservationErr = $(error).find('>error>reservation-error');
  9463. if (reservationErr.length) {
  9464. // Trigger error event
  9465. var errorCode = reservationErr.attr('error-code');
  9466. var errorMsg;
  9467. if ($(error).find('>error>text')) {
  9468. errorMsg = $(error).find('>error>text').text();
  9469. }
  9470. self.eventEmitter.emit(
  9471. XMPPEvents.RESERVATION_ERROR, errorCode, errorMsg);
  9472. return;
  9473. }
  9474. // Not authorized to create new room
  9475. if ($(error).find('>error>not-authorized').length) {
  9476. logger.warn("Unauthorized to start the conference", error);
  9477. var toDomain
  9478. = Strophe.getDomainFromJid(error.getAttribute('to'));
  9479. if (toDomain !==
  9480. this.xmppService.options.hosts.anonymousdomain) {
  9481. //FIXME: "is external" should come either from
  9482. // the focus or config.js
  9483. self.externalAuthEnabled = true;
  9484. }
  9485. self.eventEmitter.emit(
  9486. XMPPEvents.AUTHENTICATION_REQUIRED,
  9487. function () {
  9488. self.allocateConferenceFocus(
  9489. callback);
  9490. });
  9491. return;
  9492. }
  9493. var waitMs = self.getNextErrorTimeout();
  9494. logger.error("Focus error, retry after " + waitMs, error);
  9495. // Show message
  9496. var focusComponent = self.getFocusComponent();
  9497. var retrySec = waitMs / 1000;
  9498. //FIXME: message is duplicated ?
  9499. // Do not show in case of session invalid
  9500. // which means just a retry
  9501. if (!invalidSession) {
  9502. self.eventEmitter.emit(XMPPEvents.FOCUS_DISCONNECTED,
  9503. focusComponent, retrySec);
  9504. }
  9505. // Reset response timeout
  9506. self.getNextTimeout(true);
  9507. window.setTimeout(
  9508. function () {
  9509. self.allocateConferenceFocus(callback);
  9510. }, waitMs);
  9511. }
  9512. );
  9513. };
  9514. Moderator.prototype.getLoginUrl = function (urlCallback) {
  9515. var iq = $iq({to: this.getFocusComponent(), type: 'get'});
  9516. iq.c('login-url', {
  9517. xmlns: 'http://jitsi.org/protocol/focus',
  9518. room: this.roomName,
  9519. 'machine-uid': this.settings.getSettings().uid
  9520. });
  9521. this.connection.sendIQ(
  9522. iq,
  9523. function (result) {
  9524. var url = $(result).find('login-url').attr('url');
  9525. url = url = decodeURIComponent(url);
  9526. if (url) {
  9527. logger.info("Got auth url: " + url);
  9528. urlCallback(url);
  9529. } else {
  9530. logger.error(
  9531. "Failed to get auth url from the focus", result);
  9532. }
  9533. },
  9534. function (error) {
  9535. logger.error("Get auth url error", error);
  9536. }
  9537. );
  9538. };
  9539. Moderator.prototype.getPopupLoginUrl = function (urlCallback) {
  9540. var iq = $iq({to: this.getFocusComponent(), type: 'get'});
  9541. iq.c('login-url', {
  9542. xmlns: 'http://jitsi.org/protocol/focus',
  9543. room: this.roomName,
  9544. 'machine-uid': this.settings.getSettings().uid,
  9545. popup: true
  9546. });
  9547. this.connection.sendIQ(
  9548. iq,
  9549. function (result) {
  9550. var url = $(result).find('login-url').attr('url');
  9551. url = url = decodeURIComponent(url);
  9552. if (url) {
  9553. logger.info("Got POPUP auth url: " + url);
  9554. urlCallback(url);
  9555. } else {
  9556. logger.error(
  9557. "Failed to get POPUP auth url from the focus", result);
  9558. }
  9559. },
  9560. function (error) {
  9561. logger.error('Get POPUP auth url error', error);
  9562. }
  9563. );
  9564. };
  9565. Moderator.prototype.logout = function (callback) {
  9566. var iq = $iq({to: this.getFocusComponent(), type: 'set'});
  9567. var sessionId = localStorage.getItem('sessionId');
  9568. if (!sessionId) {
  9569. callback();
  9570. return;
  9571. }
  9572. iq.c('logout', {
  9573. xmlns: 'http://jitsi.org/protocol/focus',
  9574. 'session-id': sessionId
  9575. });
  9576. this.connection.sendIQ(
  9577. iq,
  9578. function (result) {
  9579. var logoutUrl = $(result).find('logout').attr('logout-url');
  9580. if (logoutUrl) {
  9581. logoutUrl = decodeURIComponent(logoutUrl);
  9582. }
  9583. logger.info("Log out OK, url: " + logoutUrl, result);
  9584. localStorage.removeItem('sessionId');
  9585. callback(logoutUrl);
  9586. },
  9587. function (error) {
  9588. logger.error("Logout error", error);
  9589. }
  9590. );
  9591. };
  9592. module.exports = Moderator;
  9593. }).call(this,"/modules/xmpp/moderator.js")
  9594. },{"../../service/authentication/AuthenticationEvents":87,"../../service/xmpp/XMPPEvents":91,"../settings/Settings":21,"jitsi-meet-logger":48}],35:[function(require,module,exports){
  9595. (function (__filename){
  9596. /* global $, $iq, config, connection, focusMucJid, messageHandler,
  9597. Toolbar, Util, Promise */
  9598. var XMPPEvents = require("../../service/XMPP/XMPPEvents");
  9599. var logger = require("jitsi-meet-logger").getLogger(__filename);
  9600. function Recording(ee, connection, focusMucJid) {
  9601. this.eventEmitter = ee;
  9602. this.connection = connection;
  9603. this.state = "off";
  9604. this.focusMucJid = focusMucJid;
  9605. this.url = null;
  9606. this._isSupported = false;
  9607. }
  9608. Recording.prototype.handleJibriPresence = function (jibri) {
  9609. var attributes = jibri.attributes;
  9610. if(!attributes)
  9611. return;
  9612. this._isSupported =
  9613. (attributes.status && attributes.status !== "undefined");
  9614. if(this._isSupported) {
  9615. this.url = attributes.url || null;
  9616. this.state = attributes.status || "off";
  9617. }
  9618. this.eventEmitter.emit(XMPPEvents.RECORDING_STATE_CHANGED);
  9619. };
  9620. Recording.prototype.setRecording = function (state, streamId, followEntity,
  9621. callback, errCallback){
  9622. if (state == this.state){
  9623. return;
  9624. }
  9625. // FIXME jibri does not accept IQ without 'url' attribute set ?
  9626. var iq = $iq({to: this.focusMucJid, type: 'set'})
  9627. .c('jibri', {
  9628. "xmlns": 'http://jitsi.org/protocol/jibri',
  9629. "action": (state === 'on') ? 'start' : 'stop',
  9630. "streamid": streamId,
  9631. "follow-entity": followEntity
  9632. }).up();
  9633. logger.log('Set jibri recording: '+state, iq.nodeTree);
  9634. console.log(iq.nodeTree);
  9635. this.connection.sendIQ(
  9636. iq,
  9637. function (result) {
  9638. callback($(result).find('jibri').attr('state'),
  9639. $(result).find('jibri').attr('url'));
  9640. },
  9641. function (error) {
  9642. logger.log('Failed to start recording, error: ', error);
  9643. errCallback(error);
  9644. });
  9645. };
  9646. Recording.prototype.toggleRecording = function (token, followEntity) {
  9647. var self = this;
  9648. return new Promise(function(resolve, reject) {
  9649. if (!token) {
  9650. reject(new Error("No token passed!"));
  9651. logger.error("No token passed!");
  9652. return;
  9653. }
  9654. if(self.state === "on") {
  9655. reject(new Error("Recording is already started!"));
  9656. logger.error("Recording is already started!");
  9657. return;
  9658. }
  9659. var oldState = self.state;
  9660. var newState = (oldState === 'off' || !oldState) ? 'on' : 'off';
  9661. self.setRecording(newState,
  9662. token, followEntity,
  9663. function (state, url) {
  9664. logger.log("New recording state: ", state);
  9665. if (state && state !== oldState) {
  9666. self.state = state;
  9667. self.url = url;
  9668. resolve();
  9669. } else {
  9670. reject(new Error("State not changed!"));
  9671. }
  9672. },
  9673. function (error) {
  9674. reject(error);
  9675. }
  9676. );
  9677. });
  9678. };
  9679. /**
  9680. * Returns true if the recording is supproted and false if not.
  9681. */
  9682. Recording.prototype.isSupported = function () {
  9683. return this._isSupported;
  9684. };
  9685. /**
  9686. * Returns null if the recording is not supported, "on" if the recording started
  9687. * and "off" if the recording is not started.
  9688. */
  9689. Recording.prototype.getState = function () {
  9690. return this.state;
  9691. };
  9692. /**
  9693. * Returns the url of the recorded video.
  9694. */
  9695. Recording.prototype.getURL = function () {
  9696. return this.url;
  9697. };
  9698. module.exports = Recording;
  9699. }).call(this,"/modules/xmpp/recording.js")
  9700. },{"../../service/XMPP/XMPPEvents":86,"jitsi-meet-logger":48}],36:[function(require,module,exports){
  9701. (function (__filename){
  9702. /* jshint -W117 */
  9703. /* a simple MUC connection plugin
  9704. * can only handle a single MUC room
  9705. */
  9706. var logger = require("jitsi-meet-logger").getLogger(__filename);
  9707. var ChatRoom = require("./ChatRoom");
  9708. module.exports = function(XMPP) {
  9709. Strophe.addConnectionPlugin('emuc', {
  9710. connection: null,
  9711. rooms: {},//map with the rooms
  9712. init: function (conn) {
  9713. this.connection = conn;
  9714. // add handlers (just once)
  9715. this.connection.addHandler(this.onPresence.bind(this), null, 'presence', null, null, null, null);
  9716. this.connection.addHandler(this.onPresenceUnavailable.bind(this), null, 'presence', 'unavailable', null);
  9717. this.connection.addHandler(this.onPresenceError.bind(this), null, 'presence', 'error', null);
  9718. this.connection.addHandler(this.onMessage.bind(this), null, 'message', null, null);
  9719. },
  9720. createRoom: function (jid, password, options) {
  9721. var roomJid = Strophe.getBareJidFromJid(jid);
  9722. if (this.rooms[roomJid]) {
  9723. logger.error("You are already in the room!");
  9724. return;
  9725. }
  9726. this.rooms[roomJid] = new ChatRoom(this.connection, jid, password, XMPP, options);
  9727. return this.rooms[roomJid];
  9728. },
  9729. doLeave: function (jid) {
  9730. this.rooms[jid].doLeave();
  9731. delete this.rooms[jid];
  9732. },
  9733. onPresence: function (pres) {
  9734. var from = pres.getAttribute('from');
  9735. // What is this for? A workaround for something?
  9736. if (pres.getAttribute('type')) {
  9737. return true;
  9738. }
  9739. var room = this.rooms[Strophe.getBareJidFromJid(from)];
  9740. if(!room)
  9741. return;
  9742. // Parse status.
  9743. if ($(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>status[code="201"]').length) {
  9744. room.createNonAnonymousRoom();
  9745. }
  9746. room.onPresence(pres);
  9747. return true;
  9748. },
  9749. onPresenceUnavailable: function (pres) {
  9750. var from = pres.getAttribute('from');
  9751. var room = this.rooms[Strophe.getBareJidFromJid(from)];
  9752. if(!room)
  9753. return;
  9754. room.onPresenceUnavailable(pres, from);
  9755. return true;
  9756. },
  9757. onPresenceError: function (pres) {
  9758. var from = pres.getAttribute('from');
  9759. var room = this.rooms[Strophe.getBareJidFromJid(from)];
  9760. if(!room)
  9761. return;
  9762. room.onPresenceError(pres, from);
  9763. return true;
  9764. },
  9765. onMessage: function (msg) {
  9766. // FIXME: this is a hack. but jingle on muc makes nickchanges hard
  9767. var from = msg.getAttribute('from');
  9768. var room = this.rooms[Strophe.getBareJidFromJid(from)];
  9769. if(!room)
  9770. return;
  9771. room.onMessage(msg, from);
  9772. return true;
  9773. },
  9774. setJingleSession: function (from, session) {
  9775. var room = this.rooms[Strophe.getBareJidFromJid(from)];
  9776. if(!room)
  9777. return;
  9778. room.setJingleSession(session);
  9779. }
  9780. });
  9781. };
  9782. }).call(this,"/modules/xmpp/strophe.emuc.js")
  9783. },{"./ChatRoom":26,"jitsi-meet-logger":48}],37:[function(require,module,exports){
  9784. (function (__filename){
  9785. /* jshint -W117 */
  9786. var logger = require("jitsi-meet-logger").getLogger(__filename);
  9787. var JingleSession = require("./JingleSessionPC");
  9788. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  9789. var RTCBrowserType = require("../RTC/RTCBrowserType");
  9790. module.exports = function(XMPP, eventEmitter) {
  9791. Strophe.addConnectionPlugin('jingle', {
  9792. connection: null,
  9793. sessions: {},
  9794. jid2session: {},
  9795. ice_config: {iceServers: []},
  9796. media_constraints: {
  9797. mandatory: {
  9798. 'OfferToReceiveAudio': true,
  9799. 'OfferToReceiveVideo': true
  9800. }
  9801. // MozDontOfferDataChannel: true when this is firefox
  9802. },
  9803. init: function (conn) {
  9804. this.connection = conn;
  9805. if (this.connection.disco) {
  9806. // http://xmpp.org/extensions/xep-0167.html#support
  9807. // http://xmpp.org/extensions/xep-0176.html#support
  9808. this.connection.disco.addFeature('urn:xmpp:jingle:1');
  9809. this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:1');
  9810. this.connection.disco.addFeature('urn:xmpp:jingle:transports:ice-udp:1');
  9811. this.connection.disco.addFeature('urn:xmpp:jingle:apps:dtls:0');
  9812. this.connection.disco.addFeature('urn:xmpp:jingle:transports:dtls-sctp:1');
  9813. this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:audio');
  9814. this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:video');
  9815. if (RTCBrowserType.isChrome() || RTCBrowserType.isOpera()
  9816. || RTCBrowserType.isTemasysPluginUsed()) {
  9817. this.connection.disco.addFeature('urn:ietf:rfc:4588');
  9818. }
  9819. // this is dealt with by SDP O/A so we don't need to announce this
  9820. //this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:rtcp-fb:0'); // XEP-0293
  9821. //this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:rtp-hdrext:0'); // XEP-0294
  9822. this.connection.disco.addFeature('urn:ietf:rfc:5761'); // rtcp-mux
  9823. this.connection.disco.addFeature('urn:ietf:rfc:5888'); // a=group, e.g. bundle
  9824. //this.connection.disco.addFeature('urn:ietf:rfc:5576'); // a=ssrc
  9825. }
  9826. this.connection.addHandler(this.onJingle.bind(this), 'urn:xmpp:jingle:1', 'iq', 'set', null, null);
  9827. },
  9828. onJingle: function (iq) {
  9829. var sid = $(iq).find('jingle').attr('sid');
  9830. var action = $(iq).find('jingle').attr('action');
  9831. var fromJid = iq.getAttribute('from');
  9832. // send ack first
  9833. var ack = $iq({type: 'result',
  9834. to: fromJid,
  9835. id: iq.getAttribute('id')
  9836. });
  9837. logger.log('on jingle ' + action + ' from ' + fromJid, iq);
  9838. var sess = this.sessions[sid];
  9839. if ('session-initiate' != action) {
  9840. if (sess === null) {
  9841. ack.type = 'error';
  9842. ack.c('error', {type: 'cancel'})
  9843. .c('item-not-found', {xmlns: 'urn:ietf:params:xml:ns:xmpp-stanzas'}).up()
  9844. .c('unknown-session', {xmlns: 'urn:xmpp:jingle:errors:1'});
  9845. this.connection.send(ack);
  9846. return true;
  9847. }
  9848. // local jid is not checked
  9849. if (fromJid != sess.peerjid) {
  9850. logger.warn('jid mismatch for session id', sid, fromJid, sess.peerjid);
  9851. ack.type = 'error';
  9852. ack.c('error', {type: 'cancel'})
  9853. .c('item-not-found', {xmlns: 'urn:ietf:params:xml:ns:xmpp-stanzas'}).up()
  9854. .c('unknown-session', {xmlns: 'urn:xmpp:jingle:errors:1'});
  9855. this.connection.send(ack);
  9856. return true;
  9857. }
  9858. } else if (sess !== undefined) {
  9859. // existing session with same session id
  9860. // this might be out-of-order if the sess.peerjid is the same as from
  9861. ack.type = 'error';
  9862. ack.c('error', {type: 'cancel'})
  9863. .c('service-unavailable', {xmlns: 'urn:ietf:params:xml:ns:xmpp-stanzas'}).up();
  9864. logger.warn('duplicate session id', sid);
  9865. this.connection.send(ack);
  9866. return true;
  9867. }
  9868. // FIXME: check for a defined action
  9869. this.connection.send(ack);
  9870. // see http://xmpp.org/extensions/xep-0166.html#concepts-session
  9871. switch (action) {
  9872. case 'session-initiate':
  9873. console.log("(TIME) received session-initiate:\t",
  9874. window.performance.now());
  9875. var startMuted = $(iq).find('jingle>startmuted');
  9876. if (startMuted && startMuted.length > 0) {
  9877. var audioMuted = startMuted.attr("audio");
  9878. var videoMuted = startMuted.attr("video");
  9879. eventEmitter.emit(XMPPEvents.START_MUTED_FROM_FOCUS,
  9880. audioMuted === "true", videoMuted === "true");
  9881. }
  9882. sess = new JingleSession(
  9883. $(iq).attr('to'), $(iq).find('jingle').attr('sid'),
  9884. this.connection, XMPP);
  9885. // configure session
  9886. var fromBareJid = Strophe.getBareJidFromJid(fromJid);
  9887. this.connection.emuc.setJingleSession(fromBareJid, sess);
  9888. sess.media_constraints = this.media_constraints;
  9889. sess.ice_config = this.ice_config;
  9890. sess.initialize(fromJid, false);
  9891. eventEmitter.emit(XMPPEvents.CALL_INCOMING, sess);
  9892. // FIXME: setRemoteDescription should only be done when this call is to be accepted
  9893. sess.setOffer($(iq).find('>jingle'));
  9894. this.sessions[sess.sid] = sess;
  9895. this.jid2session[sess.peerjid] = sess;
  9896. // the callback should either
  9897. // .sendAnswer and .accept
  9898. // or .sendTerminate -- not necessarily synchronous
  9899. sess.sendAnswer();
  9900. sess.accept();
  9901. break;
  9902. case 'session-accept':
  9903. sess.setAnswer($(iq).find('>jingle'));
  9904. sess.accept();
  9905. break;
  9906. case 'session-terminate':
  9907. // If this is not the focus sending the terminate, we have
  9908. // nothing more to do here.
  9909. if (Object.keys(this.sessions).length < 1
  9910. || !(this.sessions[Object.keys(this.sessions)[0]]
  9911. instanceof JingleSession))
  9912. {
  9913. break;
  9914. }
  9915. logger.log('terminating...', sess.sid);
  9916. sess.terminate();
  9917. this.terminate(sess.sid);
  9918. if ($(iq).find('>jingle>reason').length) {
  9919. $(document).trigger('callterminated.jingle', [
  9920. sess.sid,
  9921. sess.peerjid,
  9922. $(iq).find('>jingle>reason>:first')[0].tagName,
  9923. $(iq).find('>jingle>reason>text').text()
  9924. ]);
  9925. } else {
  9926. $(document).trigger('callterminated.jingle',
  9927. [sess.sid, sess.peerjid]);
  9928. }
  9929. break;
  9930. case 'transport-info':
  9931. sess.addIceCandidate($(iq).find('>jingle>content'));
  9932. break;
  9933. case 'session-info':
  9934. var affected;
  9935. if ($(iq).find('>jingle>ringing[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').length) {
  9936. $(document).trigger('ringing.jingle', [sess.sid]);
  9937. } else if ($(iq).find('>jingle>mute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').length) {
  9938. affected = $(iq).find('>jingle>mute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').attr('name');
  9939. $(document).trigger('mute.jingle', [sess.sid, affected]);
  9940. } else if ($(iq).find('>jingle>unmute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').length) {
  9941. affected = $(iq).find('>jingle>unmute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').attr('name');
  9942. $(document).trigger('unmute.jingle', [sess.sid, affected]);
  9943. }
  9944. break;
  9945. case 'addsource': // FIXME: proprietary, un-jingleish
  9946. case 'source-add': // FIXME: proprietary
  9947. sess.addSource($(iq).find('>jingle>content'));
  9948. break;
  9949. case 'removesource': // FIXME: proprietary, un-jingleish
  9950. case 'source-remove': // FIXME: proprietary
  9951. sess.removeSource($(iq).find('>jingle>content'));
  9952. break;
  9953. default:
  9954. logger.warn('jingle action not implemented', action);
  9955. break;
  9956. }
  9957. return true;
  9958. },
  9959. terminate: function (sid, reason, text) { // terminate by sessionid (or all sessions)
  9960. if (sid === null || sid === undefined) {
  9961. for (sid in this.sessions) {
  9962. if (this.sessions[sid].state != 'ended') {
  9963. this.sessions[sid].sendTerminate(reason || (!this.sessions[sid].active()) ? 'cancel' : null, text);
  9964. this.sessions[sid].terminate();
  9965. }
  9966. delete this.jid2session[this.sessions[sid].peerjid];
  9967. delete this.sessions[sid];
  9968. }
  9969. } else if (this.sessions.hasOwnProperty(sid)) {
  9970. if (this.sessions[sid].state != 'ended') {
  9971. this.sessions[sid].sendTerminate(reason || (!this.sessions[sid].active()) ? 'cancel' : null, text);
  9972. this.sessions[sid].terminate();
  9973. }
  9974. delete this.jid2session[this.sessions[sid].peerjid];
  9975. delete this.sessions[sid];
  9976. }
  9977. },
  9978. getStunAndTurnCredentials: function () {
  9979. // get stun and turn configuration from server via xep-0215
  9980. // uses time-limited credentials as described in
  9981. // http://tools.ietf.org/html/draft-uberti-behave-turn-rest-00
  9982. //
  9983. // see https://code.google.com/p/prosody-modules/source/browse/mod_turncredentials/mod_turncredentials.lua
  9984. // for a prosody module which implements this
  9985. //
  9986. // currently, this doesn't work with updateIce and therefore credentials with a long
  9987. // validity have to be fetched before creating the peerconnection
  9988. // TODO: implement refresh via updateIce as described in
  9989. // https://code.google.com/p/webrtc/issues/detail?id=1650
  9990. var self = this;
  9991. this.connection.sendIQ(
  9992. $iq({type: 'get', to: this.connection.domain})
  9993. .c('services', {xmlns: 'urn:xmpp:extdisco:1'}).c('service', {host: 'turn.' + this.connection.domain}),
  9994. function (res) {
  9995. var iceservers = [];
  9996. $(res).find('>services>service').each(function (idx, el) {
  9997. el = $(el);
  9998. var dict = {};
  9999. var type = el.attr('type');
  10000. switch (type) {
  10001. case 'stun':
  10002. dict.url = 'stun:' + el.attr('host');
  10003. if (el.attr('port')) {
  10004. dict.url += ':' + el.attr('port');
  10005. }
  10006. iceservers.push(dict);
  10007. break;
  10008. case 'turn':
  10009. case 'turns':
  10010. dict.url = type + ':';
  10011. if (el.attr('username')) { // https://code.google.com/p/webrtc/issues/detail?id=1508
  10012. if (navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./) && parseInt(navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./)[2], 10) < 28) {
  10013. dict.url += el.attr('username') + '@';
  10014. } else {
  10015. dict.username = el.attr('username'); // only works in M28
  10016. }
  10017. }
  10018. dict.url += el.attr('host');
  10019. if (el.attr('port') && el.attr('port') != '3478') {
  10020. dict.url += ':' + el.attr('port');
  10021. }
  10022. if (el.attr('transport') && el.attr('transport') != 'udp') {
  10023. dict.url += '?transport=' + el.attr('transport');
  10024. }
  10025. if (el.attr('password')) {
  10026. dict.credential = el.attr('password');
  10027. }
  10028. iceservers.push(dict);
  10029. break;
  10030. }
  10031. });
  10032. self.ice_config.iceServers = iceservers;
  10033. },
  10034. function (err) {
  10035. logger.warn('getting turn credentials failed', err);
  10036. logger.warn('is mod_turncredentials or similar installed?');
  10037. }
  10038. );
  10039. // implement push?
  10040. },
  10041. /**
  10042. * Returns the data saved in 'updateLog' in a format to be logged.
  10043. */
  10044. getLog: function () {
  10045. var data = {};
  10046. var self = this;
  10047. Object.keys(this.sessions).forEach(function (sid) {
  10048. var session = self.sessions[sid];
  10049. if (session.peerconnection && session.peerconnection.updateLog) {
  10050. // FIXME: should probably be a .dump call
  10051. data["jingle_" + session.sid] = {
  10052. updateLog: session.peerconnection.updateLog,
  10053. stats: session.peerconnection.stats,
  10054. url: window.location.href
  10055. };
  10056. }
  10057. });
  10058. return data;
  10059. }
  10060. });
  10061. };
  10062. }).call(this,"/modules/xmpp/strophe.jingle.js")
  10063. },{"../../service/xmpp/XMPPEvents":91,"../RTC/RTCBrowserType":17,"./JingleSessionPC":28,"jitsi-meet-logger":48}],38:[function(require,module,exports){
  10064. /* global Strophe */
  10065. module.exports = function () {
  10066. Strophe.addConnectionPlugin('logger', {
  10067. // logs raw stanzas and makes them available for download as JSON
  10068. connection: null,
  10069. log: [],
  10070. init: function (conn) {
  10071. this.connection = conn;
  10072. this.connection.rawInput = this.log_incoming.bind(this);
  10073. this.connection.rawOutput = this.log_outgoing.bind(this);
  10074. },
  10075. log_incoming: function (stanza) {
  10076. this.log.push([new Date().getTime(), 'incoming', stanza]);
  10077. },
  10078. log_outgoing: function (stanza) {
  10079. this.log.push([new Date().getTime(), 'outgoing', stanza]);
  10080. }
  10081. });
  10082. };
  10083. },{}],39:[function(require,module,exports){
  10084. (function (__filename){
  10085. /* global $, $iq, Strophe */
  10086. var logger = require("jitsi-meet-logger").getLogger(__filename);
  10087. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  10088. /**
  10089. * Ping every 20 sec
  10090. */
  10091. var PING_INTERVAL = 20000;
  10092. /**
  10093. * Ping timeout error after 15 sec of waiting.
  10094. */
  10095. var PING_TIMEOUT = 15000;
  10096. /**
  10097. * Will close the connection after 3 consecutive ping errors.
  10098. */
  10099. var PING_THRESHOLD = 3;
  10100. /**
  10101. * XEP-0199 ping plugin.
  10102. *
  10103. * Registers "urn:xmpp:ping" namespace under Strophe.NS.PING.
  10104. */
  10105. module.exports = function (XMPP, eventEmitter) {
  10106. Strophe.addConnectionPlugin('ping', {
  10107. connection: null,
  10108. failedPings: 0,
  10109. /**
  10110. * Initializes the plugin. Method called by Strophe.
  10111. * @param connection Strophe connection instance.
  10112. */
  10113. init: function (connection) {
  10114. this.connection = connection;
  10115. Strophe.addNamespace('PING', "urn:xmpp:ping");
  10116. },
  10117. /**
  10118. * Sends "ping" to given <tt>jid</tt>
  10119. * @param jid the JID to which ping request will be sent.
  10120. * @param success callback called on success.
  10121. * @param error callback called on error.
  10122. * @param timeout ms how long are we going to wait for the response. On
  10123. * timeout <tt>error<//t> callback is called with undefined error
  10124. * argument.
  10125. */
  10126. ping: function (jid, success, error, timeout) {
  10127. var iq = $iq({type: 'get', to: jid});
  10128. iq.c('ping', {xmlns: Strophe.NS.PING});
  10129. this.connection.sendIQ(iq, success, error, timeout);
  10130. },
  10131. /**
  10132. * Checks if given <tt>jid</tt> has XEP-0199 ping support.
  10133. * @param jid the JID to be checked for ping support.
  10134. * @param callback function with boolean argument which will be
  10135. * <tt>true</tt> if XEP-0199 ping is supported by given <tt>jid</tt>
  10136. */
  10137. hasPingSupport: function (jid, callback) {
  10138. this.connection.disco.info(
  10139. jid, null,
  10140. function (result) {
  10141. var ping = $(result).find('>>feature[var="urn:xmpp:ping"]');
  10142. callback(ping.length > 0);
  10143. },
  10144. function (error) {
  10145. logger.error("Ping feature discovery error", error);
  10146. callback(false);
  10147. }
  10148. );
  10149. },
  10150. /**
  10151. * Starts to send ping in given interval to specified remote JID.
  10152. * This plugin supports only one such task and <tt>stopInterval</tt>
  10153. * must be called before starting a new one.
  10154. * @param remoteJid remote JID to which ping requests will be sent to.
  10155. * @param interval task interval in ms.
  10156. */
  10157. startInterval: function (remoteJid, interval) {
  10158. if (this.intervalId) {
  10159. logger.error("Ping task scheduled already");
  10160. return;
  10161. }
  10162. if (!interval)
  10163. interval = PING_INTERVAL;
  10164. var self = this;
  10165. this.intervalId = window.setInterval(function () {
  10166. self.ping(remoteJid,
  10167. function (result) {
  10168. // Ping OK
  10169. self.failedPings = 0;
  10170. },
  10171. function (error) {
  10172. self.failedPings += 1;
  10173. logger.error(
  10174. "Ping " + (error ? "error" : "timeout"), error);
  10175. if (self.failedPings >= PING_THRESHOLD) {
  10176. self.connection.disconnect();
  10177. }
  10178. }, PING_TIMEOUT);
  10179. }, interval);
  10180. logger.info("XMPP pings will be sent every " + interval + " ms");
  10181. },
  10182. /**
  10183. * Stops current "ping" interval task.
  10184. */
  10185. stopInterval: function () {
  10186. if (this.intervalId) {
  10187. window.clearInterval(this.intervalId);
  10188. this.intervalId = null;
  10189. this.failedPings = 0;
  10190. logger.info("Ping interval cleared");
  10191. }
  10192. }
  10193. });
  10194. };
  10195. }).call(this,"/modules/xmpp/strophe.ping.js")
  10196. },{"../../service/xmpp/XMPPEvents":91,"jitsi-meet-logger":48}],40:[function(require,module,exports){
  10197. (function (__filename){
  10198. /* jshint -W117 */
  10199. var logger = require("jitsi-meet-logger").getLogger(__filename);
  10200. module.exports = function() {
  10201. Strophe.addConnectionPlugin('rayo',
  10202. {
  10203. RAYO_XMLNS: 'urn:xmpp:rayo:1',
  10204. connection: null,
  10205. init: function (conn) {
  10206. this.connection = conn;
  10207. if (this.connection.disco) {
  10208. this.connection.disco.addFeature('urn:xmpp:rayo:client:1');
  10209. }
  10210. this.connection.addHandler(
  10211. this.onRayo.bind(this), this.RAYO_XMLNS, 'iq', 'set',
  10212. null, null);
  10213. },
  10214. onRayo: function (iq) {
  10215. logger.info("Rayo IQ", iq);
  10216. },
  10217. dial: function (to, from, roomName, roomPass, focusMucJid) {
  10218. var self = this;
  10219. return new Promise(function (resolve, reject) {
  10220. if(!focusMucJid) {
  10221. reject(new Error("Internal error!"));
  10222. return;
  10223. }
  10224. var req = $iq(
  10225. {
  10226. type: 'set',
  10227. to: focusMucJid
  10228. }
  10229. );
  10230. req.c('dial',
  10231. {
  10232. xmlns: self.RAYO_XMLNS,
  10233. to: to,
  10234. from: from
  10235. });
  10236. req.c('header',
  10237. {
  10238. name: 'JvbRoomName',
  10239. value: roomName
  10240. }).up();
  10241. if (roomPass !== null && roomPass.length) {
  10242. req.c('header',
  10243. {
  10244. name: 'JvbRoomPassword',
  10245. value: roomPass
  10246. }).up();
  10247. }
  10248. self.connection.sendIQ(
  10249. req,
  10250. function (result) {
  10251. logger.info('Dial result ', result);
  10252. var resource = $(result).find('ref').attr('uri');
  10253. self.call_resource =
  10254. resource.substr('xmpp:'.length);
  10255. logger.info(
  10256. "Received call resource: " +
  10257. self.call_resource);
  10258. resolve();
  10259. },
  10260. function (error) {
  10261. logger.info('Dial error ', error);
  10262. reject(error);
  10263. }
  10264. );
  10265. });
  10266. },
  10267. hangup: function () {
  10268. var self = this;
  10269. return new Promise(function (resolve, reject) {
  10270. if (!self.call_resource) {
  10271. reject(new Error("No call in progress"));
  10272. logger.warn("No call in progress");
  10273. return;
  10274. }
  10275. var req = $iq(
  10276. {
  10277. type: 'set',
  10278. to: self.call_resource
  10279. }
  10280. );
  10281. req.c('hangup',
  10282. {
  10283. xmlns: self.RAYO_XMLNS
  10284. });
  10285. self.connection.sendIQ(
  10286. req,
  10287. function (result) {
  10288. logger.info('Hangup result ', result);
  10289. self.call_resource = null;
  10290. resolve();
  10291. },
  10292. function (error) {
  10293. logger.info('Hangup error ', error);
  10294. self.call_resource = null;
  10295. reject(new Error('Hangup error '));
  10296. }
  10297. );
  10298. });
  10299. }
  10300. }
  10301. );
  10302. };
  10303. }).call(this,"/modules/xmpp/strophe.rayo.js")
  10304. },{"jitsi-meet-logger":48}],41:[function(require,module,exports){
  10305. (function (__filename){
  10306. /* global Strophe */
  10307. /**
  10308. * Strophe logger implementation. Logs from level WARN and above.
  10309. */
  10310. var logger = require("jitsi-meet-logger").getLogger(__filename);
  10311. module.exports = function () {
  10312. Strophe.log = function (level, msg) {
  10313. switch (level) {
  10314. case Strophe.LogLevel.WARN:
  10315. logger.warn("Strophe: " + msg);
  10316. break;
  10317. case Strophe.LogLevel.ERROR:
  10318. case Strophe.LogLevel.FATAL:
  10319. logger.error("Strophe: " + msg);
  10320. break;
  10321. }
  10322. };
  10323. Strophe.getStatusString = function (status) {
  10324. switch (status) {
  10325. case Strophe.Status.ERROR:
  10326. return "ERROR";
  10327. case Strophe.Status.CONNECTING:
  10328. return "CONNECTING";
  10329. case Strophe.Status.CONNFAIL:
  10330. return "CONNFAIL";
  10331. case Strophe.Status.AUTHENTICATING:
  10332. return "AUTHENTICATING";
  10333. case Strophe.Status.AUTHFAIL:
  10334. return "AUTHFAIL";
  10335. case Strophe.Status.CONNECTED:
  10336. return "CONNECTED";
  10337. case Strophe.Status.DISCONNECTED:
  10338. return "DISCONNECTED";
  10339. case Strophe.Status.DISCONNECTING:
  10340. return "DISCONNECTING";
  10341. case Strophe.Status.ATTACHED:
  10342. return "ATTACHED";
  10343. default:
  10344. return "unknown";
  10345. }
  10346. };
  10347. };
  10348. }).call(this,"/modules/xmpp/strophe.util.js")
  10349. },{"jitsi-meet-logger":48}],42:[function(require,module,exports){
  10350. (function (__filename){
  10351. /* global $, APP, config, Strophe*/
  10352. var logger = require("jitsi-meet-logger").getLogger(__filename);
  10353. var EventEmitter = require("events");
  10354. var Pako = require("pako");
  10355. var RTCEvents = require("../../service/RTC/RTCEvents");
  10356. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  10357. var JitsiConnectionErrors = require("../../JitsiConnectionErrors");
  10358. var JitsiConnectionEvents = require("../../JitsiConnectionEvents");
  10359. var RTC = require("../RTC/RTC");
  10360. var authenticatedUser = false;
  10361. function createConnection(bosh) {
  10362. bosh = bosh || '/http-bind';
  10363. return new Strophe.Connection(bosh);
  10364. };
  10365. //!!!!!!!!!! FIXME: ...
  10366. function initStrophePlugins(XMPP)
  10367. {
  10368. require("./strophe.emuc")(XMPP);
  10369. require("./strophe.jingle")(XMPP, XMPP.eventEmitter);
  10370. // require("./strophe.moderate")(XMPP, eventEmitter);
  10371. require("./strophe.util")();
  10372. require("./strophe.ping")(XMPP, XMPP.eventEmitter);
  10373. require("./strophe.rayo")();
  10374. require("./strophe.logger")();
  10375. }
  10376. //!!!!!!!!!! FIXME: ...
  10377. ///**
  10378. // * If given <tt>localStream</tt> is video one this method will advertise it's
  10379. // * video type in MUC presence.
  10380. // * @param localStream new or modified <tt>LocalStream</tt>.
  10381. // */
  10382. //function broadcastLocalVideoType(localStream) {
  10383. // if (localStream.videoType)
  10384. // XMPP.addToPresence('videoType', localStream.videoType);
  10385. //}
  10386. //
  10387. //function registerListeners() {
  10388. // RTC.addStreamListener(
  10389. // broadcastLocalVideoType,
  10390. // StreamEventTypes.EVENT_TYPE_LOCAL_CHANGED
  10391. // );
  10392. // RTC.addListener(RTCEvents.AVAILABLE_DEVICES_CHANGED, function (devices) {
  10393. // XMPP.addToPresence("devices", devices);
  10394. // });
  10395. //}
  10396. function XMPP(options) {
  10397. this.eventEmitter = new EventEmitter();
  10398. this.connection = null;
  10399. this.disconnectInProgress = false;
  10400. this.forceMuted = false;
  10401. this.options = options;
  10402. initStrophePlugins(this);
  10403. // registerListeners();
  10404. this.connection = createConnection(options.bosh);
  10405. }
  10406. XMPP.prototype.getConnection = function(){ return connection; };
  10407. XMPP.prototype._connect = function (jid, password) {
  10408. var self = this;
  10409. // connection.connect() starts the connection process.
  10410. //
  10411. // As the connection process proceeds, the user supplied callback will
  10412. // be triggered multiple times with status updates. The callback should
  10413. // take two arguments - the status code and the error condition.
  10414. //
  10415. // The status code will be one of the values in the Strophe.Status
  10416. // constants. The error condition will be one of the conditions defined
  10417. // in RFC 3920 or the condition ‘strophe-parsererror’.
  10418. //
  10419. // The Parameters wait, hold and route are optional and only relevant
  10420. // for BOSH connections. Please see XEP 124 for a more detailed
  10421. // explanation of the optional parameters.
  10422. //
  10423. // Connection status constants for use by the connection handler
  10424. // callback.
  10425. //
  10426. // Status.ERROR - An error has occurred (websockets specific)
  10427. // Status.CONNECTING - The connection is currently being made
  10428. // Status.CONNFAIL - The connection attempt failed
  10429. // Status.AUTHENTICATING - The connection is authenticating
  10430. // Status.AUTHFAIL - The authentication attempt failed
  10431. // Status.CONNECTED - The connection has succeeded
  10432. // Status.DISCONNECTED - The connection has been terminated
  10433. // Status.DISCONNECTING - The connection is currently being terminated
  10434. // Status.ATTACHED - The connection has been attached
  10435. var anonymousConnectionFailed = false;
  10436. var connectionFailed = false;
  10437. var lastErrorMsg;
  10438. this.connection.connect(jid, password, function (status, msg) {
  10439. logger.log("(TIME) Strophe " + Strophe.getStatusString(status) +
  10440. (msg ? "[" + msg + "]" : "") + "\t:" + window.performance.now());
  10441. if (status === Strophe.Status.CONNECTED) {
  10442. if (self.options.useStunTurn) {
  10443. self.connection.jingle.getStunAndTurnCredentials();
  10444. }
  10445. logger.info("My Jabber ID: " + self.connection.jid);
  10446. // Schedule ping ?
  10447. var pingJid = self.connection.domain;
  10448. self.connection.ping.hasPingSupport(
  10449. pingJid,
  10450. function (hasPing) {
  10451. if (hasPing)
  10452. self.connection.ping.startInterval(pingJid);
  10453. else
  10454. logger.warn("Ping NOT supported by " + pingJid);
  10455. }
  10456. );
  10457. if (password)
  10458. authenticatedUser = true;
  10459. if (self.connection && self.connection.connected &&
  10460. Strophe.getResourceFromJid(self.connection.jid)) {
  10461. // .connected is true while connecting?
  10462. // self.connection.send($pres());
  10463. self.eventEmitter.emit(JitsiConnectionEvents.CONNECTION_ESTABLISHED,
  10464. Strophe.getResourceFromJid(self.connection.jid));
  10465. }
  10466. } else if (status === Strophe.Status.CONNFAIL) {
  10467. if (msg === 'x-strophe-bad-non-anon-jid') {
  10468. anonymousConnectionFailed = true;
  10469. }
  10470. else
  10471. {
  10472. connectionFailed = true;
  10473. }
  10474. lastErrorMsg = msg;
  10475. } else if (status === Strophe.Status.DISCONNECTED) {
  10476. // Stop ping interval
  10477. self.connection.ping.stopInterval();
  10478. self.disconnectInProgress = false;
  10479. if (anonymousConnectionFailed) {
  10480. // prompt user for username and password
  10481. self.eventEmitter.emit(JitsiConnectionEvents.CONNECTION_FAILED,
  10482. JitsiConnectionErrors.PASSWORD_REQUIRED);
  10483. } else if(connectionFailed) {
  10484. self.eventEmitter.emit(JitsiConnectionEvents.CONNECTION_FAILED,
  10485. JitsiConnectionErrors.OTHER_ERROR,
  10486. msg ? msg : lastErrorMsg);
  10487. } else {
  10488. self.eventEmitter.emit(JitsiConnectionEvents.CONNECTION_DISCONNECTED,
  10489. msg ? msg : lastErrorMsg);
  10490. }
  10491. } else if (status === Strophe.Status.AUTHFAIL) {
  10492. // wrong password or username, prompt user
  10493. self.eventEmitter.emit(JitsiConnectionEvents.CONNECTION_FAILED,
  10494. JitsiConnectionErrors.PASSWORD_REQUIRED);
  10495. }
  10496. });
  10497. }
  10498. XMPP.prototype.connect = function (jid, password) {
  10499. if(!jid) {
  10500. var configDomain = this.options.hosts.anonymousdomain || this.options.hosts.domain;
  10501. // Force authenticated domain if room is appended with '?login=true'
  10502. if (this.options.hosts.anonymousdomain &&
  10503. window.location.search.indexOf("login=true") !== -1) {
  10504. configDomain = this.options.hosts.domain;
  10505. }
  10506. jid = configDomain || window.location.hostname;
  10507. }
  10508. return this._connect(jid, password);
  10509. };
  10510. XMPP.prototype.createRoom = function (roomName, options, useNicks, nick) {
  10511. var roomjid = roomName + '@' + this.options.hosts.muc;
  10512. if (useNicks) {
  10513. if (nick) {
  10514. roomjid += '/' + nick;
  10515. } else {
  10516. roomjid += '/' + Strophe.getNodeFromJid(this.connection.jid);
  10517. }
  10518. } else {
  10519. var tmpJid = Strophe.getNodeFromJid(this.connection.jid);
  10520. if(!authenticatedUser)
  10521. tmpJid = tmpJid.substr(0, 8);
  10522. roomjid += '/' + tmpJid;
  10523. }
  10524. return this.connection.emuc.createRoom(roomjid, null, options);
  10525. }
  10526. XMPP.prototype.addListener = function(type, listener) {
  10527. this.eventEmitter.on(type, listener);
  10528. };
  10529. XMPP.prototype.removeListener = function (type, listener) {
  10530. this.eventEmitter.removeListener(type, listener);
  10531. };
  10532. //FIXME: this should work with the room
  10533. XMPP.prototype.leaveRoom = function (jid) {
  10534. var handler = this.connection.jingle.jid2session[jid];
  10535. if (handler && handler.peerconnection) {
  10536. // FIXME: probably removing streams is not required and close() should
  10537. // be enough
  10538. if (RTC.localAudio) {
  10539. handler.peerconnection.removeStream(
  10540. RTC.localAudio.getOriginalStream(), true);
  10541. }
  10542. if (RTC.localVideo) {
  10543. handler.peerconnection.removeStream(
  10544. RTC.localVideo.getOriginalStream(), true);
  10545. }
  10546. handler.peerconnection.close();
  10547. }
  10548. this.eventEmitter.emit(XMPPEvents.DISPOSE_CONFERENCE);
  10549. this.connection.emuc.doLeave(jid);
  10550. };
  10551. /**
  10552. * Sends 'data' as a log message to the focus. Returns true iff a message
  10553. * was sent.
  10554. * @param data
  10555. * @returns {boolean} true iff a message was sent.
  10556. */
  10557. XMPP.prototype.sendLogs = function (data) {
  10558. if(!this.connection.emuc.focusMucJid)
  10559. return false;
  10560. var deflate = true;
  10561. var content = JSON.stringify(data);
  10562. if (deflate) {
  10563. content = String.fromCharCode.apply(null, Pako.deflateRaw(content));
  10564. }
  10565. content = Base64.encode(content);
  10566. // XEP-0337-ish
  10567. var message = $msg({to: this.connection.emuc.focusMucJid, type: 'normal'});
  10568. message.c('log', { xmlns: 'urn:xmpp:eventlog',
  10569. id: 'PeerConnectionStats'});
  10570. message.c('message').t(content).up();
  10571. if (deflate) {
  10572. message.c('tag', {name: "deflated", value: "true"}).up();
  10573. }
  10574. message.up();
  10575. this.connection.send(message);
  10576. return true;
  10577. };
  10578. // Gets the logs from strophe.jingle.
  10579. XMPP.prototype.getJingleLog = function () {
  10580. return this.connection.jingle ? this.connection.jingle.getLog() : {};
  10581. };
  10582. // Gets the logs from strophe.
  10583. XMPP.prototype.getXmppLog = function () {
  10584. return this.connection.logger ? this.connection.logger.log : null;
  10585. };
  10586. XMPP.prototype.dial = function (to, from, roomName,roomPass) {
  10587. this.connection.rayo.dial(to, from, roomName,roomPass);
  10588. };
  10589. XMPP.prototype.setMute = function (jid, mute) {
  10590. this.connection.moderate.setMute(jid, mute);
  10591. };
  10592. XMPP.prototype.eject = function (jid) {
  10593. this.connection.moderate.eject(jid);
  10594. };
  10595. XMPP.prototype.getSessions = function () {
  10596. return this.connection.jingle.sessions;
  10597. };
  10598. XMPP.prototype.disconnect = function () {
  10599. if (this.disconnectInProgress || !this.connection || !this.connection.connected)
  10600. {
  10601. this.eventEmitter.emit(JitsiConnectionEvents.WRONG_STATE);
  10602. return;
  10603. }
  10604. this.disconnectInProgress = true;
  10605. this.connection.disconnect();
  10606. };
  10607. /**
  10608. * Gets the SSRC of local media stream.
  10609. * @param mediaType the media type that tells whether we want to get
  10610. * the SSRC of local audio or video stream.
  10611. * @returns {*} the SSRC number for local media stream or <tt>null</tt> if
  10612. * not available.
  10613. */
  10614. XMPP.prototype.getLocalSSRC = function (mediaType) {
  10615. if (this.connection.jingle.activecall &&
  10616. this.connection.jingle.activecall.peerconnection) {
  10617. return this.connection.jingle.activecall.getLocalSSRC(mediaType);
  10618. } else {
  10619. return null;
  10620. }
  10621. };
  10622. module.exports = XMPP;
  10623. }).call(this,"/modules/xmpp/xmpp.js")
  10624. },{"../../JitsiConnectionErrors":5,"../../JitsiConnectionEvents":6,"../../service/RTC/RTCEvents":84,"../../service/xmpp/XMPPEvents":91,"../RTC/RTC":16,"./strophe.emuc":36,"./strophe.jingle":37,"./strophe.logger":38,"./strophe.ping":39,"./strophe.rayo":40,"./strophe.util":41,"events":44,"jitsi-meet-logger":48,"pako":49}],43:[function(require,module,exports){
  10625. (function (process){
  10626. /*!
  10627. * async
  10628. * https://github.com/caolan/async
  10629. *
  10630. * Copyright 2010-2014 Caolan McMahon
  10631. * Released under the MIT license
  10632. */
  10633. /*jshint onevar: false, indent:4 */
  10634. /*global setImmediate: false, setTimeout: false, console: false */
  10635. (function () {
  10636. var async = {};
  10637. // global on the server, window in the browser
  10638. var root, previous_async;
  10639. root = this;
  10640. if (root != null) {
  10641. previous_async = root.async;
  10642. }
  10643. async.noConflict = function () {
  10644. root.async = previous_async;
  10645. return async;
  10646. };
  10647. function only_once(fn) {
  10648. var called = false;
  10649. return function() {
  10650. if (called) throw new Error("Callback was already called.");
  10651. called = true;
  10652. fn.apply(root, arguments);
  10653. }
  10654. }
  10655. //// cross-browser compatiblity functions ////
  10656. var _toString = Object.prototype.toString;
  10657. var _isArray = Array.isArray || function (obj) {
  10658. return _toString.call(obj) === '[object Array]';
  10659. };
  10660. var _each = function (arr, iterator) {
  10661. if (arr.forEach) {
  10662. return arr.forEach(iterator);
  10663. }
  10664. for (var i = 0; i < arr.length; i += 1) {
  10665. iterator(arr[i], i, arr);
  10666. }
  10667. };
  10668. var _map = function (arr, iterator) {
  10669. if (arr.map) {
  10670. return arr.map(iterator);
  10671. }
  10672. var results = [];
  10673. _each(arr, function (x, i, a) {
  10674. results.push(iterator(x, i, a));
  10675. });
  10676. return results;
  10677. };
  10678. var _reduce = function (arr, iterator, memo) {
  10679. if (arr.reduce) {
  10680. return arr.reduce(iterator, memo);
  10681. }
  10682. _each(arr, function (x, i, a) {
  10683. memo = iterator(memo, x, i, a);
  10684. });
  10685. return memo;
  10686. };
  10687. var _keys = function (obj) {
  10688. if (Object.keys) {
  10689. return Object.keys(obj);
  10690. }
  10691. var keys = [];
  10692. for (var k in obj) {
  10693. if (obj.hasOwnProperty(k)) {
  10694. keys.push(k);
  10695. }
  10696. }
  10697. return keys;
  10698. };
  10699. //// exported async module functions ////
  10700. //// nextTick implementation with browser-compatible fallback ////
  10701. if (typeof process === 'undefined' || !(process.nextTick)) {
  10702. if (typeof setImmediate === 'function') {
  10703. async.nextTick = function (fn) {
  10704. // not a direct alias for IE10 compatibility
  10705. setImmediate(fn);
  10706. };
  10707. async.setImmediate = async.nextTick;
  10708. }
  10709. else {
  10710. async.nextTick = function (fn) {
  10711. setTimeout(fn, 0);
  10712. };
  10713. async.setImmediate = async.nextTick;
  10714. }
  10715. }
  10716. else {
  10717. async.nextTick = process.nextTick;
  10718. if (typeof setImmediate !== 'undefined') {
  10719. async.setImmediate = function (fn) {
  10720. // not a direct alias for IE10 compatibility
  10721. setImmediate(fn);
  10722. };
  10723. }
  10724. else {
  10725. async.setImmediate = async.nextTick;
  10726. }
  10727. }
  10728. async.each = function (arr, iterator, callback) {
  10729. callback = callback || function () {};
  10730. if (!arr.length) {
  10731. return callback();
  10732. }
  10733. var completed = 0;
  10734. _each(arr, function (x) {
  10735. iterator(x, only_once(done) );
  10736. });
  10737. function done(err) {
  10738. if (err) {
  10739. callback(err);
  10740. callback = function () {};
  10741. }
  10742. else {
  10743. completed += 1;
  10744. if (completed >= arr.length) {
  10745. callback();
  10746. }
  10747. }
  10748. }
  10749. };
  10750. async.forEach = async.each;
  10751. async.eachSeries = function (arr, iterator, callback) {
  10752. callback = callback || function () {};
  10753. if (!arr.length) {
  10754. return callback();
  10755. }
  10756. var completed = 0;
  10757. var iterate = function () {
  10758. iterator(arr[completed], function (err) {
  10759. if (err) {
  10760. callback(err);
  10761. callback = function () {};
  10762. }
  10763. else {
  10764. completed += 1;
  10765. if (completed >= arr.length) {
  10766. callback();
  10767. }
  10768. else {
  10769. iterate();
  10770. }
  10771. }
  10772. });
  10773. };
  10774. iterate();
  10775. };
  10776. async.forEachSeries = async.eachSeries;
  10777. async.eachLimit = function (arr, limit, iterator, callback) {
  10778. var fn = _eachLimit(limit);
  10779. fn.apply(null, [arr, iterator, callback]);
  10780. };
  10781. async.forEachLimit = async.eachLimit;
  10782. var _eachLimit = function (limit) {
  10783. return function (arr, iterator, callback) {
  10784. callback = callback || function () {};
  10785. if (!arr.length || limit <= 0) {
  10786. return callback();
  10787. }
  10788. var completed = 0;
  10789. var started = 0;
  10790. var running = 0;
  10791. (function replenish () {
  10792. if (completed >= arr.length) {
  10793. return callback();
  10794. }
  10795. while (running < limit && started < arr.length) {
  10796. started += 1;
  10797. running += 1;
  10798. iterator(arr[started - 1], function (err) {
  10799. if (err) {
  10800. callback(err);
  10801. callback = function () {};
  10802. }
  10803. else {
  10804. completed += 1;
  10805. running -= 1;
  10806. if (completed >= arr.length) {
  10807. callback();
  10808. }
  10809. else {
  10810. replenish();
  10811. }
  10812. }
  10813. });
  10814. }
  10815. })();
  10816. };
  10817. };
  10818. var doParallel = function (fn) {
  10819. return function () {
  10820. var args = Array.prototype.slice.call(arguments);
  10821. return fn.apply(null, [async.each].concat(args));
  10822. };
  10823. };
  10824. var doParallelLimit = function(limit, fn) {
  10825. return function () {
  10826. var args = Array.prototype.slice.call(arguments);
  10827. return fn.apply(null, [_eachLimit(limit)].concat(args));
  10828. };
  10829. };
  10830. var doSeries = function (fn) {
  10831. return function () {
  10832. var args = Array.prototype.slice.call(arguments);
  10833. return fn.apply(null, [async.eachSeries].concat(args));
  10834. };
  10835. };
  10836. var _asyncMap = function (eachfn, arr, iterator, callback) {
  10837. arr = _map(arr, function (x, i) {
  10838. return {index: i, value: x};
  10839. });
  10840. if (!callback) {
  10841. eachfn(arr, function (x, callback) {
  10842. iterator(x.value, function (err) {
  10843. callback(err);
  10844. });
  10845. });
  10846. } else {
  10847. var results = [];
  10848. eachfn(arr, function (x, callback) {
  10849. iterator(x.value, function (err, v) {
  10850. results[x.index] = v;
  10851. callback(err);
  10852. });
  10853. }, function (err) {
  10854. callback(err, results);
  10855. });
  10856. }
  10857. };
  10858. async.map = doParallel(_asyncMap);
  10859. async.mapSeries = doSeries(_asyncMap);
  10860. async.mapLimit = function (arr, limit, iterator, callback) {
  10861. return _mapLimit(limit)(arr, iterator, callback);
  10862. };
  10863. var _mapLimit = function(limit) {
  10864. return doParallelLimit(limit, _asyncMap);
  10865. };
  10866. // reduce only has a series version, as doing reduce in parallel won't
  10867. // work in many situations.
  10868. async.reduce = function (arr, memo, iterator, callback) {
  10869. async.eachSeries(arr, function (x, callback) {
  10870. iterator(memo, x, function (err, v) {
  10871. memo = v;
  10872. callback(err);
  10873. });
  10874. }, function (err) {
  10875. callback(err, memo);
  10876. });
  10877. };
  10878. // inject alias
  10879. async.inject = async.reduce;
  10880. // foldl alias
  10881. async.foldl = async.reduce;
  10882. async.reduceRight = function (arr, memo, iterator, callback) {
  10883. var reversed = _map(arr, function (x) {
  10884. return x;
  10885. }).reverse();
  10886. async.reduce(reversed, memo, iterator, callback);
  10887. };
  10888. // foldr alias
  10889. async.foldr = async.reduceRight;
  10890. var _filter = function (eachfn, arr, iterator, callback) {
  10891. var results = [];
  10892. arr = _map(arr, function (x, i) {
  10893. return {index: i, value: x};
  10894. });
  10895. eachfn(arr, function (x, callback) {
  10896. iterator(x.value, function (v) {
  10897. if (v) {
  10898. results.push(x);
  10899. }
  10900. callback();
  10901. });
  10902. }, function (err) {
  10903. callback(_map(results.sort(function (a, b) {
  10904. return a.index - b.index;
  10905. }), function (x) {
  10906. return x.value;
  10907. }));
  10908. });
  10909. };
  10910. async.filter = doParallel(_filter);
  10911. async.filterSeries = doSeries(_filter);
  10912. // select alias
  10913. async.select = async.filter;
  10914. async.selectSeries = async.filterSeries;
  10915. var _reject = function (eachfn, arr, iterator, callback) {
  10916. var results = [];
  10917. arr = _map(arr, function (x, i) {
  10918. return {index: i, value: x};
  10919. });
  10920. eachfn(arr, function (x, callback) {
  10921. iterator(x.value, function (v) {
  10922. if (!v) {
  10923. results.push(x);
  10924. }
  10925. callback();
  10926. });
  10927. }, function (err) {
  10928. callback(_map(results.sort(function (a, b) {
  10929. return a.index - b.index;
  10930. }), function (x) {
  10931. return x.value;
  10932. }));
  10933. });
  10934. };
  10935. async.reject = doParallel(_reject);
  10936. async.rejectSeries = doSeries(_reject);
  10937. var _detect = function (eachfn, arr, iterator, main_callback) {
  10938. eachfn(arr, function (x, callback) {
  10939. iterator(x, function (result) {
  10940. if (result) {
  10941. main_callback(x);
  10942. main_callback = function () {};
  10943. }
  10944. else {
  10945. callback();
  10946. }
  10947. });
  10948. }, function (err) {
  10949. main_callback();
  10950. });
  10951. };
  10952. async.detect = doParallel(_detect);
  10953. async.detectSeries = doSeries(_detect);
  10954. async.some = function (arr, iterator, main_callback) {
  10955. async.each(arr, function (x, callback) {
  10956. iterator(x, function (v) {
  10957. if (v) {
  10958. main_callback(true);
  10959. main_callback = function () {};
  10960. }
  10961. callback();
  10962. });
  10963. }, function (err) {
  10964. main_callback(false);
  10965. });
  10966. };
  10967. // any alias
  10968. async.any = async.some;
  10969. async.every = function (arr, iterator, main_callback) {
  10970. async.each(arr, function (x, callback) {
  10971. iterator(x, function (v) {
  10972. if (!v) {
  10973. main_callback(false);
  10974. main_callback = function () {};
  10975. }
  10976. callback();
  10977. });
  10978. }, function (err) {
  10979. main_callback(true);
  10980. });
  10981. };
  10982. // all alias
  10983. async.all = async.every;
  10984. async.sortBy = function (arr, iterator, callback) {
  10985. async.map(arr, function (x, callback) {
  10986. iterator(x, function (err, criteria) {
  10987. if (err) {
  10988. callback(err);
  10989. }
  10990. else {
  10991. callback(null, {value: x, criteria: criteria});
  10992. }
  10993. });
  10994. }, function (err, results) {
  10995. if (err) {
  10996. return callback(err);
  10997. }
  10998. else {
  10999. var fn = function (left, right) {
  11000. var a = left.criteria, b = right.criteria;
  11001. return a < b ? -1 : a > b ? 1 : 0;
  11002. };
  11003. callback(null, _map(results.sort(fn), function (x) {
  11004. return x.value;
  11005. }));
  11006. }
  11007. });
  11008. };
  11009. async.auto = function (tasks, callback) {
  11010. callback = callback || function () {};
  11011. var keys = _keys(tasks);
  11012. var remainingTasks = keys.length
  11013. if (!remainingTasks) {
  11014. return callback();
  11015. }
  11016. var results = {};
  11017. var listeners = [];
  11018. var addListener = function (fn) {
  11019. listeners.unshift(fn);
  11020. };
  11021. var removeListener = function (fn) {
  11022. for (var i = 0; i < listeners.length; i += 1) {
  11023. if (listeners[i] === fn) {
  11024. listeners.splice(i, 1);
  11025. return;
  11026. }
  11027. }
  11028. };
  11029. var taskComplete = function () {
  11030. remainingTasks--
  11031. _each(listeners.slice(0), function (fn) {
  11032. fn();
  11033. });
  11034. };
  11035. addListener(function () {
  11036. if (!remainingTasks) {
  11037. var theCallback = callback;
  11038. // prevent final callback from calling itself if it errors
  11039. callback = function () {};
  11040. theCallback(null, results);
  11041. }
  11042. });
  11043. _each(keys, function (k) {
  11044. var task = _isArray(tasks[k]) ? tasks[k]: [tasks[k]];
  11045. var taskCallback = function (err) {
  11046. var args = Array.prototype.slice.call(arguments, 1);
  11047. if (args.length <= 1) {
  11048. args = args[0];
  11049. }
  11050. if (err) {
  11051. var safeResults = {};
  11052. _each(_keys(results), function(rkey) {
  11053. safeResults[rkey] = results[rkey];
  11054. });
  11055. safeResults[k] = args;
  11056. callback(err, safeResults);
  11057. // stop subsequent errors hitting callback multiple times
  11058. callback = function () {};
  11059. }
  11060. else {
  11061. results[k] = args;
  11062. async.setImmediate(taskComplete);
  11063. }
  11064. };
  11065. var requires = task.slice(0, Math.abs(task.length - 1)) || [];
  11066. var ready = function () {
  11067. return _reduce(requires, function (a, x) {
  11068. return (a && results.hasOwnProperty(x));
  11069. }, true) && !results.hasOwnProperty(k);
  11070. };
  11071. if (ready()) {
  11072. task[task.length - 1](taskCallback, results);
  11073. }
  11074. else {
  11075. var listener = function () {
  11076. if (ready()) {
  11077. removeListener(listener);
  11078. task[task.length - 1](taskCallback, results);
  11079. }
  11080. };
  11081. addListener(listener);
  11082. }
  11083. });
  11084. };
  11085. async.retry = function(times, task, callback) {
  11086. var DEFAULT_TIMES = 5;
  11087. var attempts = [];
  11088. // Use defaults if times not passed
  11089. if (typeof times === 'function') {
  11090. callback = task;
  11091. task = times;
  11092. times = DEFAULT_TIMES;
  11093. }
  11094. // Make sure times is a number
  11095. times = parseInt(times, 10) || DEFAULT_TIMES;
  11096. var wrappedTask = function(wrappedCallback, wrappedResults) {
  11097. var retryAttempt = function(task, finalAttempt) {
  11098. return function(seriesCallback) {
  11099. task(function(err, result){
  11100. seriesCallback(!err || finalAttempt, {err: err, result: result});
  11101. }, wrappedResults);
  11102. };
  11103. };
  11104. while (times) {
  11105. attempts.push(retryAttempt(task, !(times-=1)));
  11106. }
  11107. async.series(attempts, function(done, data){
  11108. data = data[data.length - 1];
  11109. (wrappedCallback || callback)(data.err, data.result);
  11110. });
  11111. }
  11112. // If a callback is passed, run this as a controll flow
  11113. return callback ? wrappedTask() : wrappedTask
  11114. };
  11115. async.waterfall = function (tasks, callback) {
  11116. callback = callback || function () {};
  11117. if (!_isArray(tasks)) {
  11118. var err = new Error('First argument to waterfall must be an array of functions');
  11119. return callback(err);
  11120. }
  11121. if (!tasks.length) {
  11122. return callback();
  11123. }
  11124. var wrapIterator = function (iterator) {
  11125. return function (err) {
  11126. if (err) {
  11127. callback.apply(null, arguments);
  11128. callback = function () {};
  11129. }
  11130. else {
  11131. var args = Array.prototype.slice.call(arguments, 1);
  11132. var next = iterator.next();
  11133. if (next) {
  11134. args.push(wrapIterator(next));
  11135. }
  11136. else {
  11137. args.push(callback);
  11138. }
  11139. async.setImmediate(function () {
  11140. iterator.apply(null, args);
  11141. });
  11142. }
  11143. };
  11144. };
  11145. wrapIterator(async.iterator(tasks))();
  11146. };
  11147. var _parallel = function(eachfn, tasks, callback) {
  11148. callback = callback || function () {};
  11149. if (_isArray(tasks)) {
  11150. eachfn.map(tasks, function (fn, callback) {
  11151. if (fn) {
  11152. fn(function (err) {
  11153. var args = Array.prototype.slice.call(arguments, 1);
  11154. if (args.length <= 1) {
  11155. args = args[0];
  11156. }
  11157. callback.call(null, err, args);
  11158. });
  11159. }
  11160. }, callback);
  11161. }
  11162. else {
  11163. var results = {};
  11164. eachfn.each(_keys(tasks), function (k, callback) {
  11165. tasks[k](function (err) {
  11166. var args = Array.prototype.slice.call(arguments, 1);
  11167. if (args.length <= 1) {
  11168. args = args[0];
  11169. }
  11170. results[k] = args;
  11171. callback(err);
  11172. });
  11173. }, function (err) {
  11174. callback(err, results);
  11175. });
  11176. }
  11177. };
  11178. async.parallel = function (tasks, callback) {
  11179. _parallel({ map: async.map, each: async.each }, tasks, callback);
  11180. };
  11181. async.parallelLimit = function(tasks, limit, callback) {
  11182. _parallel({ map: _mapLimit(limit), each: _eachLimit(limit) }, tasks, callback);
  11183. };
  11184. async.series = function (tasks, callback) {
  11185. callback = callback || function () {};
  11186. if (_isArray(tasks)) {
  11187. async.mapSeries(tasks, function (fn, callback) {
  11188. if (fn) {
  11189. fn(function (err) {
  11190. var args = Array.prototype.slice.call(arguments, 1);
  11191. if (args.length <= 1) {
  11192. args = args[0];
  11193. }
  11194. callback.call(null, err, args);
  11195. });
  11196. }
  11197. }, callback);
  11198. }
  11199. else {
  11200. var results = {};
  11201. async.eachSeries(_keys(tasks), function (k, callback) {
  11202. tasks[k](function (err) {
  11203. var args = Array.prototype.slice.call(arguments, 1);
  11204. if (args.length <= 1) {
  11205. args = args[0];
  11206. }
  11207. results[k] = args;
  11208. callback(err);
  11209. });
  11210. }, function (err) {
  11211. callback(err, results);
  11212. });
  11213. }
  11214. };
  11215. async.iterator = function (tasks) {
  11216. var makeCallback = function (index) {
  11217. var fn = function () {
  11218. if (tasks.length) {
  11219. tasks[index].apply(null, arguments);
  11220. }
  11221. return fn.next();
  11222. };
  11223. fn.next = function () {
  11224. return (index < tasks.length - 1) ? makeCallback(index + 1): null;
  11225. };
  11226. return fn;
  11227. };
  11228. return makeCallback(0);
  11229. };
  11230. async.apply = function (fn) {
  11231. var args = Array.prototype.slice.call(arguments, 1);
  11232. return function () {
  11233. return fn.apply(
  11234. null, args.concat(Array.prototype.slice.call(arguments))
  11235. );
  11236. };
  11237. };
  11238. var _concat = function (eachfn, arr, fn, callback) {
  11239. var r = [];
  11240. eachfn(arr, function (x, cb) {
  11241. fn(x, function (err, y) {
  11242. r = r.concat(y || []);
  11243. cb(err);
  11244. });
  11245. }, function (err) {
  11246. callback(err, r);
  11247. });
  11248. };
  11249. async.concat = doParallel(_concat);
  11250. async.concatSeries = doSeries(_concat);
  11251. async.whilst = function (test, iterator, callback) {
  11252. if (test()) {
  11253. iterator(function (err) {
  11254. if (err) {
  11255. return callback(err);
  11256. }
  11257. async.whilst(test, iterator, callback);
  11258. });
  11259. }
  11260. else {
  11261. callback();
  11262. }
  11263. };
  11264. async.doWhilst = function (iterator, test, callback) {
  11265. iterator(function (err) {
  11266. if (err) {
  11267. return callback(err);
  11268. }
  11269. var args = Array.prototype.slice.call(arguments, 1);
  11270. if (test.apply(null, args)) {
  11271. async.doWhilst(iterator, test, callback);
  11272. }
  11273. else {
  11274. callback();
  11275. }
  11276. });
  11277. };
  11278. async.until = function (test, iterator, callback) {
  11279. if (!test()) {
  11280. iterator(function (err) {
  11281. if (err) {
  11282. return callback(err);
  11283. }
  11284. async.until(test, iterator, callback);
  11285. });
  11286. }
  11287. else {
  11288. callback();
  11289. }
  11290. };
  11291. async.doUntil = function (iterator, test, callback) {
  11292. iterator(function (err) {
  11293. if (err) {
  11294. return callback(err);
  11295. }
  11296. var args = Array.prototype.slice.call(arguments, 1);
  11297. if (!test.apply(null, args)) {
  11298. async.doUntil(iterator, test, callback);
  11299. }
  11300. else {
  11301. callback();
  11302. }
  11303. });
  11304. };
  11305. async.queue = function (worker, concurrency) {
  11306. if (concurrency === undefined) {
  11307. concurrency = 1;
  11308. }
  11309. function _insert(q, data, pos, callback) {
  11310. if (!q.started){
  11311. q.started = true;
  11312. }
  11313. if (!_isArray(data)) {
  11314. data = [data];
  11315. }
  11316. if(data.length == 0) {
  11317. // call drain immediately if there are no tasks
  11318. return async.setImmediate(function() {
  11319. if (q.drain) {
  11320. q.drain();
  11321. }
  11322. });
  11323. }
  11324. _each(data, function(task) {
  11325. var item = {
  11326. data: task,
  11327. callback: typeof callback === 'function' ? callback : null
  11328. };
  11329. if (pos) {
  11330. q.tasks.unshift(item);
  11331. } else {
  11332. q.tasks.push(item);
  11333. }
  11334. if (q.saturated && q.tasks.length === q.concurrency) {
  11335. q.saturated();
  11336. }
  11337. async.setImmediate(q.process);
  11338. });
  11339. }
  11340. var workers = 0;
  11341. var q = {
  11342. tasks: [],
  11343. concurrency: concurrency,
  11344. saturated: null,
  11345. empty: null,
  11346. drain: null,
  11347. started: false,
  11348. paused: false,
  11349. push: function (data, callback) {
  11350. _insert(q, data, false, callback);
  11351. },
  11352. kill: function () {
  11353. q.drain = null;
  11354. q.tasks = [];
  11355. },
  11356. unshift: function (data, callback) {
  11357. _insert(q, data, true, callback);
  11358. },
  11359. process: function () {
  11360. if (!q.paused && workers < q.concurrency && q.tasks.length) {
  11361. var task = q.tasks.shift();
  11362. if (q.empty && q.tasks.length === 0) {
  11363. q.empty();
  11364. }
  11365. workers += 1;
  11366. var next = function () {
  11367. workers -= 1;
  11368. if (task.callback) {
  11369. task.callback.apply(task, arguments);
  11370. }
  11371. if (q.drain && q.tasks.length + workers === 0) {
  11372. q.drain();
  11373. }
  11374. q.process();
  11375. };
  11376. var cb = only_once(next);
  11377. worker(task.data, cb);
  11378. }
  11379. },
  11380. length: function () {
  11381. return q.tasks.length;
  11382. },
  11383. running: function () {
  11384. return workers;
  11385. },
  11386. idle: function() {
  11387. return q.tasks.length + workers === 0;
  11388. },
  11389. pause: function () {
  11390. if (q.paused === true) { return; }
  11391. q.paused = true;
  11392. q.process();
  11393. },
  11394. resume: function () {
  11395. if (q.paused === false) { return; }
  11396. q.paused = false;
  11397. q.process();
  11398. }
  11399. };
  11400. return q;
  11401. };
  11402. async.priorityQueue = function (worker, concurrency) {
  11403. function _compareTasks(a, b){
  11404. return a.priority - b.priority;
  11405. };
  11406. function _binarySearch(sequence, item, compare) {
  11407. var beg = -1,
  11408. end = sequence.length - 1;
  11409. while (beg < end) {
  11410. var mid = beg + ((end - beg + 1) >>> 1);
  11411. if (compare(item, sequence[mid]) >= 0) {
  11412. beg = mid;
  11413. } else {
  11414. end = mid - 1;
  11415. }
  11416. }
  11417. return beg;
  11418. }
  11419. function _insert(q, data, priority, callback) {
  11420. if (!q.started){
  11421. q.started = true;
  11422. }
  11423. if (!_isArray(data)) {
  11424. data = [data];
  11425. }
  11426. if(data.length == 0) {
  11427. // call drain immediately if there are no tasks
  11428. return async.setImmediate(function() {
  11429. if (q.drain) {
  11430. q.drain();
  11431. }
  11432. });
  11433. }
  11434. _each(data, function(task) {
  11435. var item = {
  11436. data: task,
  11437. priority: priority,
  11438. callback: typeof callback === 'function' ? callback : null
  11439. };
  11440. q.tasks.splice(_binarySearch(q.tasks, item, _compareTasks) + 1, 0, item);
  11441. if (q.saturated && q.tasks.length === q.concurrency) {
  11442. q.saturated();
  11443. }
  11444. async.setImmediate(q.process);
  11445. });
  11446. }
  11447. // Start with a normal queue
  11448. var q = async.queue(worker, concurrency);
  11449. // Override push to accept second parameter representing priority
  11450. q.push = function (data, priority, callback) {
  11451. _insert(q, data, priority, callback);
  11452. };
  11453. // Remove unshift function
  11454. delete q.unshift;
  11455. return q;
  11456. };
  11457. async.cargo = function (worker, payload) {
  11458. var working = false,
  11459. tasks = [];
  11460. var cargo = {
  11461. tasks: tasks,
  11462. payload: payload,
  11463. saturated: null,
  11464. empty: null,
  11465. drain: null,
  11466. drained: true,
  11467. push: function (data, callback) {
  11468. if (!_isArray(data)) {
  11469. data = [data];
  11470. }
  11471. _each(data, function(task) {
  11472. tasks.push({
  11473. data: task,
  11474. callback: typeof callback === 'function' ? callback : null
  11475. });
  11476. cargo.drained = false;
  11477. if (cargo.saturated && tasks.length === payload) {
  11478. cargo.saturated();
  11479. }
  11480. });
  11481. async.setImmediate(cargo.process);
  11482. },
  11483. process: function process() {
  11484. if (working) return;
  11485. if (tasks.length === 0) {
  11486. if(cargo.drain && !cargo.drained) cargo.drain();
  11487. cargo.drained = true;
  11488. return;
  11489. }
  11490. var ts = typeof payload === 'number'
  11491. ? tasks.splice(0, payload)
  11492. : tasks.splice(0, tasks.length);
  11493. var ds = _map(ts, function (task) {
  11494. return task.data;
  11495. });
  11496. if(cargo.empty) cargo.empty();
  11497. working = true;
  11498. worker(ds, function () {
  11499. working = false;
  11500. var args = arguments;
  11501. _each(ts, function (data) {
  11502. if (data.callback) {
  11503. data.callback.apply(null, args);
  11504. }
  11505. });
  11506. process();
  11507. });
  11508. },
  11509. length: function () {
  11510. return tasks.length;
  11511. },
  11512. running: function () {
  11513. return working;
  11514. }
  11515. };
  11516. return cargo;
  11517. };
  11518. var _console_fn = function (name) {
  11519. return function (fn) {
  11520. var args = Array.prototype.slice.call(arguments, 1);
  11521. fn.apply(null, args.concat([function (err) {
  11522. var args = Array.prototype.slice.call(arguments, 1);
  11523. if (typeof console !== 'undefined') {
  11524. if (err) {
  11525. if (console.error) {
  11526. console.error(err);
  11527. }
  11528. }
  11529. else if (console[name]) {
  11530. _each(args, function (x) {
  11531. console[name](x);
  11532. });
  11533. }
  11534. }
  11535. }]));
  11536. };
  11537. };
  11538. async.log = _console_fn('log');
  11539. async.dir = _console_fn('dir');
  11540. /*async.info = _console_fn('info');
  11541. async.warn = _console_fn('warn');
  11542. async.error = _console_fn('error');*/
  11543. async.memoize = function (fn, hasher) {
  11544. var memo = {};
  11545. var queues = {};
  11546. hasher = hasher || function (x) {
  11547. return x;
  11548. };
  11549. var memoized = function () {
  11550. var args = Array.prototype.slice.call(arguments);
  11551. var callback = args.pop();
  11552. var key = hasher.apply(null, args);
  11553. if (key in memo) {
  11554. async.nextTick(function () {
  11555. callback.apply(null, memo[key]);
  11556. });
  11557. }
  11558. else if (key in queues) {
  11559. queues[key].push(callback);
  11560. }
  11561. else {
  11562. queues[key] = [callback];
  11563. fn.apply(null, args.concat([function () {
  11564. memo[key] = arguments;
  11565. var q = queues[key];
  11566. delete queues[key];
  11567. for (var i = 0, l = q.length; i < l; i++) {
  11568. q[i].apply(null, arguments);
  11569. }
  11570. }]));
  11571. }
  11572. };
  11573. memoized.memo = memo;
  11574. memoized.unmemoized = fn;
  11575. return memoized;
  11576. };
  11577. async.unmemoize = function (fn) {
  11578. return function () {
  11579. return (fn.unmemoized || fn).apply(null, arguments);
  11580. };
  11581. };
  11582. async.times = function (count, iterator, callback) {
  11583. var counter = [];
  11584. for (var i = 0; i < count; i++) {
  11585. counter.push(i);
  11586. }
  11587. return async.map(counter, iterator, callback);
  11588. };
  11589. async.timesSeries = function (count, iterator, callback) {
  11590. var counter = [];
  11591. for (var i = 0; i < count; i++) {
  11592. counter.push(i);
  11593. }
  11594. return async.mapSeries(counter, iterator, callback);
  11595. };
  11596. async.seq = function (/* functions... */) {
  11597. var fns = arguments;
  11598. return function () {
  11599. var that = this;
  11600. var args = Array.prototype.slice.call(arguments);
  11601. var callback = args.pop();
  11602. async.reduce(fns, args, function (newargs, fn, cb) {
  11603. fn.apply(that, newargs.concat([function () {
  11604. var err = arguments[0];
  11605. var nextargs = Array.prototype.slice.call(arguments, 1);
  11606. cb(err, nextargs);
  11607. }]))
  11608. },
  11609. function (err, results) {
  11610. callback.apply(that, [err].concat(results));
  11611. });
  11612. };
  11613. };
  11614. async.compose = function (/* functions... */) {
  11615. return async.seq.apply(null, Array.prototype.reverse.call(arguments));
  11616. };
  11617. var _applyEach = function (eachfn, fns /*args...*/) {
  11618. var go = function () {
  11619. var that = this;
  11620. var args = Array.prototype.slice.call(arguments);
  11621. var callback = args.pop();
  11622. return eachfn(fns, function (fn, cb) {
  11623. fn.apply(that, args.concat([cb]));
  11624. },
  11625. callback);
  11626. };
  11627. if (arguments.length > 2) {
  11628. var args = Array.prototype.slice.call(arguments, 2);
  11629. return go.apply(this, args);
  11630. }
  11631. else {
  11632. return go;
  11633. }
  11634. };
  11635. async.applyEach = doParallel(_applyEach);
  11636. async.applyEachSeries = doSeries(_applyEach);
  11637. async.forever = function (fn, callback) {
  11638. function next(err) {
  11639. if (err) {
  11640. if (callback) {
  11641. return callback(err);
  11642. }
  11643. throw err;
  11644. }
  11645. fn(next);
  11646. }
  11647. next();
  11648. };
  11649. // Node.js
  11650. if (typeof module !== 'undefined' && module.exports) {
  11651. module.exports = async;
  11652. }
  11653. // AMD / RequireJS
  11654. else if (typeof define !== 'undefined' && define.amd) {
  11655. define([], function () {
  11656. return async;
  11657. });
  11658. }
  11659. // included directly via <script> tag
  11660. else {
  11661. root.async = async;
  11662. }
  11663. }());
  11664. }).call(this,require('_process'))
  11665. },{"_process":45}],44:[function(require,module,exports){
  11666. // Copyright Joyent, Inc. and other Node contributors.
  11667. //
  11668. // Permission is hereby granted, free of charge, to any person obtaining a
  11669. // copy of this software and associated documentation files (the
  11670. // "Software"), to deal in the Software without restriction, including
  11671. // without limitation the rights to use, copy, modify, merge, publish,
  11672. // distribute, sublicense, and/or sell copies of the Software, and to permit
  11673. // persons to whom the Software is furnished to do so, subject to the
  11674. // following conditions:
  11675. //
  11676. // The above copyright notice and this permission notice shall be included
  11677. // in all copies or substantial portions of the Software.
  11678. //
  11679. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  11680. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  11681. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  11682. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  11683. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  11684. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  11685. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  11686. function EventEmitter() {
  11687. this._events = this._events || {};
  11688. this._maxListeners = this._maxListeners || undefined;
  11689. }
  11690. module.exports = EventEmitter;
  11691. // Backwards-compat with node 0.10.x
  11692. EventEmitter.EventEmitter = EventEmitter;
  11693. EventEmitter.prototype._events = undefined;
  11694. EventEmitter.prototype._maxListeners = undefined;
  11695. // By default EventEmitters will print a warning if more than 10 listeners are
  11696. // added to it. This is a useful default which helps finding memory leaks.
  11697. EventEmitter.defaultMaxListeners = 10;
  11698. // Obviously not all Emitters should be limited to 10. This function allows
  11699. // that to be increased. Set to zero for unlimited.
  11700. EventEmitter.prototype.setMaxListeners = function(n) {
  11701. if (!isNumber(n) || n < 0 || isNaN(n))
  11702. throw TypeError('n must be a positive number');
  11703. this._maxListeners = n;
  11704. return this;
  11705. };
  11706. EventEmitter.prototype.emit = function(type) {
  11707. var er, handler, len, args, i, listeners;
  11708. if (!this._events)
  11709. this._events = {};
  11710. // If there is no 'error' event listener then throw.
  11711. if (type === 'error') {
  11712. if (!this._events.error ||
  11713. (isObject(this._events.error) && !this._events.error.length)) {
  11714. er = arguments[1];
  11715. if (er instanceof Error) {
  11716. throw er; // Unhandled 'error' event
  11717. }
  11718. throw TypeError('Uncaught, unspecified "error" event.');
  11719. }
  11720. }
  11721. handler = this._events[type];
  11722. if (isUndefined(handler))
  11723. return false;
  11724. if (isFunction(handler)) {
  11725. switch (arguments.length) {
  11726. // fast cases
  11727. case 1:
  11728. handler.call(this);
  11729. break;
  11730. case 2:
  11731. handler.call(this, arguments[1]);
  11732. break;
  11733. case 3:
  11734. handler.call(this, arguments[1], arguments[2]);
  11735. break;
  11736. // slower
  11737. default:
  11738. len = arguments.length;
  11739. args = new Array(len - 1);
  11740. for (i = 1; i < len; i++)
  11741. args[i - 1] = arguments[i];
  11742. handler.apply(this, args);
  11743. }
  11744. } else if (isObject(handler)) {
  11745. len = arguments.length;
  11746. args = new Array(len - 1);
  11747. for (i = 1; i < len; i++)
  11748. args[i - 1] = arguments[i];
  11749. listeners = handler.slice();
  11750. len = listeners.length;
  11751. for (i = 0; i < len; i++)
  11752. listeners[i].apply(this, args);
  11753. }
  11754. return true;
  11755. };
  11756. EventEmitter.prototype.addListener = function(type, listener) {
  11757. var m;
  11758. if (!isFunction(listener))
  11759. throw TypeError('listener must be a function');
  11760. if (!this._events)
  11761. this._events = {};
  11762. // To avoid recursion in the case that type === "newListener"! Before
  11763. // adding it to the listeners, first emit "newListener".
  11764. if (this._events.newListener)
  11765. this.emit('newListener', type,
  11766. isFunction(listener.listener) ?
  11767. listener.listener : listener);
  11768. if (!this._events[type])
  11769. // Optimize the case of one listener. Don't need the extra array object.
  11770. this._events[type] = listener;
  11771. else if (isObject(this._events[type]))
  11772. // If we've already got an array, just append.
  11773. this._events[type].push(listener);
  11774. else
  11775. // Adding the second element, need to change to array.
  11776. this._events[type] = [this._events[type], listener];
  11777. // Check for listener leak
  11778. if (isObject(this._events[type]) && !this._events[type].warned) {
  11779. var m;
  11780. if (!isUndefined(this._maxListeners)) {
  11781. m = this._maxListeners;
  11782. } else {
  11783. m = EventEmitter.defaultMaxListeners;
  11784. }
  11785. if (m && m > 0 && this._events[type].length > m) {
  11786. this._events[type].warned = true;
  11787. console.error('(node) warning: possible EventEmitter memory ' +
  11788. 'leak detected. %d listeners added. ' +
  11789. 'Use emitter.setMaxListeners() to increase limit.',
  11790. this._events[type].length);
  11791. if (typeof console.trace === 'function') {
  11792. // not supported in IE 10
  11793. console.trace();
  11794. }
  11795. }
  11796. }
  11797. return this;
  11798. };
  11799. EventEmitter.prototype.on = EventEmitter.prototype.addListener;
  11800. EventEmitter.prototype.once = function(type, listener) {
  11801. if (!isFunction(listener))
  11802. throw TypeError('listener must be a function');
  11803. var fired = false;
  11804. function g() {
  11805. this.removeListener(type, g);
  11806. if (!fired) {
  11807. fired = true;
  11808. listener.apply(this, arguments);
  11809. }
  11810. }
  11811. g.listener = listener;
  11812. this.on(type, g);
  11813. return this;
  11814. };
  11815. // emits a 'removeListener' event iff the listener was removed
  11816. EventEmitter.prototype.removeListener = function(type, listener) {
  11817. var list, position, length, i;
  11818. if (!isFunction(listener))
  11819. throw TypeError('listener must be a function');
  11820. if (!this._events || !this._events[type])
  11821. return this;
  11822. list = this._events[type];
  11823. length = list.length;
  11824. position = -1;
  11825. if (list === listener ||
  11826. (isFunction(list.listener) && list.listener === listener)) {
  11827. delete this._events[type];
  11828. if (this._events.removeListener)
  11829. this.emit('removeListener', type, listener);
  11830. } else if (isObject(list)) {
  11831. for (i = length; i-- > 0;) {
  11832. if (list[i] === listener ||
  11833. (list[i].listener && list[i].listener === listener)) {
  11834. position = i;
  11835. break;
  11836. }
  11837. }
  11838. if (position < 0)
  11839. return this;
  11840. if (list.length === 1) {
  11841. list.length = 0;
  11842. delete this._events[type];
  11843. } else {
  11844. list.splice(position, 1);
  11845. }
  11846. if (this._events.removeListener)
  11847. this.emit('removeListener', type, listener);
  11848. }
  11849. return this;
  11850. };
  11851. EventEmitter.prototype.removeAllListeners = function(type) {
  11852. var key, listeners;
  11853. if (!this._events)
  11854. return this;
  11855. // not listening for removeListener, no need to emit
  11856. if (!this._events.removeListener) {
  11857. if (arguments.length === 0)
  11858. this._events = {};
  11859. else if (this._events[type])
  11860. delete this._events[type];
  11861. return this;
  11862. }
  11863. // emit removeListener for all listeners on all events
  11864. if (arguments.length === 0) {
  11865. for (key in this._events) {
  11866. if (key === 'removeListener') continue;
  11867. this.removeAllListeners(key);
  11868. }
  11869. this.removeAllListeners('removeListener');
  11870. this._events = {};
  11871. return this;
  11872. }
  11873. listeners = this._events[type];
  11874. if (isFunction(listeners)) {
  11875. this.removeListener(type, listeners);
  11876. } else {
  11877. // LIFO order
  11878. while (listeners.length)
  11879. this.removeListener(type, listeners[listeners.length - 1]);
  11880. }
  11881. delete this._events[type];
  11882. return this;
  11883. };
  11884. EventEmitter.prototype.listeners = function(type) {
  11885. var ret;
  11886. if (!this._events || !this._events[type])
  11887. ret = [];
  11888. else if (isFunction(this._events[type]))
  11889. ret = [this._events[type]];
  11890. else
  11891. ret = this._events[type].slice();
  11892. return ret;
  11893. };
  11894. EventEmitter.listenerCount = function(emitter, type) {
  11895. var ret;
  11896. if (!emitter._events || !emitter._events[type])
  11897. ret = 0;
  11898. else if (isFunction(emitter._events[type]))
  11899. ret = 1;
  11900. else
  11901. ret = emitter._events[type].length;
  11902. return ret;
  11903. };
  11904. function isFunction(arg) {
  11905. return typeof arg === 'function';
  11906. }
  11907. function isNumber(arg) {
  11908. return typeof arg === 'number';
  11909. }
  11910. function isObject(arg) {
  11911. return typeof arg === 'object' && arg !== null;
  11912. }
  11913. function isUndefined(arg) {
  11914. return arg === void 0;
  11915. }
  11916. },{}],45:[function(require,module,exports){
  11917. // shim for using process in browser
  11918. var process = module.exports = {};
  11919. var queue = [];
  11920. var draining = false;
  11921. var currentQueue;
  11922. var queueIndex = -1;
  11923. function cleanUpNextTick() {
  11924. draining = false;
  11925. if (currentQueue.length) {
  11926. queue = currentQueue.concat(queue);
  11927. } else {
  11928. queueIndex = -1;
  11929. }
  11930. if (queue.length) {
  11931. drainQueue();
  11932. }
  11933. }
  11934. function drainQueue() {
  11935. if (draining) {
  11936. return;
  11937. }
  11938. var timeout = setTimeout(cleanUpNextTick);
  11939. draining = true;
  11940. var len = queue.length;
  11941. while(len) {
  11942. currentQueue = queue;
  11943. queue = [];
  11944. while (++queueIndex < len) {
  11945. if (currentQueue) {
  11946. currentQueue[queueIndex].run();
  11947. }
  11948. }
  11949. queueIndex = -1;
  11950. len = queue.length;
  11951. }
  11952. currentQueue = null;
  11953. draining = false;
  11954. clearTimeout(timeout);
  11955. }
  11956. process.nextTick = function (fun) {
  11957. var args = new Array(arguments.length - 1);
  11958. if (arguments.length > 1) {
  11959. for (var i = 1; i < arguments.length; i++) {
  11960. args[i - 1] = arguments[i];
  11961. }
  11962. }
  11963. queue.push(new Item(fun, args));
  11964. if (queue.length === 1 && !draining) {
  11965. setTimeout(drainQueue, 0);
  11966. }
  11967. };
  11968. // v8 likes predictible objects
  11969. function Item(fun, array) {
  11970. this.fun = fun;
  11971. this.array = array;
  11972. }
  11973. Item.prototype.run = function () {
  11974. this.fun.apply(null, this.array);
  11975. };
  11976. process.title = 'browser';
  11977. process.browser = true;
  11978. process.env = {};
  11979. process.argv = [];
  11980. process.version = ''; // empty string to avoid regexp issues
  11981. process.versions = {};
  11982. function noop() {}
  11983. process.on = noop;
  11984. process.addListener = noop;
  11985. process.once = noop;
  11986. process.off = noop;
  11987. process.removeListener = noop;
  11988. process.removeAllListeners = noop;
  11989. process.emit = noop;
  11990. process.binding = function (name) {
  11991. throw new Error('process.binding is not supported');
  11992. };
  11993. process.cwd = function () { return '/' };
  11994. process.chdir = function (dir) {
  11995. throw new Error('process.chdir is not supported');
  11996. };
  11997. process.umask = function() { return 0; };
  11998. },{}],46:[function(require,module,exports){
  11999. (function (process,global){
  12000. /*!
  12001. * @overview es6-promise - a tiny implementation of Promises/A+.
  12002. * @copyright Copyright (c) 2014 Yehuda Katz, Tom Dale, Stefan Penner and contributors (Conversion to ES6 API by Jake Archibald)
  12003. * @license Licensed under MIT license
  12004. * See https://raw.githubusercontent.com/jakearchibald/es6-promise/master/LICENSE
  12005. * @version 3.0.2
  12006. */
  12007. (function() {
  12008. "use strict";
  12009. function lib$es6$promise$utils$$objectOrFunction(x) {
  12010. return typeof x === 'function' || (typeof x === 'object' && x !== null);
  12011. }
  12012. function lib$es6$promise$utils$$isFunction(x) {
  12013. return typeof x === 'function';
  12014. }
  12015. function lib$es6$promise$utils$$isMaybeThenable(x) {
  12016. return typeof x === 'object' && x !== null;
  12017. }
  12018. var lib$es6$promise$utils$$_isArray;
  12019. if (!Array.isArray) {
  12020. lib$es6$promise$utils$$_isArray = function (x) {
  12021. return Object.prototype.toString.call(x) === '[object Array]';
  12022. };
  12023. } else {
  12024. lib$es6$promise$utils$$_isArray = Array.isArray;
  12025. }
  12026. var lib$es6$promise$utils$$isArray = lib$es6$promise$utils$$_isArray;
  12027. var lib$es6$promise$asap$$len = 0;
  12028. var lib$es6$promise$asap$$toString = {}.toString;
  12029. var lib$es6$promise$asap$$vertxNext;
  12030. var lib$es6$promise$asap$$customSchedulerFn;
  12031. var lib$es6$promise$asap$$asap = function asap(callback, arg) {
  12032. lib$es6$promise$asap$$queue[lib$es6$promise$asap$$len] = callback;
  12033. lib$es6$promise$asap$$queue[lib$es6$promise$asap$$len + 1] = arg;
  12034. lib$es6$promise$asap$$len += 2;
  12035. if (lib$es6$promise$asap$$len === 2) {
  12036. // If len is 2, that means that we need to schedule an async flush.
  12037. // If additional callbacks are queued before the queue is flushed, they
  12038. // will be processed by this flush that we are scheduling.
  12039. if (lib$es6$promise$asap$$customSchedulerFn) {
  12040. lib$es6$promise$asap$$customSchedulerFn(lib$es6$promise$asap$$flush);
  12041. } else {
  12042. lib$es6$promise$asap$$scheduleFlush();
  12043. }
  12044. }
  12045. }
  12046. function lib$es6$promise$asap$$setScheduler(scheduleFn) {
  12047. lib$es6$promise$asap$$customSchedulerFn = scheduleFn;
  12048. }
  12049. function lib$es6$promise$asap$$setAsap(asapFn) {
  12050. lib$es6$promise$asap$$asap = asapFn;
  12051. }
  12052. var lib$es6$promise$asap$$browserWindow = (typeof window !== 'undefined') ? window : undefined;
  12053. var lib$es6$promise$asap$$browserGlobal = lib$es6$promise$asap$$browserWindow || {};
  12054. var lib$es6$promise$asap$$BrowserMutationObserver = lib$es6$promise$asap$$browserGlobal.MutationObserver || lib$es6$promise$asap$$browserGlobal.WebKitMutationObserver;
  12055. var lib$es6$promise$asap$$isNode = typeof process !== 'undefined' && {}.toString.call(process) === '[object process]';
  12056. // test for web worker but not in IE10
  12057. var lib$es6$promise$asap$$isWorker = typeof Uint8ClampedArray !== 'undefined' &&
  12058. typeof importScripts !== 'undefined' &&
  12059. typeof MessageChannel !== 'undefined';
  12060. // node
  12061. function lib$es6$promise$asap$$useNextTick() {
  12062. // node version 0.10.x displays a deprecation warning when nextTick is used recursively
  12063. // see https://github.com/cujojs/when/issues/410 for details
  12064. return function() {
  12065. process.nextTick(lib$es6$promise$asap$$flush);
  12066. };
  12067. }
  12068. // vertx
  12069. function lib$es6$promise$asap$$useVertxTimer() {
  12070. return function() {
  12071. lib$es6$promise$asap$$vertxNext(lib$es6$promise$asap$$flush);
  12072. };
  12073. }
  12074. function lib$es6$promise$asap$$useMutationObserver() {
  12075. var iterations = 0;
  12076. var observer = new lib$es6$promise$asap$$BrowserMutationObserver(lib$es6$promise$asap$$flush);
  12077. var node = document.createTextNode('');
  12078. observer.observe(node, { characterData: true });
  12079. return function() {
  12080. node.data = (iterations = ++iterations % 2);
  12081. };
  12082. }
  12083. // web worker
  12084. function lib$es6$promise$asap$$useMessageChannel() {
  12085. var channel = new MessageChannel();
  12086. channel.port1.onmessage = lib$es6$promise$asap$$flush;
  12087. return function () {
  12088. channel.port2.postMessage(0);
  12089. };
  12090. }
  12091. function lib$es6$promise$asap$$useSetTimeout() {
  12092. return function() {
  12093. setTimeout(lib$es6$promise$asap$$flush, 1);
  12094. };
  12095. }
  12096. var lib$es6$promise$asap$$queue = new Array(1000);
  12097. function lib$es6$promise$asap$$flush() {
  12098. for (var i = 0; i < lib$es6$promise$asap$$len; i+=2) {
  12099. var callback = lib$es6$promise$asap$$queue[i];
  12100. var arg = lib$es6$promise$asap$$queue[i+1];
  12101. callback(arg);
  12102. lib$es6$promise$asap$$queue[i] = undefined;
  12103. lib$es6$promise$asap$$queue[i+1] = undefined;
  12104. }
  12105. lib$es6$promise$asap$$len = 0;
  12106. }
  12107. function lib$es6$promise$asap$$attemptVertx() {
  12108. try {
  12109. var r = require;
  12110. var vertx = r('vertx');
  12111. lib$es6$promise$asap$$vertxNext = vertx.runOnLoop || vertx.runOnContext;
  12112. return lib$es6$promise$asap$$useVertxTimer();
  12113. } catch(e) {
  12114. return lib$es6$promise$asap$$useSetTimeout();
  12115. }
  12116. }
  12117. var lib$es6$promise$asap$$scheduleFlush;
  12118. // Decide what async method to use to triggering processing of queued callbacks:
  12119. if (lib$es6$promise$asap$$isNode) {
  12120. lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useNextTick();
  12121. } else if (lib$es6$promise$asap$$BrowserMutationObserver) {
  12122. lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useMutationObserver();
  12123. } else if (lib$es6$promise$asap$$isWorker) {
  12124. lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useMessageChannel();
  12125. } else if (lib$es6$promise$asap$$browserWindow === undefined && typeof require === 'function') {
  12126. lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$attemptVertx();
  12127. } else {
  12128. lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useSetTimeout();
  12129. }
  12130. function lib$es6$promise$$internal$$noop() {}
  12131. var lib$es6$promise$$internal$$PENDING = void 0;
  12132. var lib$es6$promise$$internal$$FULFILLED = 1;
  12133. var lib$es6$promise$$internal$$REJECTED = 2;
  12134. var lib$es6$promise$$internal$$GET_THEN_ERROR = new lib$es6$promise$$internal$$ErrorObject();
  12135. function lib$es6$promise$$internal$$selfFulfillment() {
  12136. return new TypeError("You cannot resolve a promise with itself");
  12137. }
  12138. function lib$es6$promise$$internal$$cannotReturnOwn() {
  12139. return new TypeError('A promises callback cannot return that same promise.');
  12140. }
  12141. function lib$es6$promise$$internal$$getThen(promise) {
  12142. try {
  12143. return promise.then;
  12144. } catch(error) {
  12145. lib$es6$promise$$internal$$GET_THEN_ERROR.error = error;
  12146. return lib$es6$promise$$internal$$GET_THEN_ERROR;
  12147. }
  12148. }
  12149. function lib$es6$promise$$internal$$tryThen(then, value, fulfillmentHandler, rejectionHandler) {
  12150. try {
  12151. then.call(value, fulfillmentHandler, rejectionHandler);
  12152. } catch(e) {
  12153. return e;
  12154. }
  12155. }
  12156. function lib$es6$promise$$internal$$handleForeignThenable(promise, thenable, then) {
  12157. lib$es6$promise$asap$$asap(function(promise) {
  12158. var sealed = false;
  12159. var error = lib$es6$promise$$internal$$tryThen(then, thenable, function(value) {
  12160. if (sealed) { return; }
  12161. sealed = true;
  12162. if (thenable !== value) {
  12163. lib$es6$promise$$internal$$resolve(promise, value);
  12164. } else {
  12165. lib$es6$promise$$internal$$fulfill(promise, value);
  12166. }
  12167. }, function(reason) {
  12168. if (sealed) { return; }
  12169. sealed = true;
  12170. lib$es6$promise$$internal$$reject(promise, reason);
  12171. }, 'Settle: ' + (promise._label || ' unknown promise'));
  12172. if (!sealed && error) {
  12173. sealed = true;
  12174. lib$es6$promise$$internal$$reject(promise, error);
  12175. }
  12176. }, promise);
  12177. }
  12178. function lib$es6$promise$$internal$$handleOwnThenable(promise, thenable) {
  12179. if (thenable._state === lib$es6$promise$$internal$$FULFILLED) {
  12180. lib$es6$promise$$internal$$fulfill(promise, thenable._result);
  12181. } else if (thenable._state === lib$es6$promise$$internal$$REJECTED) {
  12182. lib$es6$promise$$internal$$reject(promise, thenable._result);
  12183. } else {
  12184. lib$es6$promise$$internal$$subscribe(thenable, undefined, function(value) {
  12185. lib$es6$promise$$internal$$resolve(promise, value);
  12186. }, function(reason) {
  12187. lib$es6$promise$$internal$$reject(promise, reason);
  12188. });
  12189. }
  12190. }
  12191. function lib$es6$promise$$internal$$handleMaybeThenable(promise, maybeThenable) {
  12192. if (maybeThenable.constructor === promise.constructor) {
  12193. lib$es6$promise$$internal$$handleOwnThenable(promise, maybeThenable);
  12194. } else {
  12195. var then = lib$es6$promise$$internal$$getThen(maybeThenable);
  12196. if (then === lib$es6$promise$$internal$$GET_THEN_ERROR) {
  12197. lib$es6$promise$$internal$$reject(promise, lib$es6$promise$$internal$$GET_THEN_ERROR.error);
  12198. } else if (then === undefined) {
  12199. lib$es6$promise$$internal$$fulfill(promise, maybeThenable);
  12200. } else if (lib$es6$promise$utils$$isFunction(then)) {
  12201. lib$es6$promise$$internal$$handleForeignThenable(promise, maybeThenable, then);
  12202. } else {
  12203. lib$es6$promise$$internal$$fulfill(promise, maybeThenable);
  12204. }
  12205. }
  12206. }
  12207. function lib$es6$promise$$internal$$resolve(promise, value) {
  12208. if (promise === value) {
  12209. lib$es6$promise$$internal$$reject(promise, lib$es6$promise$$internal$$selfFulfillment());
  12210. } else if (lib$es6$promise$utils$$objectOrFunction(value)) {
  12211. lib$es6$promise$$internal$$handleMaybeThenable(promise, value);
  12212. } else {
  12213. lib$es6$promise$$internal$$fulfill(promise, value);
  12214. }
  12215. }
  12216. function lib$es6$promise$$internal$$publishRejection(promise) {
  12217. if (promise._onerror) {
  12218. promise._onerror(promise._result);
  12219. }
  12220. lib$es6$promise$$internal$$publish(promise);
  12221. }
  12222. function lib$es6$promise$$internal$$fulfill(promise, value) {
  12223. if (promise._state !== lib$es6$promise$$internal$$PENDING) { return; }
  12224. promise._result = value;
  12225. promise._state = lib$es6$promise$$internal$$FULFILLED;
  12226. if (promise._subscribers.length !== 0) {
  12227. lib$es6$promise$asap$$asap(lib$es6$promise$$internal$$publish, promise);
  12228. }
  12229. }
  12230. function lib$es6$promise$$internal$$reject(promise, reason) {
  12231. if (promise._state !== lib$es6$promise$$internal$$PENDING) { return; }
  12232. promise._state = lib$es6$promise$$internal$$REJECTED;
  12233. promise._result = reason;
  12234. lib$es6$promise$asap$$asap(lib$es6$promise$$internal$$publishRejection, promise);
  12235. }
  12236. function lib$es6$promise$$internal$$subscribe(parent, child, onFulfillment, onRejection) {
  12237. var subscribers = parent._subscribers;
  12238. var length = subscribers.length;
  12239. parent._onerror = null;
  12240. subscribers[length] = child;
  12241. subscribers[length + lib$es6$promise$$internal$$FULFILLED] = onFulfillment;
  12242. subscribers[length + lib$es6$promise$$internal$$REJECTED] = onRejection;
  12243. if (length === 0 && parent._state) {
  12244. lib$es6$promise$asap$$asap(lib$es6$promise$$internal$$publish, parent);
  12245. }
  12246. }
  12247. function lib$es6$promise$$internal$$publish(promise) {
  12248. var subscribers = promise._subscribers;
  12249. var settled = promise._state;
  12250. if (subscribers.length === 0) { return; }
  12251. var child, callback, detail = promise._result;
  12252. for (var i = 0; i < subscribers.length; i += 3) {
  12253. child = subscribers[i];
  12254. callback = subscribers[i + settled];
  12255. if (child) {
  12256. lib$es6$promise$$internal$$invokeCallback(settled, child, callback, detail);
  12257. } else {
  12258. callback(detail);
  12259. }
  12260. }
  12261. promise._subscribers.length = 0;
  12262. }
  12263. function lib$es6$promise$$internal$$ErrorObject() {
  12264. this.error = null;
  12265. }
  12266. var lib$es6$promise$$internal$$TRY_CATCH_ERROR = new lib$es6$promise$$internal$$ErrorObject();
  12267. function lib$es6$promise$$internal$$tryCatch(callback, detail) {
  12268. try {
  12269. return callback(detail);
  12270. } catch(e) {
  12271. lib$es6$promise$$internal$$TRY_CATCH_ERROR.error = e;
  12272. return lib$es6$promise$$internal$$TRY_CATCH_ERROR;
  12273. }
  12274. }
  12275. function lib$es6$promise$$internal$$invokeCallback(settled, promise, callback, detail) {
  12276. var hasCallback = lib$es6$promise$utils$$isFunction(callback),
  12277. value, error, succeeded, failed;
  12278. if (hasCallback) {
  12279. value = lib$es6$promise$$internal$$tryCatch(callback, detail);
  12280. if (value === lib$es6$promise$$internal$$TRY_CATCH_ERROR) {
  12281. failed = true;
  12282. error = value.error;
  12283. value = null;
  12284. } else {
  12285. succeeded = true;
  12286. }
  12287. if (promise === value) {
  12288. lib$es6$promise$$internal$$reject(promise, lib$es6$promise$$internal$$cannotReturnOwn());
  12289. return;
  12290. }
  12291. } else {
  12292. value = detail;
  12293. succeeded = true;
  12294. }
  12295. if (promise._state !== lib$es6$promise$$internal$$PENDING) {
  12296. // noop
  12297. } else if (hasCallback && succeeded) {
  12298. lib$es6$promise$$internal$$resolve(promise, value);
  12299. } else if (failed) {
  12300. lib$es6$promise$$internal$$reject(promise, error);
  12301. } else if (settled === lib$es6$promise$$internal$$FULFILLED) {
  12302. lib$es6$promise$$internal$$fulfill(promise, value);
  12303. } else if (settled === lib$es6$promise$$internal$$REJECTED) {
  12304. lib$es6$promise$$internal$$reject(promise, value);
  12305. }
  12306. }
  12307. function lib$es6$promise$$internal$$initializePromise(promise, resolver) {
  12308. try {
  12309. resolver(function resolvePromise(value){
  12310. lib$es6$promise$$internal$$resolve(promise, value);
  12311. }, function rejectPromise(reason) {
  12312. lib$es6$promise$$internal$$reject(promise, reason);
  12313. });
  12314. } catch(e) {
  12315. lib$es6$promise$$internal$$reject(promise, e);
  12316. }
  12317. }
  12318. function lib$es6$promise$enumerator$$Enumerator(Constructor, input) {
  12319. var enumerator = this;
  12320. enumerator._instanceConstructor = Constructor;
  12321. enumerator.promise = new Constructor(lib$es6$promise$$internal$$noop);
  12322. if (enumerator._validateInput(input)) {
  12323. enumerator._input = input;
  12324. enumerator.length = input.length;
  12325. enumerator._remaining = input.length;
  12326. enumerator._init();
  12327. if (enumerator.length === 0) {
  12328. lib$es6$promise$$internal$$fulfill(enumerator.promise, enumerator._result);
  12329. } else {
  12330. enumerator.length = enumerator.length || 0;
  12331. enumerator._enumerate();
  12332. if (enumerator._remaining === 0) {
  12333. lib$es6$promise$$internal$$fulfill(enumerator.promise, enumerator._result);
  12334. }
  12335. }
  12336. } else {
  12337. lib$es6$promise$$internal$$reject(enumerator.promise, enumerator._validationError());
  12338. }
  12339. }
  12340. lib$es6$promise$enumerator$$Enumerator.prototype._validateInput = function(input) {
  12341. return lib$es6$promise$utils$$isArray(input);
  12342. };
  12343. lib$es6$promise$enumerator$$Enumerator.prototype._validationError = function() {
  12344. return new Error('Array Methods must be provided an Array');
  12345. };
  12346. lib$es6$promise$enumerator$$Enumerator.prototype._init = function() {
  12347. this._result = new Array(this.length);
  12348. };
  12349. var lib$es6$promise$enumerator$$default = lib$es6$promise$enumerator$$Enumerator;
  12350. lib$es6$promise$enumerator$$Enumerator.prototype._enumerate = function() {
  12351. var enumerator = this;
  12352. var length = enumerator.length;
  12353. var promise = enumerator.promise;
  12354. var input = enumerator._input;
  12355. for (var i = 0; promise._state === lib$es6$promise$$internal$$PENDING && i < length; i++) {
  12356. enumerator._eachEntry(input[i], i);
  12357. }
  12358. };
  12359. lib$es6$promise$enumerator$$Enumerator.prototype._eachEntry = function(entry, i) {
  12360. var enumerator = this;
  12361. var c = enumerator._instanceConstructor;
  12362. if (lib$es6$promise$utils$$isMaybeThenable(entry)) {
  12363. if (entry.constructor === c && entry._state !== lib$es6$promise$$internal$$PENDING) {
  12364. entry._onerror = null;
  12365. enumerator._settledAt(entry._state, i, entry._result);
  12366. } else {
  12367. enumerator._willSettleAt(c.resolve(entry), i);
  12368. }
  12369. } else {
  12370. enumerator._remaining--;
  12371. enumerator._result[i] = entry;
  12372. }
  12373. };
  12374. lib$es6$promise$enumerator$$Enumerator.prototype._settledAt = function(state, i, value) {
  12375. var enumerator = this;
  12376. var promise = enumerator.promise;
  12377. if (promise._state === lib$es6$promise$$internal$$PENDING) {
  12378. enumerator._remaining--;
  12379. if (state === lib$es6$promise$$internal$$REJECTED) {
  12380. lib$es6$promise$$internal$$reject(promise, value);
  12381. } else {
  12382. enumerator._result[i] = value;
  12383. }
  12384. }
  12385. if (enumerator._remaining === 0) {
  12386. lib$es6$promise$$internal$$fulfill(promise, enumerator._result);
  12387. }
  12388. };
  12389. lib$es6$promise$enumerator$$Enumerator.prototype._willSettleAt = function(promise, i) {
  12390. var enumerator = this;
  12391. lib$es6$promise$$internal$$subscribe(promise, undefined, function(value) {
  12392. enumerator._settledAt(lib$es6$promise$$internal$$FULFILLED, i, value);
  12393. }, function(reason) {
  12394. enumerator._settledAt(lib$es6$promise$$internal$$REJECTED, i, reason);
  12395. });
  12396. };
  12397. function lib$es6$promise$promise$all$$all(entries) {
  12398. return new lib$es6$promise$enumerator$$default(this, entries).promise;
  12399. }
  12400. var lib$es6$promise$promise$all$$default = lib$es6$promise$promise$all$$all;
  12401. function lib$es6$promise$promise$race$$race(entries) {
  12402. /*jshint validthis:true */
  12403. var Constructor = this;
  12404. var promise = new Constructor(lib$es6$promise$$internal$$noop);
  12405. if (!lib$es6$promise$utils$$isArray(entries)) {
  12406. lib$es6$promise$$internal$$reject(promise, new TypeError('You must pass an array to race.'));
  12407. return promise;
  12408. }
  12409. var length = entries.length;
  12410. function onFulfillment(value) {
  12411. lib$es6$promise$$internal$$resolve(promise, value);
  12412. }
  12413. function onRejection(reason) {
  12414. lib$es6$promise$$internal$$reject(promise, reason);
  12415. }
  12416. for (var i = 0; promise._state === lib$es6$promise$$internal$$PENDING && i < length; i++) {
  12417. lib$es6$promise$$internal$$subscribe(Constructor.resolve(entries[i]), undefined, onFulfillment, onRejection);
  12418. }
  12419. return promise;
  12420. }
  12421. var lib$es6$promise$promise$race$$default = lib$es6$promise$promise$race$$race;
  12422. function lib$es6$promise$promise$resolve$$resolve(object) {
  12423. /*jshint validthis:true */
  12424. var Constructor = this;
  12425. if (object && typeof object === 'object' && object.constructor === Constructor) {
  12426. return object;
  12427. }
  12428. var promise = new Constructor(lib$es6$promise$$internal$$noop);
  12429. lib$es6$promise$$internal$$resolve(promise, object);
  12430. return promise;
  12431. }
  12432. var lib$es6$promise$promise$resolve$$default = lib$es6$promise$promise$resolve$$resolve;
  12433. function lib$es6$promise$promise$reject$$reject(reason) {
  12434. /*jshint validthis:true */
  12435. var Constructor = this;
  12436. var promise = new Constructor(lib$es6$promise$$internal$$noop);
  12437. lib$es6$promise$$internal$$reject(promise, reason);
  12438. return promise;
  12439. }
  12440. var lib$es6$promise$promise$reject$$default = lib$es6$promise$promise$reject$$reject;
  12441. var lib$es6$promise$promise$$counter = 0;
  12442. function lib$es6$promise$promise$$needsResolver() {
  12443. throw new TypeError('You must pass a resolver function as the first argument to the promise constructor');
  12444. }
  12445. function lib$es6$promise$promise$$needsNew() {
  12446. throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function.");
  12447. }
  12448. var lib$es6$promise$promise$$default = lib$es6$promise$promise$$Promise;
  12449. /**
  12450. Promise objects represent the eventual result of an asynchronous operation. The
  12451. primary way of interacting with a promise is through its `then` method, which
  12452. registers callbacks to receive either a promise's eventual value or the reason
  12453. why the promise cannot be fulfilled.
  12454. Terminology
  12455. -----------
  12456. - `promise` is an object or function with a `then` method whose behavior conforms to this specification.
  12457. - `thenable` is an object or function that defines a `then` method.
  12458. - `value` is any legal JavaScript value (including undefined, a thenable, or a promise).
  12459. - `exception` is a value that is thrown using the throw statement.
  12460. - `reason` is a value that indicates why a promise was rejected.
  12461. - `settled` the final resting state of a promise, fulfilled or rejected.
  12462. A promise can be in one of three states: pending, fulfilled, or rejected.
  12463. Promises that are fulfilled have a fulfillment value and are in the fulfilled
  12464. state. Promises that are rejected have a rejection reason and are in the
  12465. rejected state. A fulfillment value is never a thenable.
  12466. Promises can also be said to *resolve* a value. If this value is also a
  12467. promise, then the original promise's settled state will match the value's
  12468. settled state. So a promise that *resolves* a promise that rejects will
  12469. itself reject, and a promise that *resolves* a promise that fulfills will
  12470. itself fulfill.
  12471. Basic Usage:
  12472. ------------
  12473. ```js
  12474. var promise = new Promise(function(resolve, reject) {
  12475. // on success
  12476. resolve(value);
  12477. // on failure
  12478. reject(reason);
  12479. });
  12480. promise.then(function(value) {
  12481. // on fulfillment
  12482. }, function(reason) {
  12483. // on rejection
  12484. });
  12485. ```
  12486. Advanced Usage:
  12487. ---------------
  12488. Promises shine when abstracting away asynchronous interactions such as
  12489. `XMLHttpRequest`s.
  12490. ```js
  12491. function getJSON(url) {
  12492. return new Promise(function(resolve, reject){
  12493. var xhr = new XMLHttpRequest();
  12494. xhr.open('GET', url);
  12495. xhr.onreadystatechange = handler;
  12496. xhr.responseType = 'json';
  12497. xhr.setRequestHeader('Accept', 'application/json');
  12498. xhr.send();
  12499. function handler() {
  12500. if (this.readyState === this.DONE) {
  12501. if (this.status === 200) {
  12502. resolve(this.response);
  12503. } else {
  12504. reject(new Error('getJSON: `' + url + '` failed with status: [' + this.status + ']'));
  12505. }
  12506. }
  12507. };
  12508. });
  12509. }
  12510. getJSON('/posts.json').then(function(json) {
  12511. // on fulfillment
  12512. }, function(reason) {
  12513. // on rejection
  12514. });
  12515. ```
  12516. Unlike callbacks, promises are great composable primitives.
  12517. ```js
  12518. Promise.all([
  12519. getJSON('/posts'),
  12520. getJSON('/comments')
  12521. ]).then(function(values){
  12522. values[0] // => postsJSON
  12523. values[1] // => commentsJSON
  12524. return values;
  12525. });
  12526. ```
  12527. @class Promise
  12528. @param {function} resolver
  12529. Useful for tooling.
  12530. @constructor
  12531. */
  12532. function lib$es6$promise$promise$$Promise(resolver) {
  12533. this._id = lib$es6$promise$promise$$counter++;
  12534. this._state = undefined;
  12535. this._result = undefined;
  12536. this._subscribers = [];
  12537. if (lib$es6$promise$$internal$$noop !== resolver) {
  12538. if (!lib$es6$promise$utils$$isFunction(resolver)) {
  12539. lib$es6$promise$promise$$needsResolver();
  12540. }
  12541. if (!(this instanceof lib$es6$promise$promise$$Promise)) {
  12542. lib$es6$promise$promise$$needsNew();
  12543. }
  12544. lib$es6$promise$$internal$$initializePromise(this, resolver);
  12545. }
  12546. }
  12547. lib$es6$promise$promise$$Promise.all = lib$es6$promise$promise$all$$default;
  12548. lib$es6$promise$promise$$Promise.race = lib$es6$promise$promise$race$$default;
  12549. lib$es6$promise$promise$$Promise.resolve = lib$es6$promise$promise$resolve$$default;
  12550. lib$es6$promise$promise$$Promise.reject = lib$es6$promise$promise$reject$$default;
  12551. lib$es6$promise$promise$$Promise._setScheduler = lib$es6$promise$asap$$setScheduler;
  12552. lib$es6$promise$promise$$Promise._setAsap = lib$es6$promise$asap$$setAsap;
  12553. lib$es6$promise$promise$$Promise._asap = lib$es6$promise$asap$$asap;
  12554. lib$es6$promise$promise$$Promise.prototype = {
  12555. constructor: lib$es6$promise$promise$$Promise,
  12556. /**
  12557. The primary way of interacting with a promise is through its `then` method,
  12558. which registers callbacks to receive either a promise's eventual value or the
  12559. reason why the promise cannot be fulfilled.
  12560. ```js
  12561. findUser().then(function(user){
  12562. // user is available
  12563. }, function(reason){
  12564. // user is unavailable, and you are given the reason why
  12565. });
  12566. ```
  12567. Chaining
  12568. --------
  12569. The return value of `then` is itself a promise. This second, 'downstream'
  12570. promise is resolved with the return value of the first promise's fulfillment
  12571. or rejection handler, or rejected if the handler throws an exception.
  12572. ```js
  12573. findUser().then(function (user) {
  12574. return user.name;
  12575. }, function (reason) {
  12576. return 'default name';
  12577. }).then(function (userName) {
  12578. // If `findUser` fulfilled, `userName` will be the user's name, otherwise it
  12579. // will be `'default name'`
  12580. });
  12581. findUser().then(function (user) {
  12582. throw new Error('Found user, but still unhappy');
  12583. }, function (reason) {
  12584. throw new Error('`findUser` rejected and we're unhappy');
  12585. }).then(function (value) {
  12586. // never reached
  12587. }, function (reason) {
  12588. // if `findUser` fulfilled, `reason` will be 'Found user, but still unhappy'.
  12589. // If `findUser` rejected, `reason` will be '`findUser` rejected and we're unhappy'.
  12590. });
  12591. ```
  12592. If the downstream promise does not specify a rejection handler, rejection reasons will be propagated further downstream.
  12593. ```js
  12594. findUser().then(function (user) {
  12595. throw new PedagogicalException('Upstream error');
  12596. }).then(function (value) {
  12597. // never reached
  12598. }).then(function (value) {
  12599. // never reached
  12600. }, function (reason) {
  12601. // The `PedgagocialException` is propagated all the way down to here
  12602. });
  12603. ```
  12604. Assimilation
  12605. ------------
  12606. Sometimes the value you want to propagate to a downstream promise can only be
  12607. retrieved asynchronously. This can be achieved by returning a promise in the
  12608. fulfillment or rejection handler. The downstream promise will then be pending
  12609. until the returned promise is settled. This is called *assimilation*.
  12610. ```js
  12611. findUser().then(function (user) {
  12612. return findCommentsByAuthor(user);
  12613. }).then(function (comments) {
  12614. // The user's comments are now available
  12615. });
  12616. ```
  12617. If the assimliated promise rejects, then the downstream promise will also reject.
  12618. ```js
  12619. findUser().then(function (user) {
  12620. return findCommentsByAuthor(user);
  12621. }).then(function (comments) {
  12622. // If `findCommentsByAuthor` fulfills, we'll have the value here
  12623. }, function (reason) {
  12624. // If `findCommentsByAuthor` rejects, we'll have the reason here
  12625. });
  12626. ```
  12627. Simple Example
  12628. --------------
  12629. Synchronous Example
  12630. ```javascript
  12631. var result;
  12632. try {
  12633. result = findResult();
  12634. // success
  12635. } catch(reason) {
  12636. // failure
  12637. }
  12638. ```
  12639. Errback Example
  12640. ```js
  12641. findResult(function(result, err){
  12642. if (err) {
  12643. // failure
  12644. } else {
  12645. // success
  12646. }
  12647. });
  12648. ```
  12649. Promise Example;
  12650. ```javascript
  12651. findResult().then(function(result){
  12652. // success
  12653. }, function(reason){
  12654. // failure
  12655. });
  12656. ```
  12657. Advanced Example
  12658. --------------
  12659. Synchronous Example
  12660. ```javascript
  12661. var author, books;
  12662. try {
  12663. author = findAuthor();
  12664. books = findBooksByAuthor(author);
  12665. // success
  12666. } catch(reason) {
  12667. // failure
  12668. }
  12669. ```
  12670. Errback Example
  12671. ```js
  12672. function foundBooks(books) {
  12673. }
  12674. function failure(reason) {
  12675. }
  12676. findAuthor(function(author, err){
  12677. if (err) {
  12678. failure(err);
  12679. // failure
  12680. } else {
  12681. try {
  12682. findBoooksByAuthor(author, function(books, err) {
  12683. if (err) {
  12684. failure(err);
  12685. } else {
  12686. try {
  12687. foundBooks(books);
  12688. } catch(reason) {
  12689. failure(reason);
  12690. }
  12691. }
  12692. });
  12693. } catch(error) {
  12694. failure(err);
  12695. }
  12696. // success
  12697. }
  12698. });
  12699. ```
  12700. Promise Example;
  12701. ```javascript
  12702. findAuthor().
  12703. then(findBooksByAuthor).
  12704. then(function(books){
  12705. // found books
  12706. }).catch(function(reason){
  12707. // something went wrong
  12708. });
  12709. ```
  12710. @method then
  12711. @param {Function} onFulfilled
  12712. @param {Function} onRejected
  12713. Useful for tooling.
  12714. @return {Promise}
  12715. */
  12716. then: function(onFulfillment, onRejection) {
  12717. var parent = this;
  12718. var state = parent._state;
  12719. if (state === lib$es6$promise$$internal$$FULFILLED && !onFulfillment || state === lib$es6$promise$$internal$$REJECTED && !onRejection) {
  12720. return this;
  12721. }
  12722. var child = new this.constructor(lib$es6$promise$$internal$$noop);
  12723. var result = parent._result;
  12724. if (state) {
  12725. var callback = arguments[state - 1];
  12726. lib$es6$promise$asap$$asap(function(){
  12727. lib$es6$promise$$internal$$invokeCallback(state, child, callback, result);
  12728. });
  12729. } else {
  12730. lib$es6$promise$$internal$$subscribe(parent, child, onFulfillment, onRejection);
  12731. }
  12732. return child;
  12733. },
  12734. /**
  12735. `catch` is simply sugar for `then(undefined, onRejection)` which makes it the same
  12736. as the catch block of a try/catch statement.
  12737. ```js
  12738. function findAuthor(){
  12739. throw new Error('couldn't find that author');
  12740. }
  12741. // synchronous
  12742. try {
  12743. findAuthor();
  12744. } catch(reason) {
  12745. // something went wrong
  12746. }
  12747. // async with promises
  12748. findAuthor().catch(function(reason){
  12749. // something went wrong
  12750. });
  12751. ```
  12752. @method catch
  12753. @param {Function} onRejection
  12754. Useful for tooling.
  12755. @return {Promise}
  12756. */
  12757. 'catch': function(onRejection) {
  12758. return this.then(null, onRejection);
  12759. }
  12760. };
  12761. function lib$es6$promise$polyfill$$polyfill() {
  12762. var local;
  12763. if (typeof global !== 'undefined') {
  12764. local = global;
  12765. } else if (typeof self !== 'undefined') {
  12766. local = self;
  12767. } else {
  12768. try {
  12769. local = Function('return this')();
  12770. } catch (e) {
  12771. throw new Error('polyfill failed because global object is unavailable in this environment');
  12772. }
  12773. }
  12774. var P = local.Promise;
  12775. if (P && Object.prototype.toString.call(P.resolve()) === '[object Promise]' && !P.cast) {
  12776. return;
  12777. }
  12778. local.Promise = lib$es6$promise$promise$$default;
  12779. }
  12780. var lib$es6$promise$polyfill$$default = lib$es6$promise$polyfill$$polyfill;
  12781. var lib$es6$promise$umd$$ES6Promise = {
  12782. 'Promise': lib$es6$promise$promise$$default,
  12783. 'polyfill': lib$es6$promise$polyfill$$default
  12784. };
  12785. /* global define:true module:true window: true */
  12786. if (typeof define === 'function' && define['amd']) {
  12787. define(function() { return lib$es6$promise$umd$$ES6Promise; });
  12788. } else if (typeof module !== 'undefined' && module['exports']) {
  12789. module['exports'] = lib$es6$promise$umd$$ES6Promise;
  12790. } else if (typeof this !== 'undefined') {
  12791. this['ES6Promise'] = lib$es6$promise$umd$$ES6Promise;
  12792. }
  12793. lib$es6$promise$polyfill$$default();
  12794. }).call(this);
  12795. }).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  12796. },{"_process":45}],47:[function(require,module,exports){
  12797. /* Copyright @ 2015 Atlassian Pty Ltd
  12798. *
  12799. * Licensed under the Apache License, Version 2.0 (the "License");
  12800. * you may not use this file except in compliance with the License.
  12801. * You may obtain a copy of the License at
  12802. *
  12803. * http://www.apache.org/licenses/LICENSE-2.0
  12804. *
  12805. * Unless required by applicable law or agreed to in writing, software
  12806. * distributed under the License is distributed on an "AS IS" BASIS,
  12807. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12808. * See the License for the specific language governing permissions and
  12809. * limitations under the License.
  12810. */
  12811. /**
  12812. * Ordered log levels.
  12813. */
  12814. var levels = {
  12815. "trace": 0,
  12816. "debug": 1,
  12817. "info": 2,
  12818. "log": 3,
  12819. "warn": 4,
  12820. "error": 5
  12821. };
  12822. /**
  12823. * Parses Error's object stack trace and extracts information about the last
  12824. * caller before the log method was called.
  12825. * @returns JS object with info about the caller - method name, file location,
  12826. * line and column.
  12827. */
  12828. function getCallerInfo() {
  12829. var callerInfo = {
  12830. methodName: "",
  12831. fileLocation: "",
  12832. line: null,
  12833. column: null
  12834. };
  12835. //gets the part of the stack without the logger wrappers
  12836. var error = new Error();
  12837. var stack = error.stack? error.stack.split("\n") : [];
  12838. if(!stack || stack.length < 1) {
  12839. return callerInfo;
  12840. }
  12841. var m = null;
  12842. if(stack[3]) {
  12843. m = stack[3].match(/\s*at\s*(.+?)\s*\((\S*)\s*:(\d*)\s*:(\d*)\)/);
  12844. }
  12845. if(!m || m.length <= 4) {
  12846. //Firefox && Safari
  12847. if(stack[2].indexOf("log@") === 0){
  12848. //Safari
  12849. callerInfo.methodName = stack[3].substr(0, stack[3].indexOf("@"));
  12850. } else {
  12851. //Firefox
  12852. callerInfo.methodName = stack[2].substr(0, stack[2].indexOf("@"));
  12853. }
  12854. return callerInfo;
  12855. }
  12856. callerInfo.methodName = m[1];
  12857. callerInfo.fileLocation = m[2];
  12858. callerInfo.line = m[3];
  12859. callerInfo.column = m[4];
  12860. return callerInfo;
  12861. }
  12862. /**
  12863. * Logs messages using the transports and level from the logger.
  12864. * @param logger a logger instance.
  12865. * @param level the log level of the message. See the levels variable.
  12866. * @param arguments array with arguments that will be logged.
  12867. */
  12868. function log() {
  12869. var logger = arguments[0], level = arguments[1],
  12870. args = Array.prototype.slice.call(arguments, 2);
  12871. if(levels[level] <= logger.level) {
  12872. return;
  12873. }
  12874. var callerInfo = getCallerInfo();
  12875. for(var i = 0; i < logger.transports.length; i++) {
  12876. var t = logger.transports[i];
  12877. var l = t[level];
  12878. if(l && typeof(l) === "function") {
  12879. l.bind(t, logger.id? "[" + logger.id + "]" : "", "<" + callerInfo.methodName + ">: ")
  12880. .apply(t, args);
  12881. }
  12882. }
  12883. }
  12884. /**
  12885. *
  12886. * Constructs new logger object.
  12887. * @param level the logging level for the new logger
  12888. * @param id optional identifier for the logger instance.
  12889. * @param transports optional list of handlers(objects) for the logs.
  12890. * The handlers must support - log, warn, error, debug, info, trace.
  12891. * @param format optional (NOT implemented) string.
  12892. */
  12893. function Logger(level, id, transports, format) {
  12894. this.id = id;
  12895. this.format = format;
  12896. if(!this.transports) {
  12897. this.transports = [];
  12898. this.transports.push(Logger.consoleTransport);
  12899. }
  12900. this.level = levels[level];
  12901. var methods = Object.keys(levels);
  12902. for(var i = 0; i < methods.length; i++){
  12903. this[methods[i]] =
  12904. log.bind(null, this, methods[i]);
  12905. }
  12906. }
  12907. /**
  12908. * Sets the log level for the logger.
  12909. * @param level the new log level.
  12910. */
  12911. Logger.prototype.setLevel = function (level) {
  12912. this.level = levels[level];
  12913. };
  12914. module.exports = Logger;
  12915. /**
  12916. * The default transport - console
  12917. */
  12918. Logger.consoleTransport = console;
  12919. /**
  12920. * Enum for the supported log levels.
  12921. */
  12922. Logger.levels = {
  12923. TRACE: "trace",
  12924. DEBUG: "debug",
  12925. INFO: "info",
  12926. LOG: "log",
  12927. WARN: "warn",
  12928. ERROR: "error"
  12929. };
  12930. },{}],48:[function(require,module,exports){
  12931. /* Copyright @ 2015 Atlassian Pty Ltd
  12932. *
  12933. * Licensed under the Apache License, Version 2.0 (the "License");
  12934. * you may not use this file except in compliance with the License.
  12935. * You may obtain a copy of the License at
  12936. *
  12937. * http://www.apache.org/licenses/LICENSE-2.0
  12938. *
  12939. * Unless required by applicable law or agreed to in writing, software
  12940. * distributed under the License is distributed on an "AS IS" BASIS,
  12941. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12942. * See the License for the specific language governing permissions and
  12943. * limitations under the License.
  12944. */
  12945. var Logger = require("./Logger");
  12946. /**
  12947. * Map with the created loggers with ID.
  12948. */
  12949. var idLoggers = {};
  12950. /**
  12951. * Array with the loggers without id.
  12952. */
  12953. var loggers = [];
  12954. /**
  12955. * Log level for the lbrary.
  12956. */
  12957. var curLevel = Logger.levels.TRACE;
  12958. module.exports = {
  12959. /**
  12960. * Creates new logger.
  12961. * @arguments the same as Logger constructor
  12962. */
  12963. getLogger: function(id, transports, format) {
  12964. var logger = new Logger(curLevel, id, transports, format);
  12965. if(id) {
  12966. idLoggers[id] = idLoggers[id] || [];
  12967. idLoggers[id].push(logger);
  12968. } else {
  12969. loggers.push(logger);
  12970. }
  12971. return logger;
  12972. },
  12973. /**
  12974. * Changes the log level for the existing loggers by id.
  12975. * @param level the new log level.
  12976. * @param id if specified the level will be changed only for loggers with the
  12977. * same id. Otherwise the operation will affect all loggers that don't
  12978. * have id.
  12979. */
  12980. setLogLevelById: function(level, id) {
  12981. var l = id? (idLoggers[id] || []) : loggers;
  12982. for(var i = 0; i < l.length; i++) {
  12983. l[i].setLevel(level);
  12984. }
  12985. },
  12986. /**
  12987. * Changes the log level for all existing loggers.
  12988. * @param level the new log level.
  12989. */
  12990. setLogLevel: function (level) {
  12991. curLevel = level;
  12992. var i = 0;
  12993. for(; i < loggers.length; i++) {
  12994. loggers[i].setLevel(level);
  12995. }
  12996. for(var id in idLoggers) {
  12997. var l = idLoggers[id] || [];
  12998. for(i = 0; i < l.length; i++) {
  12999. l[i].setLevel(level);
  13000. }
  13001. }
  13002. },
  13003. /**
  13004. * The supported log levels.
  13005. */
  13006. levels: Logger.levels
  13007. };
  13008. },{"./Logger":47}],49:[function(require,module,exports){
  13009. // Top level file is just a mixin of submodules & constants
  13010. 'use strict';
  13011. var assign = require('./lib/utils/common').assign;
  13012. var deflate = require('./lib/deflate');
  13013. var inflate = require('./lib/inflate');
  13014. var constants = require('./lib/zlib/constants');
  13015. var pako = {};
  13016. assign(pako, deflate, inflate, constants);
  13017. module.exports = pako;
  13018. },{"./lib/deflate":50,"./lib/inflate":51,"./lib/utils/common":52,"./lib/zlib/constants":55}],50:[function(require,module,exports){
  13019. 'use strict';
  13020. var zlib_deflate = require('./zlib/deflate.js');
  13021. var utils = require('./utils/common');
  13022. var strings = require('./utils/strings');
  13023. var msg = require('./zlib/messages');
  13024. var zstream = require('./zlib/zstream');
  13025. var toString = Object.prototype.toString;
  13026. /* Public constants ==========================================================*/
  13027. /* ===========================================================================*/
  13028. var Z_NO_FLUSH = 0;
  13029. var Z_FINISH = 4;
  13030. var Z_OK = 0;
  13031. var Z_STREAM_END = 1;
  13032. var Z_SYNC_FLUSH = 2;
  13033. var Z_DEFAULT_COMPRESSION = -1;
  13034. var Z_DEFAULT_STRATEGY = 0;
  13035. var Z_DEFLATED = 8;
  13036. /* ===========================================================================*/
  13037. /**
  13038. * class Deflate
  13039. *
  13040. * Generic JS-style wrapper for zlib calls. If you don't need
  13041. * streaming behaviour - use more simple functions: [[deflate]],
  13042. * [[deflateRaw]] and [[gzip]].
  13043. **/
  13044. /* internal
  13045. * Deflate.chunks -> Array
  13046. *
  13047. * Chunks of output data, if [[Deflate#onData]] not overriden.
  13048. **/
  13049. /**
  13050. * Deflate.result -> Uint8Array|Array
  13051. *
  13052. * Compressed result, generated by default [[Deflate#onData]]
  13053. * and [[Deflate#onEnd]] handlers. Filled after you push last chunk
  13054. * (call [[Deflate#push]] with `Z_FINISH` / `true` param) or if you
  13055. * push a chunk with explicit flush (call [[Deflate#push]] with
  13056. * `Z_SYNC_FLUSH` param).
  13057. **/
  13058. /**
  13059. * Deflate.err -> Number
  13060. *
  13061. * Error code after deflate finished. 0 (Z_OK) on success.
  13062. * You will not need it in real life, because deflate errors
  13063. * are possible only on wrong options or bad `onData` / `onEnd`
  13064. * custom handlers.
  13065. **/
  13066. /**
  13067. * Deflate.msg -> String
  13068. *
  13069. * Error message, if [[Deflate.err]] != 0
  13070. **/
  13071. /**
  13072. * new Deflate(options)
  13073. * - options (Object): zlib deflate options.
  13074. *
  13075. * Creates new deflator instance with specified params. Throws exception
  13076. * on bad params. Supported options:
  13077. *
  13078. * - `level`
  13079. * - `windowBits`
  13080. * - `memLevel`
  13081. * - `strategy`
  13082. *
  13083. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  13084. * for more information on these.
  13085. *
  13086. * Additional options, for internal needs:
  13087. *
  13088. * - `chunkSize` - size of generated data chunks (16K by default)
  13089. * - `raw` (Boolean) - do raw deflate
  13090. * - `gzip` (Boolean) - create gzip wrapper
  13091. * - `to` (String) - if equal to 'string', then result will be "binary string"
  13092. * (each char code [0..255])
  13093. * - `header` (Object) - custom header for gzip
  13094. * - `text` (Boolean) - true if compressed data believed to be text
  13095. * - `time` (Number) - modification time, unix timestamp
  13096. * - `os` (Number) - operation system code
  13097. * - `extra` (Array) - array of bytes with extra data (max 65536)
  13098. * - `name` (String) - file name (binary string)
  13099. * - `comment` (String) - comment (binary string)
  13100. * - `hcrc` (Boolean) - true if header crc should be added
  13101. *
  13102. * ##### Example:
  13103. *
  13104. * ```javascript
  13105. * var pako = require('pako')
  13106. * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
  13107. * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
  13108. *
  13109. * var deflate = new pako.Deflate({ level: 3});
  13110. *
  13111. * deflate.push(chunk1, false);
  13112. * deflate.push(chunk2, true); // true -> last chunk
  13113. *
  13114. * if (deflate.err) { throw new Error(deflate.err); }
  13115. *
  13116. * console.log(deflate.result);
  13117. * ```
  13118. **/
  13119. var Deflate = function(options) {
  13120. this.options = utils.assign({
  13121. level: Z_DEFAULT_COMPRESSION,
  13122. method: Z_DEFLATED,
  13123. chunkSize: 16384,
  13124. windowBits: 15,
  13125. memLevel: 8,
  13126. strategy: Z_DEFAULT_STRATEGY,
  13127. to: ''
  13128. }, options || {});
  13129. var opt = this.options;
  13130. if (opt.raw && (opt.windowBits > 0)) {
  13131. opt.windowBits = -opt.windowBits;
  13132. }
  13133. else if (opt.gzip && (opt.windowBits > 0) && (opt.windowBits < 16)) {
  13134. opt.windowBits += 16;
  13135. }
  13136. this.err = 0; // error code, if happens (0 = Z_OK)
  13137. this.msg = ''; // error message
  13138. this.ended = false; // used to avoid multiple onEnd() calls
  13139. this.chunks = []; // chunks of compressed data
  13140. this.strm = new zstream();
  13141. this.strm.avail_out = 0;
  13142. var status = zlib_deflate.deflateInit2(
  13143. this.strm,
  13144. opt.level,
  13145. opt.method,
  13146. opt.windowBits,
  13147. opt.memLevel,
  13148. opt.strategy
  13149. );
  13150. if (status !== Z_OK) {
  13151. throw new Error(msg[status]);
  13152. }
  13153. if (opt.header) {
  13154. zlib_deflate.deflateSetHeader(this.strm, opt.header);
  13155. }
  13156. };
  13157. /**
  13158. * Deflate#push(data[, mode]) -> Boolean
  13159. * - data (Uint8Array|Array|ArrayBuffer|String): input data. Strings will be
  13160. * converted to utf8 byte sequence.
  13161. * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
  13162. * See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH.
  13163. *
  13164. * Sends input data to deflate pipe, generating [[Deflate#onData]] calls with
  13165. * new compressed chunks. Returns `true` on success. The last data block must have
  13166. * mode Z_FINISH (or `true`). That will flush internal pending buffers and call
  13167. * [[Deflate#onEnd]]. For interim explicit flushes (without ending the stream) you
  13168. * can use mode Z_SYNC_FLUSH, keeping the compression context.
  13169. *
  13170. * On fail call [[Deflate#onEnd]] with error code and return false.
  13171. *
  13172. * We strongly recommend to use `Uint8Array` on input for best speed (output
  13173. * array format is detected automatically). Also, don't skip last param and always
  13174. * use the same type in your code (boolean or number). That will improve JS speed.
  13175. *
  13176. * For regular `Array`-s make sure all elements are [0..255].
  13177. *
  13178. * ##### Example
  13179. *
  13180. * ```javascript
  13181. * push(chunk, false); // push one of data chunks
  13182. * ...
  13183. * push(chunk, true); // push last chunk
  13184. * ```
  13185. **/
  13186. Deflate.prototype.push = function(data, mode) {
  13187. var strm = this.strm;
  13188. var chunkSize = this.options.chunkSize;
  13189. var status, _mode;
  13190. if (this.ended) { return false; }
  13191. _mode = (mode === ~~mode) ? mode : ((mode === true) ? Z_FINISH : Z_NO_FLUSH);
  13192. // Convert data if needed
  13193. if (typeof data === 'string') {
  13194. // If we need to compress text, change encoding to utf8.
  13195. strm.input = strings.string2buf(data);
  13196. } else if (toString.call(data) === '[object ArrayBuffer]') {
  13197. strm.input = new Uint8Array(data);
  13198. } else {
  13199. strm.input = data;
  13200. }
  13201. strm.next_in = 0;
  13202. strm.avail_in = strm.input.length;
  13203. do {
  13204. if (strm.avail_out === 0) {
  13205. strm.output = new utils.Buf8(chunkSize);
  13206. strm.next_out = 0;
  13207. strm.avail_out = chunkSize;
  13208. }
  13209. status = zlib_deflate.deflate(strm, _mode); /* no bad return value */
  13210. if (status !== Z_STREAM_END && status !== Z_OK) {
  13211. this.onEnd(status);
  13212. this.ended = true;
  13213. return false;
  13214. }
  13215. if (strm.avail_out === 0 || (strm.avail_in === 0 && (_mode === Z_FINISH || _mode === Z_SYNC_FLUSH))) {
  13216. if (this.options.to === 'string') {
  13217. this.onData(strings.buf2binstring(utils.shrinkBuf(strm.output, strm.next_out)));
  13218. } else {
  13219. this.onData(utils.shrinkBuf(strm.output, strm.next_out));
  13220. }
  13221. }
  13222. } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== Z_STREAM_END);
  13223. // Finalize on the last chunk.
  13224. if (_mode === Z_FINISH) {
  13225. status = zlib_deflate.deflateEnd(this.strm);
  13226. this.onEnd(status);
  13227. this.ended = true;
  13228. return status === Z_OK;
  13229. }
  13230. // callback interim results if Z_SYNC_FLUSH.
  13231. if (_mode === Z_SYNC_FLUSH) {
  13232. this.onEnd(Z_OK);
  13233. strm.avail_out = 0;
  13234. return true;
  13235. }
  13236. return true;
  13237. };
  13238. /**
  13239. * Deflate#onData(chunk) -> Void
  13240. * - chunk (Uint8Array|Array|String): ouput data. Type of array depends
  13241. * on js engine support. When string output requested, each chunk
  13242. * will be string.
  13243. *
  13244. * By default, stores data blocks in `chunks[]` property and glue
  13245. * those in `onEnd`. Override this handler, if you need another behaviour.
  13246. **/
  13247. Deflate.prototype.onData = function(chunk) {
  13248. this.chunks.push(chunk);
  13249. };
  13250. /**
  13251. * Deflate#onEnd(status) -> Void
  13252. * - status (Number): deflate status. 0 (Z_OK) on success,
  13253. * other if not.
  13254. *
  13255. * Called once after you tell deflate that the input stream is
  13256. * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH)
  13257. * or if an error happened. By default - join collected chunks,
  13258. * free memory and fill `results` / `err` properties.
  13259. **/
  13260. Deflate.prototype.onEnd = function(status) {
  13261. // On success - join
  13262. if (status === Z_OK) {
  13263. if (this.options.to === 'string') {
  13264. this.result = this.chunks.join('');
  13265. } else {
  13266. this.result = utils.flattenChunks(this.chunks);
  13267. }
  13268. }
  13269. this.chunks = [];
  13270. this.err = status;
  13271. this.msg = this.strm.msg;
  13272. };
  13273. /**
  13274. * deflate(data[, options]) -> Uint8Array|Array|String
  13275. * - data (Uint8Array|Array|String): input data to compress.
  13276. * - options (Object): zlib deflate options.
  13277. *
  13278. * Compress `data` with deflate alrorythm and `options`.
  13279. *
  13280. * Supported options are:
  13281. *
  13282. * - level
  13283. * - windowBits
  13284. * - memLevel
  13285. * - strategy
  13286. *
  13287. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  13288. * for more information on these.
  13289. *
  13290. * Sugar (options):
  13291. *
  13292. * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
  13293. * negative windowBits implicitly.
  13294. * - `to` (String) - if equal to 'string', then result will be "binary string"
  13295. * (each char code [0..255])
  13296. *
  13297. * ##### Example:
  13298. *
  13299. * ```javascript
  13300. * var pako = require('pako')
  13301. * , data = Uint8Array([1,2,3,4,5,6,7,8,9]);
  13302. *
  13303. * console.log(pako.deflate(data));
  13304. * ```
  13305. **/
  13306. function deflate(input, options) {
  13307. var deflator = new Deflate(options);
  13308. deflator.push(input, true);
  13309. // That will never happens, if you don't cheat with options :)
  13310. if (deflator.err) { throw deflator.msg; }
  13311. return deflator.result;
  13312. }
  13313. /**
  13314. * deflateRaw(data[, options]) -> Uint8Array|Array|String
  13315. * - data (Uint8Array|Array|String): input data to compress.
  13316. * - options (Object): zlib deflate options.
  13317. *
  13318. * The same as [[deflate]], but creates raw data, without wrapper
  13319. * (header and adler32 crc).
  13320. **/
  13321. function deflateRaw(input, options) {
  13322. options = options || {};
  13323. options.raw = true;
  13324. return deflate(input, options);
  13325. }
  13326. /**
  13327. * gzip(data[, options]) -> Uint8Array|Array|String
  13328. * - data (Uint8Array|Array|String): input data to compress.
  13329. * - options (Object): zlib deflate options.
  13330. *
  13331. * The same as [[deflate]], but create gzip wrapper instead of
  13332. * deflate one.
  13333. **/
  13334. function gzip(input, options) {
  13335. options = options || {};
  13336. options.gzip = true;
  13337. return deflate(input, options);
  13338. }
  13339. exports.Deflate = Deflate;
  13340. exports.deflate = deflate;
  13341. exports.deflateRaw = deflateRaw;
  13342. exports.gzip = gzip;
  13343. },{"./utils/common":52,"./utils/strings":53,"./zlib/deflate.js":57,"./zlib/messages":62,"./zlib/zstream":64}],51:[function(require,module,exports){
  13344. 'use strict';
  13345. var zlib_inflate = require('./zlib/inflate.js');
  13346. var utils = require('./utils/common');
  13347. var strings = require('./utils/strings');
  13348. var c = require('./zlib/constants');
  13349. var msg = require('./zlib/messages');
  13350. var zstream = require('./zlib/zstream');
  13351. var gzheader = require('./zlib/gzheader');
  13352. var toString = Object.prototype.toString;
  13353. /**
  13354. * class Inflate
  13355. *
  13356. * Generic JS-style wrapper for zlib calls. If you don't need
  13357. * streaming behaviour - use more simple functions: [[inflate]]
  13358. * and [[inflateRaw]].
  13359. **/
  13360. /* internal
  13361. * inflate.chunks -> Array
  13362. *
  13363. * Chunks of output data, if [[Inflate#onData]] not overriden.
  13364. **/
  13365. /**
  13366. * Inflate.result -> Uint8Array|Array|String
  13367. *
  13368. * Uncompressed result, generated by default [[Inflate#onData]]
  13369. * and [[Inflate#onEnd]] handlers. Filled after you push last chunk
  13370. * (call [[Inflate#push]] with `Z_FINISH` / `true` param) or if you
  13371. * push a chunk with explicit flush (call [[Inflate#push]] with
  13372. * `Z_SYNC_FLUSH` param).
  13373. **/
  13374. /**
  13375. * Inflate.err -> Number
  13376. *
  13377. * Error code after inflate finished. 0 (Z_OK) on success.
  13378. * Should be checked if broken data possible.
  13379. **/
  13380. /**
  13381. * Inflate.msg -> String
  13382. *
  13383. * Error message, if [[Inflate.err]] != 0
  13384. **/
  13385. /**
  13386. * new Inflate(options)
  13387. * - options (Object): zlib inflate options.
  13388. *
  13389. * Creates new inflator instance with specified params. Throws exception
  13390. * on bad params. Supported options:
  13391. *
  13392. * - `windowBits`
  13393. *
  13394. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  13395. * for more information on these.
  13396. *
  13397. * Additional options, for internal needs:
  13398. *
  13399. * - `chunkSize` - size of generated data chunks (16K by default)
  13400. * - `raw` (Boolean) - do raw inflate
  13401. * - `to` (String) - if equal to 'string', then result will be converted
  13402. * from utf8 to utf16 (javascript) string. When string output requested,
  13403. * chunk length can differ from `chunkSize`, depending on content.
  13404. *
  13405. * By default, when no options set, autodetect deflate/gzip data format via
  13406. * wrapper header.
  13407. *
  13408. * ##### Example:
  13409. *
  13410. * ```javascript
  13411. * var pako = require('pako')
  13412. * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
  13413. * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
  13414. *
  13415. * var inflate = new pako.Inflate({ level: 3});
  13416. *
  13417. * inflate.push(chunk1, false);
  13418. * inflate.push(chunk2, true); // true -> last chunk
  13419. *
  13420. * if (inflate.err) { throw new Error(inflate.err); }
  13421. *
  13422. * console.log(inflate.result);
  13423. * ```
  13424. **/
  13425. var Inflate = function(options) {
  13426. this.options = utils.assign({
  13427. chunkSize: 16384,
  13428. windowBits: 0,
  13429. to: ''
  13430. }, options || {});
  13431. var opt = this.options;
  13432. // Force window size for `raw` data, if not set directly,
  13433. // because we have no header for autodetect.
  13434. if (opt.raw && (opt.windowBits >= 0) && (opt.windowBits < 16)) {
  13435. opt.windowBits = -opt.windowBits;
  13436. if (opt.windowBits === 0) { opt.windowBits = -15; }
  13437. }
  13438. // If `windowBits` not defined (and mode not raw) - set autodetect flag for gzip/deflate
  13439. if ((opt.windowBits >= 0) && (opt.windowBits < 16) &&
  13440. !(options && options.windowBits)) {
  13441. opt.windowBits += 32;
  13442. }
  13443. // Gzip header has no info about windows size, we can do autodetect only
  13444. // for deflate. So, if window size not set, force it to max when gzip possible
  13445. if ((opt.windowBits > 15) && (opt.windowBits < 48)) {
  13446. // bit 3 (16) -> gzipped data
  13447. // bit 4 (32) -> autodetect gzip/deflate
  13448. if ((opt.windowBits & 15) === 0) {
  13449. opt.windowBits |= 15;
  13450. }
  13451. }
  13452. this.err = 0; // error code, if happens (0 = Z_OK)
  13453. this.msg = ''; // error message
  13454. this.ended = false; // used to avoid multiple onEnd() calls
  13455. this.chunks = []; // chunks of compressed data
  13456. this.strm = new zstream();
  13457. this.strm.avail_out = 0;
  13458. var status = zlib_inflate.inflateInit2(
  13459. this.strm,
  13460. opt.windowBits
  13461. );
  13462. if (status !== c.Z_OK) {
  13463. throw new Error(msg[status]);
  13464. }
  13465. this.header = new gzheader();
  13466. zlib_inflate.inflateGetHeader(this.strm, this.header);
  13467. };
  13468. /**
  13469. * Inflate#push(data[, mode]) -> Boolean
  13470. * - data (Uint8Array|Array|ArrayBuffer|String): input data
  13471. * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
  13472. * See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH.
  13473. *
  13474. * Sends input data to inflate pipe, generating [[Inflate#onData]] calls with
  13475. * new output chunks. Returns `true` on success. The last data block must have
  13476. * mode Z_FINISH (or `true`). That will flush internal pending buffers and call
  13477. * [[Inflate#onEnd]]. For interim explicit flushes (without ending the stream) you
  13478. * can use mode Z_SYNC_FLUSH, keeping the decompression context.
  13479. *
  13480. * On fail call [[Inflate#onEnd]] with error code and return false.
  13481. *
  13482. * We strongly recommend to use `Uint8Array` on input for best speed (output
  13483. * format is detected automatically). Also, don't skip last param and always
  13484. * use the same type in your code (boolean or number). That will improve JS speed.
  13485. *
  13486. * For regular `Array`-s make sure all elements are [0..255].
  13487. *
  13488. * ##### Example
  13489. *
  13490. * ```javascript
  13491. * push(chunk, false); // push one of data chunks
  13492. * ...
  13493. * push(chunk, true); // push last chunk
  13494. * ```
  13495. **/
  13496. Inflate.prototype.push = function(data, mode) {
  13497. var strm = this.strm;
  13498. var chunkSize = this.options.chunkSize;
  13499. var status, _mode;
  13500. var next_out_utf8, tail, utf8str;
  13501. // Flag to properly process Z_BUF_ERROR on testing inflate call
  13502. // when we check that all output data was flushed.
  13503. var allowBufError = false;
  13504. if (this.ended) { return false; }
  13505. _mode = (mode === ~~mode) ? mode : ((mode === true) ? c.Z_FINISH : c.Z_NO_FLUSH);
  13506. // Convert data if needed
  13507. if (typeof data === 'string') {
  13508. // Only binary strings can be decompressed on practice
  13509. strm.input = strings.binstring2buf(data);
  13510. } else if (toString.call(data) === '[object ArrayBuffer]') {
  13511. strm.input = new Uint8Array(data);
  13512. } else {
  13513. strm.input = data;
  13514. }
  13515. strm.next_in = 0;
  13516. strm.avail_in = strm.input.length;
  13517. do {
  13518. if (strm.avail_out === 0) {
  13519. strm.output = new utils.Buf8(chunkSize);
  13520. strm.next_out = 0;
  13521. strm.avail_out = chunkSize;
  13522. }
  13523. status = zlib_inflate.inflate(strm, c.Z_NO_FLUSH); /* no bad return value */
  13524. if (status === c.Z_BUF_ERROR && allowBufError === true) {
  13525. status = c.Z_OK;
  13526. allowBufError = false;
  13527. }
  13528. if (status !== c.Z_STREAM_END && status !== c.Z_OK) {
  13529. this.onEnd(status);
  13530. this.ended = true;
  13531. return false;
  13532. }
  13533. if (strm.next_out) {
  13534. if (strm.avail_out === 0 || status === c.Z_STREAM_END || (strm.avail_in === 0 && (_mode === c.Z_FINISH || _mode === c.Z_SYNC_FLUSH))) {
  13535. if (this.options.to === 'string') {
  13536. next_out_utf8 = strings.utf8border(strm.output, strm.next_out);
  13537. tail = strm.next_out - next_out_utf8;
  13538. utf8str = strings.buf2string(strm.output, next_out_utf8);
  13539. // move tail
  13540. strm.next_out = tail;
  13541. strm.avail_out = chunkSize - tail;
  13542. if (tail) { utils.arraySet(strm.output, strm.output, next_out_utf8, tail, 0); }
  13543. this.onData(utf8str);
  13544. } else {
  13545. this.onData(utils.shrinkBuf(strm.output, strm.next_out));
  13546. }
  13547. }
  13548. }
  13549. // When no more input data, we should check that internal inflate buffers
  13550. // are flushed. The only way to do it when avail_out = 0 - run one more
  13551. // inflate pass. But if output data not exists, inflate return Z_BUF_ERROR.
  13552. // Here we set flag to process this error properly.
  13553. //
  13554. // NOTE. Deflate does not return error in this case and does not needs such
  13555. // logic.
  13556. if (strm.avail_in === 0 && strm.avail_out === 0) {
  13557. allowBufError = true;
  13558. }
  13559. } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== c.Z_STREAM_END);
  13560. if (status === c.Z_STREAM_END) {
  13561. _mode = c.Z_FINISH;
  13562. }
  13563. // Finalize on the last chunk.
  13564. if (_mode === c.Z_FINISH) {
  13565. status = zlib_inflate.inflateEnd(this.strm);
  13566. this.onEnd(status);
  13567. this.ended = true;
  13568. return status === c.Z_OK;
  13569. }
  13570. // callback interim results if Z_SYNC_FLUSH.
  13571. if (_mode === c.Z_SYNC_FLUSH) {
  13572. this.onEnd(c.Z_OK);
  13573. strm.avail_out = 0;
  13574. return true;
  13575. }
  13576. return true;
  13577. };
  13578. /**
  13579. * Inflate#onData(chunk) -> Void
  13580. * - chunk (Uint8Array|Array|String): ouput data. Type of array depends
  13581. * on js engine support. When string output requested, each chunk
  13582. * will be string.
  13583. *
  13584. * By default, stores data blocks in `chunks[]` property and glue
  13585. * those in `onEnd`. Override this handler, if you need another behaviour.
  13586. **/
  13587. Inflate.prototype.onData = function(chunk) {
  13588. this.chunks.push(chunk);
  13589. };
  13590. /**
  13591. * Inflate#onEnd(status) -> Void
  13592. * - status (Number): inflate status. 0 (Z_OK) on success,
  13593. * other if not.
  13594. *
  13595. * Called either after you tell inflate that the input stream is
  13596. * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH)
  13597. * or if an error happened. By default - join collected chunks,
  13598. * free memory and fill `results` / `err` properties.
  13599. **/
  13600. Inflate.prototype.onEnd = function(status) {
  13601. // On success - join
  13602. if (status === c.Z_OK) {
  13603. if (this.options.to === 'string') {
  13604. // Glue & convert here, until we teach pako to send
  13605. // utf8 alligned strings to onData
  13606. this.result = this.chunks.join('');
  13607. } else {
  13608. this.result = utils.flattenChunks(this.chunks);
  13609. }
  13610. }
  13611. this.chunks = [];
  13612. this.err = status;
  13613. this.msg = this.strm.msg;
  13614. };
  13615. /**
  13616. * inflate(data[, options]) -> Uint8Array|Array|String
  13617. * - data (Uint8Array|Array|String): input data to decompress.
  13618. * - options (Object): zlib inflate options.
  13619. *
  13620. * Decompress `data` with inflate/ungzip and `options`. Autodetect
  13621. * format via wrapper header by default. That's why we don't provide
  13622. * separate `ungzip` method.
  13623. *
  13624. * Supported options are:
  13625. *
  13626. * - windowBits
  13627. *
  13628. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  13629. * for more information.
  13630. *
  13631. * Sugar (options):
  13632. *
  13633. * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
  13634. * negative windowBits implicitly.
  13635. * - `to` (String) - if equal to 'string', then result will be converted
  13636. * from utf8 to utf16 (javascript) string. When string output requested,
  13637. * chunk length can differ from `chunkSize`, depending on content.
  13638. *
  13639. *
  13640. * ##### Example:
  13641. *
  13642. * ```javascript
  13643. * var pako = require('pako')
  13644. * , input = pako.deflate([1,2,3,4,5,6,7,8,9])
  13645. * , output;
  13646. *
  13647. * try {
  13648. * output = pako.inflate(input);
  13649. * } catch (err)
  13650. * console.log(err);
  13651. * }
  13652. * ```
  13653. **/
  13654. function inflate(input, options) {
  13655. var inflator = new Inflate(options);
  13656. inflator.push(input, true);
  13657. // That will never happens, if you don't cheat with options :)
  13658. if (inflator.err) { throw inflator.msg; }
  13659. return inflator.result;
  13660. }
  13661. /**
  13662. * inflateRaw(data[, options]) -> Uint8Array|Array|String
  13663. * - data (Uint8Array|Array|String): input data to decompress.
  13664. * - options (Object): zlib inflate options.
  13665. *
  13666. * The same as [[inflate]], but creates raw data, without wrapper
  13667. * (header and adler32 crc).
  13668. **/
  13669. function inflateRaw(input, options) {
  13670. options = options || {};
  13671. options.raw = true;
  13672. return inflate(input, options);
  13673. }
  13674. /**
  13675. * ungzip(data[, options]) -> Uint8Array|Array|String
  13676. * - data (Uint8Array|Array|String): input data to decompress.
  13677. * - options (Object): zlib inflate options.
  13678. *
  13679. * Just shortcut to [[inflate]], because it autodetects format
  13680. * by header.content. Done for convenience.
  13681. **/
  13682. exports.Inflate = Inflate;
  13683. exports.inflate = inflate;
  13684. exports.inflateRaw = inflateRaw;
  13685. exports.ungzip = inflate;
  13686. },{"./utils/common":52,"./utils/strings":53,"./zlib/constants":55,"./zlib/gzheader":58,"./zlib/inflate.js":60,"./zlib/messages":62,"./zlib/zstream":64}],52:[function(require,module,exports){
  13687. 'use strict';
  13688. var TYPED_OK = (typeof Uint8Array !== 'undefined') &&
  13689. (typeof Uint16Array !== 'undefined') &&
  13690. (typeof Int32Array !== 'undefined');
  13691. exports.assign = function (obj /*from1, from2, from3, ...*/) {
  13692. var sources = Array.prototype.slice.call(arguments, 1);
  13693. while (sources.length) {
  13694. var source = sources.shift();
  13695. if (!source) { continue; }
  13696. if (typeof source !== 'object') {
  13697. throw new TypeError(source + 'must be non-object');
  13698. }
  13699. for (var p in source) {
  13700. if (source.hasOwnProperty(p)) {
  13701. obj[p] = source[p];
  13702. }
  13703. }
  13704. }
  13705. return obj;
  13706. };
  13707. // reduce buffer size, avoiding mem copy
  13708. exports.shrinkBuf = function (buf, size) {
  13709. if (buf.length === size) { return buf; }
  13710. if (buf.subarray) { return buf.subarray(0, size); }
  13711. buf.length = size;
  13712. return buf;
  13713. };
  13714. var fnTyped = {
  13715. arraySet: function (dest, src, src_offs, len, dest_offs) {
  13716. if (src.subarray && dest.subarray) {
  13717. dest.set(src.subarray(src_offs, src_offs+len), dest_offs);
  13718. return;
  13719. }
  13720. // Fallback to ordinary array
  13721. for (var i=0; i<len; i++) {
  13722. dest[dest_offs + i] = src[src_offs + i];
  13723. }
  13724. },
  13725. // Join array of chunks to single array.
  13726. flattenChunks: function(chunks) {
  13727. var i, l, len, pos, chunk, result;
  13728. // calculate data length
  13729. len = 0;
  13730. for (i=0, l=chunks.length; i<l; i++) {
  13731. len += chunks[i].length;
  13732. }
  13733. // join chunks
  13734. result = new Uint8Array(len);
  13735. pos = 0;
  13736. for (i=0, l=chunks.length; i<l; i++) {
  13737. chunk = chunks[i];
  13738. result.set(chunk, pos);
  13739. pos += chunk.length;
  13740. }
  13741. return result;
  13742. }
  13743. };
  13744. var fnUntyped = {
  13745. arraySet: function (dest, src, src_offs, len, dest_offs) {
  13746. for (var i=0; i<len; i++) {
  13747. dest[dest_offs + i] = src[src_offs + i];
  13748. }
  13749. },
  13750. // Join array of chunks to single array.
  13751. flattenChunks: function(chunks) {
  13752. return [].concat.apply([], chunks);
  13753. }
  13754. };
  13755. // Enable/Disable typed arrays use, for testing
  13756. //
  13757. exports.setTyped = function (on) {
  13758. if (on) {
  13759. exports.Buf8 = Uint8Array;
  13760. exports.Buf16 = Uint16Array;
  13761. exports.Buf32 = Int32Array;
  13762. exports.assign(exports, fnTyped);
  13763. } else {
  13764. exports.Buf8 = Array;
  13765. exports.Buf16 = Array;
  13766. exports.Buf32 = Array;
  13767. exports.assign(exports, fnUntyped);
  13768. }
  13769. };
  13770. exports.setTyped(TYPED_OK);
  13771. },{}],53:[function(require,module,exports){
  13772. // String encode/decode helpers
  13773. 'use strict';
  13774. var utils = require('./common');
  13775. // Quick check if we can use fast array to bin string conversion
  13776. //
  13777. // - apply(Array) can fail on Android 2.2
  13778. // - apply(Uint8Array) can fail on iOS 5.1 Safary
  13779. //
  13780. var STR_APPLY_OK = true;
  13781. var STR_APPLY_UIA_OK = true;
  13782. try { String.fromCharCode.apply(null, [0]); } catch(__) { STR_APPLY_OK = false; }
  13783. try { String.fromCharCode.apply(null, new Uint8Array(1)); } catch(__) { STR_APPLY_UIA_OK = false; }
  13784. // Table with utf8 lengths (calculated by first byte of sequence)
  13785. // Note, that 5 & 6-byte values and some 4-byte values can not be represented in JS,
  13786. // because max possible codepoint is 0x10ffff
  13787. var _utf8len = new utils.Buf8(256);
  13788. for (var q=0; q<256; q++) {
  13789. _utf8len[q] = (q >= 252 ? 6 : q >= 248 ? 5 : q >= 240 ? 4 : q >= 224 ? 3 : q >= 192 ? 2 : 1);
  13790. }
  13791. _utf8len[254]=_utf8len[254]=1; // Invalid sequence start
  13792. // convert string to array (typed, when possible)
  13793. exports.string2buf = function (str) {
  13794. var buf, c, c2, m_pos, i, str_len = str.length, buf_len = 0;
  13795. // count binary size
  13796. for (m_pos = 0; m_pos < str_len; m_pos++) {
  13797. c = str.charCodeAt(m_pos);
  13798. if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) {
  13799. c2 = str.charCodeAt(m_pos+1);
  13800. if ((c2 & 0xfc00) === 0xdc00) {
  13801. c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
  13802. m_pos++;
  13803. }
  13804. }
  13805. buf_len += c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4;
  13806. }
  13807. // allocate buffer
  13808. buf = new utils.Buf8(buf_len);
  13809. // convert
  13810. for (i=0, m_pos = 0; i < buf_len; m_pos++) {
  13811. c = str.charCodeAt(m_pos);
  13812. if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) {
  13813. c2 = str.charCodeAt(m_pos+1);
  13814. if ((c2 & 0xfc00) === 0xdc00) {
  13815. c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
  13816. m_pos++;
  13817. }
  13818. }
  13819. if (c < 0x80) {
  13820. /* one byte */
  13821. buf[i++] = c;
  13822. } else if (c < 0x800) {
  13823. /* two bytes */
  13824. buf[i++] = 0xC0 | (c >>> 6);
  13825. buf[i++] = 0x80 | (c & 0x3f);
  13826. } else if (c < 0x10000) {
  13827. /* three bytes */
  13828. buf[i++] = 0xE0 | (c >>> 12);
  13829. buf[i++] = 0x80 | (c >>> 6 & 0x3f);
  13830. buf[i++] = 0x80 | (c & 0x3f);
  13831. } else {
  13832. /* four bytes */
  13833. buf[i++] = 0xf0 | (c >>> 18);
  13834. buf[i++] = 0x80 | (c >>> 12 & 0x3f);
  13835. buf[i++] = 0x80 | (c >>> 6 & 0x3f);
  13836. buf[i++] = 0x80 | (c & 0x3f);
  13837. }
  13838. }
  13839. return buf;
  13840. };
  13841. // Helper (used in 2 places)
  13842. function buf2binstring(buf, len) {
  13843. // use fallback for big arrays to avoid stack overflow
  13844. if (len < 65537) {
  13845. if ((buf.subarray && STR_APPLY_UIA_OK) || (!buf.subarray && STR_APPLY_OK)) {
  13846. return String.fromCharCode.apply(null, utils.shrinkBuf(buf, len));
  13847. }
  13848. }
  13849. var result = '';
  13850. for (var i=0; i < len; i++) {
  13851. result += String.fromCharCode(buf[i]);
  13852. }
  13853. return result;
  13854. }
  13855. // Convert byte array to binary string
  13856. exports.buf2binstring = function(buf) {
  13857. return buf2binstring(buf, buf.length);
  13858. };
  13859. // Convert binary string (typed, when possible)
  13860. exports.binstring2buf = function(str) {
  13861. var buf = new utils.Buf8(str.length);
  13862. for (var i=0, len=buf.length; i < len; i++) {
  13863. buf[i] = str.charCodeAt(i);
  13864. }
  13865. return buf;
  13866. };
  13867. // convert array to string
  13868. exports.buf2string = function (buf, max) {
  13869. var i, out, c, c_len;
  13870. var len = max || buf.length;
  13871. // Reserve max possible length (2 words per char)
  13872. // NB: by unknown reasons, Array is significantly faster for
  13873. // String.fromCharCode.apply than Uint16Array.
  13874. var utf16buf = new Array(len*2);
  13875. for (out=0, i=0; i<len;) {
  13876. c = buf[i++];
  13877. // quick process ascii
  13878. if (c < 0x80) { utf16buf[out++] = c; continue; }
  13879. c_len = _utf8len[c];
  13880. // skip 5 & 6 byte codes
  13881. if (c_len > 4) { utf16buf[out++] = 0xfffd; i += c_len-1; continue; }
  13882. // apply mask on first byte
  13883. c &= c_len === 2 ? 0x1f : c_len === 3 ? 0x0f : 0x07;
  13884. // join the rest
  13885. while (c_len > 1 && i < len) {
  13886. c = (c << 6) | (buf[i++] & 0x3f);
  13887. c_len--;
  13888. }
  13889. // terminated by end of string?
  13890. if (c_len > 1) { utf16buf[out++] = 0xfffd; continue; }
  13891. if (c < 0x10000) {
  13892. utf16buf[out++] = c;
  13893. } else {
  13894. c -= 0x10000;
  13895. utf16buf[out++] = 0xd800 | ((c >> 10) & 0x3ff);
  13896. utf16buf[out++] = 0xdc00 | (c & 0x3ff);
  13897. }
  13898. }
  13899. return buf2binstring(utf16buf, out);
  13900. };
  13901. // Calculate max possible position in utf8 buffer,
  13902. // that will not break sequence. If that's not possible
  13903. // - (very small limits) return max size as is.
  13904. //
  13905. // buf[] - utf8 bytes array
  13906. // max - length limit (mandatory);
  13907. exports.utf8border = function(buf, max) {
  13908. var pos;
  13909. max = max || buf.length;
  13910. if (max > buf.length) { max = buf.length; }
  13911. // go back from last position, until start of sequence found
  13912. pos = max-1;
  13913. while (pos >= 0 && (buf[pos] & 0xC0) === 0x80) { pos--; }
  13914. // Fuckup - very small and broken sequence,
  13915. // return max, because we should return something anyway.
  13916. if (pos < 0) { return max; }
  13917. // If we came to start of buffer - that means vuffer is too small,
  13918. // return max too.
  13919. if (pos === 0) { return max; }
  13920. return (pos + _utf8len[buf[pos]] > max) ? pos : max;
  13921. };
  13922. },{"./common":52}],54:[function(require,module,exports){
  13923. 'use strict';
  13924. // Note: adler32 takes 12% for level 0 and 2% for level 6.
  13925. // It doesn't worth to make additional optimizationa as in original.
  13926. // Small size is preferable.
  13927. function adler32(adler, buf, len, pos) {
  13928. var s1 = (adler & 0xffff) |0,
  13929. s2 = ((adler >>> 16) & 0xffff) |0,
  13930. n = 0;
  13931. while (len !== 0) {
  13932. // Set limit ~ twice less than 5552, to keep
  13933. // s2 in 31-bits, because we force signed ints.
  13934. // in other case %= will fail.
  13935. n = len > 2000 ? 2000 : len;
  13936. len -= n;
  13937. do {
  13938. s1 = (s1 + buf[pos++]) |0;
  13939. s2 = (s2 + s1) |0;
  13940. } while (--n);
  13941. s1 %= 65521;
  13942. s2 %= 65521;
  13943. }
  13944. return (s1 | (s2 << 16)) |0;
  13945. }
  13946. module.exports = adler32;
  13947. },{}],55:[function(require,module,exports){
  13948. module.exports = {
  13949. /* Allowed flush values; see deflate() and inflate() below for details */
  13950. Z_NO_FLUSH: 0,
  13951. Z_PARTIAL_FLUSH: 1,
  13952. Z_SYNC_FLUSH: 2,
  13953. Z_FULL_FLUSH: 3,
  13954. Z_FINISH: 4,
  13955. Z_BLOCK: 5,
  13956. Z_TREES: 6,
  13957. /* Return codes for the compression/decompression functions. Negative values
  13958. * are errors, positive values are used for special but normal events.
  13959. */
  13960. Z_OK: 0,
  13961. Z_STREAM_END: 1,
  13962. Z_NEED_DICT: 2,
  13963. Z_ERRNO: -1,
  13964. Z_STREAM_ERROR: -2,
  13965. Z_DATA_ERROR: -3,
  13966. //Z_MEM_ERROR: -4,
  13967. Z_BUF_ERROR: -5,
  13968. //Z_VERSION_ERROR: -6,
  13969. /* compression levels */
  13970. Z_NO_COMPRESSION: 0,
  13971. Z_BEST_SPEED: 1,
  13972. Z_BEST_COMPRESSION: 9,
  13973. Z_DEFAULT_COMPRESSION: -1,
  13974. Z_FILTERED: 1,
  13975. Z_HUFFMAN_ONLY: 2,
  13976. Z_RLE: 3,
  13977. Z_FIXED: 4,
  13978. Z_DEFAULT_STRATEGY: 0,
  13979. /* Possible values of the data_type field (though see inflate()) */
  13980. Z_BINARY: 0,
  13981. Z_TEXT: 1,
  13982. //Z_ASCII: 1, // = Z_TEXT (deprecated)
  13983. Z_UNKNOWN: 2,
  13984. /* The deflate compression method */
  13985. Z_DEFLATED: 8
  13986. //Z_NULL: null // Use -1 or null inline, depending on var type
  13987. };
  13988. },{}],56:[function(require,module,exports){
  13989. 'use strict';
  13990. // Note: we can't get significant speed boost here.
  13991. // So write code to minimize size - no pregenerated tables
  13992. // and array tools dependencies.
  13993. // Use ordinary array, since untyped makes no boost here
  13994. function makeTable() {
  13995. var c, table = [];
  13996. for (var n =0; n < 256; n++) {
  13997. c = n;
  13998. for (var k =0; k < 8; k++) {
  13999. c = ((c&1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1));
  14000. }
  14001. table[n] = c;
  14002. }
  14003. return table;
  14004. }
  14005. // Create table on load. Just 255 signed longs. Not a problem.
  14006. var crcTable = makeTable();
  14007. function crc32(crc, buf, len, pos) {
  14008. var t = crcTable,
  14009. end = pos + len;
  14010. crc = crc ^ (-1);
  14011. for (var i = pos; i < end; i++) {
  14012. crc = (crc >>> 8) ^ t[(crc ^ buf[i]) & 0xFF];
  14013. }
  14014. return (crc ^ (-1)); // >>> 0;
  14015. }
  14016. module.exports = crc32;
  14017. },{}],57:[function(require,module,exports){
  14018. 'use strict';
  14019. var utils = require('../utils/common');
  14020. var trees = require('./trees');
  14021. var adler32 = require('./adler32');
  14022. var crc32 = require('./crc32');
  14023. var msg = require('./messages');
  14024. /* Public constants ==========================================================*/
  14025. /* ===========================================================================*/
  14026. /* Allowed flush values; see deflate() and inflate() below for details */
  14027. var Z_NO_FLUSH = 0;
  14028. var Z_PARTIAL_FLUSH = 1;
  14029. //var Z_SYNC_FLUSH = 2;
  14030. var Z_FULL_FLUSH = 3;
  14031. var Z_FINISH = 4;
  14032. var Z_BLOCK = 5;
  14033. //var Z_TREES = 6;
  14034. /* Return codes for the compression/decompression functions. Negative values
  14035. * are errors, positive values are used for special but normal events.
  14036. */
  14037. var Z_OK = 0;
  14038. var Z_STREAM_END = 1;
  14039. //var Z_NEED_DICT = 2;
  14040. //var Z_ERRNO = -1;
  14041. var Z_STREAM_ERROR = -2;
  14042. var Z_DATA_ERROR = -3;
  14043. //var Z_MEM_ERROR = -4;
  14044. var Z_BUF_ERROR = -5;
  14045. //var Z_VERSION_ERROR = -6;
  14046. /* compression levels */
  14047. //var Z_NO_COMPRESSION = 0;
  14048. //var Z_BEST_SPEED = 1;
  14049. //var Z_BEST_COMPRESSION = 9;
  14050. var Z_DEFAULT_COMPRESSION = -1;
  14051. var Z_FILTERED = 1;
  14052. var Z_HUFFMAN_ONLY = 2;
  14053. var Z_RLE = 3;
  14054. var Z_FIXED = 4;
  14055. var Z_DEFAULT_STRATEGY = 0;
  14056. /* Possible values of the data_type field (though see inflate()) */
  14057. //var Z_BINARY = 0;
  14058. //var Z_TEXT = 1;
  14059. //var Z_ASCII = 1; // = Z_TEXT
  14060. var Z_UNKNOWN = 2;
  14061. /* The deflate compression method */
  14062. var Z_DEFLATED = 8;
  14063. /*============================================================================*/
  14064. var MAX_MEM_LEVEL = 9;
  14065. /* Maximum value for memLevel in deflateInit2 */
  14066. var MAX_WBITS = 15;
  14067. /* 32K LZ77 window */
  14068. var DEF_MEM_LEVEL = 8;
  14069. var LENGTH_CODES = 29;
  14070. /* number of length codes, not counting the special END_BLOCK code */
  14071. var LITERALS = 256;
  14072. /* number of literal bytes 0..255 */
  14073. var L_CODES = LITERALS + 1 + LENGTH_CODES;
  14074. /* number of Literal or Length codes, including the END_BLOCK code */
  14075. var D_CODES = 30;
  14076. /* number of distance codes */
  14077. var BL_CODES = 19;
  14078. /* number of codes used to transfer the bit lengths */
  14079. var HEAP_SIZE = 2*L_CODES + 1;
  14080. /* maximum heap size */
  14081. var MAX_BITS = 15;
  14082. /* All codes must not exceed MAX_BITS bits */
  14083. var MIN_MATCH = 3;
  14084. var MAX_MATCH = 258;
  14085. var MIN_LOOKAHEAD = (MAX_MATCH + MIN_MATCH + 1);
  14086. var PRESET_DICT = 0x20;
  14087. var INIT_STATE = 42;
  14088. var EXTRA_STATE = 69;
  14089. var NAME_STATE = 73;
  14090. var COMMENT_STATE = 91;
  14091. var HCRC_STATE = 103;
  14092. var BUSY_STATE = 113;
  14093. var FINISH_STATE = 666;
  14094. var BS_NEED_MORE = 1; /* block not completed, need more input or more output */
  14095. var BS_BLOCK_DONE = 2; /* block flush performed */
  14096. var BS_FINISH_STARTED = 3; /* finish started, need only more output at next deflate */
  14097. var BS_FINISH_DONE = 4; /* finish done, accept no more input or output */
  14098. var OS_CODE = 0x03; // Unix :) . Don't detect, use this default.
  14099. function err(strm, errorCode) {
  14100. strm.msg = msg[errorCode];
  14101. return errorCode;
  14102. }
  14103. function rank(f) {
  14104. return ((f) << 1) - ((f) > 4 ? 9 : 0);
  14105. }
  14106. function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
  14107. /* =========================================================================
  14108. * Flush as much pending output as possible. All deflate() output goes
  14109. * through this function so some applications may wish to modify it
  14110. * to avoid allocating a large strm->output buffer and copying into it.
  14111. * (See also read_buf()).
  14112. */
  14113. function flush_pending(strm) {
  14114. var s = strm.state;
  14115. //_tr_flush_bits(s);
  14116. var len = s.pending;
  14117. if (len > strm.avail_out) {
  14118. len = strm.avail_out;
  14119. }
  14120. if (len === 0) { return; }
  14121. utils.arraySet(strm.output, s.pending_buf, s.pending_out, len, strm.next_out);
  14122. strm.next_out += len;
  14123. s.pending_out += len;
  14124. strm.total_out += len;
  14125. strm.avail_out -= len;
  14126. s.pending -= len;
  14127. if (s.pending === 0) {
  14128. s.pending_out = 0;
  14129. }
  14130. }
  14131. function flush_block_only (s, last) {
  14132. trees._tr_flush_block(s, (s.block_start >= 0 ? s.block_start : -1), s.strstart - s.block_start, last);
  14133. s.block_start = s.strstart;
  14134. flush_pending(s.strm);
  14135. }
  14136. function put_byte(s, b) {
  14137. s.pending_buf[s.pending++] = b;
  14138. }
  14139. /* =========================================================================
  14140. * Put a short in the pending buffer. The 16-bit value is put in MSB order.
  14141. * IN assertion: the stream state is correct and there is enough room in
  14142. * pending_buf.
  14143. */
  14144. function putShortMSB(s, b) {
  14145. // put_byte(s, (Byte)(b >> 8));
  14146. // put_byte(s, (Byte)(b & 0xff));
  14147. s.pending_buf[s.pending++] = (b >>> 8) & 0xff;
  14148. s.pending_buf[s.pending++] = b & 0xff;
  14149. }
  14150. /* ===========================================================================
  14151. * Read a new buffer from the current input stream, update the adler32
  14152. * and total number of bytes read. All deflate() input goes through
  14153. * this function so some applications may wish to modify it to avoid
  14154. * allocating a large strm->input buffer and copying from it.
  14155. * (See also flush_pending()).
  14156. */
  14157. function read_buf(strm, buf, start, size) {
  14158. var len = strm.avail_in;
  14159. if (len > size) { len = size; }
  14160. if (len === 0) { return 0; }
  14161. strm.avail_in -= len;
  14162. utils.arraySet(buf, strm.input, strm.next_in, len, start);
  14163. if (strm.state.wrap === 1) {
  14164. strm.adler = adler32(strm.adler, buf, len, start);
  14165. }
  14166. else if (strm.state.wrap === 2) {
  14167. strm.adler = crc32(strm.adler, buf, len, start);
  14168. }
  14169. strm.next_in += len;
  14170. strm.total_in += len;
  14171. return len;
  14172. }
  14173. /* ===========================================================================
  14174. * Set match_start to the longest match starting at the given string and
  14175. * return its length. Matches shorter or equal to prev_length are discarded,
  14176. * in which case the result is equal to prev_length and match_start is
  14177. * garbage.
  14178. * IN assertions: cur_match is the head of the hash chain for the current
  14179. * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
  14180. * OUT assertion: the match length is not greater than s->lookahead.
  14181. */
  14182. function longest_match(s, cur_match) {
  14183. var chain_length = s.max_chain_length; /* max hash chain length */
  14184. var scan = s.strstart; /* current string */
  14185. var match; /* matched string */
  14186. var len; /* length of current match */
  14187. var best_len = s.prev_length; /* best match length so far */
  14188. var nice_match = s.nice_match; /* stop if match long enough */
  14189. var limit = (s.strstart > (s.w_size - MIN_LOOKAHEAD)) ?
  14190. s.strstart - (s.w_size - MIN_LOOKAHEAD) : 0/*NIL*/;
  14191. var _win = s.window; // shortcut
  14192. var wmask = s.w_mask;
  14193. var prev = s.prev;
  14194. /* Stop when cur_match becomes <= limit. To simplify the code,
  14195. * we prevent matches with the string of window index 0.
  14196. */
  14197. var strend = s.strstart + MAX_MATCH;
  14198. var scan_end1 = _win[scan + best_len - 1];
  14199. var scan_end = _win[scan + best_len];
  14200. /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
  14201. * It is easy to get rid of this optimization if necessary.
  14202. */
  14203. // Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
  14204. /* Do not waste too much time if we already have a good match: */
  14205. if (s.prev_length >= s.good_match) {
  14206. chain_length >>= 2;
  14207. }
  14208. /* Do not look for matches beyond the end of the input. This is necessary
  14209. * to make deflate deterministic.
  14210. */
  14211. if (nice_match > s.lookahead) { nice_match = s.lookahead; }
  14212. // Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
  14213. do {
  14214. // Assert(cur_match < s->strstart, "no future");
  14215. match = cur_match;
  14216. /* Skip to next match if the match length cannot increase
  14217. * or if the match length is less than 2. Note that the checks below
  14218. * for insufficient lookahead only occur occasionally for performance
  14219. * reasons. Therefore uninitialized memory will be accessed, and
  14220. * conditional jumps will be made that depend on those values.
  14221. * However the length of the match is limited to the lookahead, so
  14222. * the output of deflate is not affected by the uninitialized values.
  14223. */
  14224. if (_win[match + best_len] !== scan_end ||
  14225. _win[match + best_len - 1] !== scan_end1 ||
  14226. _win[match] !== _win[scan] ||
  14227. _win[++match] !== _win[scan + 1]) {
  14228. continue;
  14229. }
  14230. /* The check at best_len-1 can be removed because it will be made
  14231. * again later. (This heuristic is not always a win.)
  14232. * It is not necessary to compare scan[2] and match[2] since they
  14233. * are always equal when the other bytes match, given that
  14234. * the hash keys are equal and that HASH_BITS >= 8.
  14235. */
  14236. scan += 2;
  14237. match++;
  14238. // Assert(*scan == *match, "match[2]?");
  14239. /* We check for insufficient lookahead only every 8th comparison;
  14240. * the 256th check will be made at strstart+258.
  14241. */
  14242. do {
  14243. /*jshint noempty:false*/
  14244. } while (_win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  14245. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  14246. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  14247. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  14248. scan < strend);
  14249. // Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  14250. len = MAX_MATCH - (strend - scan);
  14251. scan = strend - MAX_MATCH;
  14252. if (len > best_len) {
  14253. s.match_start = cur_match;
  14254. best_len = len;
  14255. if (len >= nice_match) {
  14256. break;
  14257. }
  14258. scan_end1 = _win[scan + best_len - 1];
  14259. scan_end = _win[scan + best_len];
  14260. }
  14261. } while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length !== 0);
  14262. if (best_len <= s.lookahead) {
  14263. return best_len;
  14264. }
  14265. return s.lookahead;
  14266. }
  14267. /* ===========================================================================
  14268. * Fill the window when the lookahead becomes insufficient.
  14269. * Updates strstart and lookahead.
  14270. *
  14271. * IN assertion: lookahead < MIN_LOOKAHEAD
  14272. * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
  14273. * At least one byte has been read, or avail_in == 0; reads are
  14274. * performed for at least two bytes (required for the zip translate_eol
  14275. * option -- not supported here).
  14276. */
  14277. function fill_window(s) {
  14278. var _w_size = s.w_size;
  14279. var p, n, m, more, str;
  14280. //Assert(s->lookahead < MIN_LOOKAHEAD, "already enough lookahead");
  14281. do {
  14282. more = s.window_size - s.lookahead - s.strstart;
  14283. // JS ints have 32 bit, block below not needed
  14284. /* Deal with !@#$% 64K limit: */
  14285. //if (sizeof(int) <= 2) {
  14286. // if (more == 0 && s->strstart == 0 && s->lookahead == 0) {
  14287. // more = wsize;
  14288. //
  14289. // } else if (more == (unsigned)(-1)) {
  14290. // /* Very unlikely, but possible on 16 bit machine if
  14291. // * strstart == 0 && lookahead == 1 (input done a byte at time)
  14292. // */
  14293. // more--;
  14294. // }
  14295. //}
  14296. /* If the window is almost full and there is insufficient lookahead,
  14297. * move the upper half to the lower one to make room in the upper half.
  14298. */
  14299. if (s.strstart >= _w_size + (_w_size - MIN_LOOKAHEAD)) {
  14300. utils.arraySet(s.window, s.window, _w_size, _w_size, 0);
  14301. s.match_start -= _w_size;
  14302. s.strstart -= _w_size;
  14303. /* we now have strstart >= MAX_DIST */
  14304. s.block_start -= _w_size;
  14305. /* Slide the hash table (could be avoided with 32 bit values
  14306. at the expense of memory usage). We slide even when level == 0
  14307. to keep the hash table consistent if we switch back to level > 0
  14308. later. (Using level 0 permanently is not an optimal usage of
  14309. zlib, so we don't care about this pathological case.)
  14310. */
  14311. n = s.hash_size;
  14312. p = n;
  14313. do {
  14314. m = s.head[--p];
  14315. s.head[p] = (m >= _w_size ? m - _w_size : 0);
  14316. } while (--n);
  14317. n = _w_size;
  14318. p = n;
  14319. do {
  14320. m = s.prev[--p];
  14321. s.prev[p] = (m >= _w_size ? m - _w_size : 0);
  14322. /* If n is not on any hash chain, prev[n] is garbage but
  14323. * its value will never be used.
  14324. */
  14325. } while (--n);
  14326. more += _w_size;
  14327. }
  14328. if (s.strm.avail_in === 0) {
  14329. break;
  14330. }
  14331. /* If there was no sliding:
  14332. * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
  14333. * more == window_size - lookahead - strstart
  14334. * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
  14335. * => more >= window_size - 2*WSIZE + 2
  14336. * In the BIG_MEM or MMAP case (not yet supported),
  14337. * window_size == input_size + MIN_LOOKAHEAD &&
  14338. * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
  14339. * Otherwise, window_size == 2*WSIZE so more >= 2.
  14340. * If there was sliding, more >= WSIZE. So in all cases, more >= 2.
  14341. */
  14342. //Assert(more >= 2, "more < 2");
  14343. n = read_buf(s.strm, s.window, s.strstart + s.lookahead, more);
  14344. s.lookahead += n;
  14345. /* Initialize the hash value now that we have some input: */
  14346. if (s.lookahead + s.insert >= MIN_MATCH) {
  14347. str = s.strstart - s.insert;
  14348. s.ins_h = s.window[str];
  14349. /* UPDATE_HASH(s, s->ins_h, s->window[str + 1]); */
  14350. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + 1]) & s.hash_mask;
  14351. //#if MIN_MATCH != 3
  14352. // Call update_hash() MIN_MATCH-3 more times
  14353. //#endif
  14354. while (s.insert) {
  14355. /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */
  14356. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH-1]) & s.hash_mask;
  14357. s.prev[str & s.w_mask] = s.head[s.ins_h];
  14358. s.head[s.ins_h] = str;
  14359. str++;
  14360. s.insert--;
  14361. if (s.lookahead + s.insert < MIN_MATCH) {
  14362. break;
  14363. }
  14364. }
  14365. }
  14366. /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,
  14367. * but this is not important since only literal bytes will be emitted.
  14368. */
  14369. } while (s.lookahead < MIN_LOOKAHEAD && s.strm.avail_in !== 0);
  14370. /* If the WIN_INIT bytes after the end of the current data have never been
  14371. * written, then zero those bytes in order to avoid memory check reports of
  14372. * the use of uninitialized (or uninitialised as Julian writes) bytes by
  14373. * the longest match routines. Update the high water mark for the next
  14374. * time through here. WIN_INIT is set to MAX_MATCH since the longest match
  14375. * routines allow scanning to strstart + MAX_MATCH, ignoring lookahead.
  14376. */
  14377. // if (s.high_water < s.window_size) {
  14378. // var curr = s.strstart + s.lookahead;
  14379. // var init = 0;
  14380. //
  14381. // if (s.high_water < curr) {
  14382. // /* Previous high water mark below current data -- zero WIN_INIT
  14383. // * bytes or up to end of window, whichever is less.
  14384. // */
  14385. // init = s.window_size - curr;
  14386. // if (init > WIN_INIT)
  14387. // init = WIN_INIT;
  14388. // zmemzero(s->window + curr, (unsigned)init);
  14389. // s->high_water = curr + init;
  14390. // }
  14391. // else if (s->high_water < (ulg)curr + WIN_INIT) {
  14392. // /* High water mark at or above current data, but below current data
  14393. // * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up
  14394. // * to end of window, whichever is less.
  14395. // */
  14396. // init = (ulg)curr + WIN_INIT - s->high_water;
  14397. // if (init > s->window_size - s->high_water)
  14398. // init = s->window_size - s->high_water;
  14399. // zmemzero(s->window + s->high_water, (unsigned)init);
  14400. // s->high_water += init;
  14401. // }
  14402. // }
  14403. //
  14404. // Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD,
  14405. // "not enough room for search");
  14406. }
  14407. /* ===========================================================================
  14408. * Copy without compression as much as possible from the input stream, return
  14409. * the current block state.
  14410. * This function does not insert new strings in the dictionary since
  14411. * uncompressible data is probably not useful. This function is used
  14412. * only for the level=0 compression option.
  14413. * NOTE: this function should be optimized to avoid extra copying from
  14414. * window to pending_buf.
  14415. */
  14416. function deflate_stored(s, flush) {
  14417. /* Stored blocks are limited to 0xffff bytes, pending_buf is limited
  14418. * to pending_buf_size, and each stored block has a 5 byte header:
  14419. */
  14420. var max_block_size = 0xffff;
  14421. if (max_block_size > s.pending_buf_size - 5) {
  14422. max_block_size = s.pending_buf_size - 5;
  14423. }
  14424. /* Copy as much as possible from input to output: */
  14425. for (;;) {
  14426. /* Fill the window as much as possible: */
  14427. if (s.lookahead <= 1) {
  14428. //Assert(s->strstart < s->w_size+MAX_DIST(s) ||
  14429. // s->block_start >= (long)s->w_size, "slide too late");
  14430. // if (!(s.strstart < s.w_size + (s.w_size - MIN_LOOKAHEAD) ||
  14431. // s.block_start >= s.w_size)) {
  14432. // throw new Error("slide too late");
  14433. // }
  14434. fill_window(s);
  14435. if (s.lookahead === 0 && flush === Z_NO_FLUSH) {
  14436. return BS_NEED_MORE;
  14437. }
  14438. if (s.lookahead === 0) {
  14439. break;
  14440. }
  14441. /* flush the current block */
  14442. }
  14443. //Assert(s->block_start >= 0L, "block gone");
  14444. // if (s.block_start < 0) throw new Error("block gone");
  14445. s.strstart += s.lookahead;
  14446. s.lookahead = 0;
  14447. /* Emit a stored block if pending_buf will be full: */
  14448. var max_start = s.block_start + max_block_size;
  14449. if (s.strstart === 0 || s.strstart >= max_start) {
  14450. /* strstart == 0 is possible when wraparound on 16-bit machine */
  14451. s.lookahead = s.strstart - max_start;
  14452. s.strstart = max_start;
  14453. /*** FLUSH_BLOCK(s, 0); ***/
  14454. flush_block_only(s, false);
  14455. if (s.strm.avail_out === 0) {
  14456. return BS_NEED_MORE;
  14457. }
  14458. /***/
  14459. }
  14460. /* Flush if we may have to slide, otherwise block_start may become
  14461. * negative and the data will be gone:
  14462. */
  14463. if (s.strstart - s.block_start >= (s.w_size - MIN_LOOKAHEAD)) {
  14464. /*** FLUSH_BLOCK(s, 0); ***/
  14465. flush_block_only(s, false);
  14466. if (s.strm.avail_out === 0) {
  14467. return BS_NEED_MORE;
  14468. }
  14469. /***/
  14470. }
  14471. }
  14472. s.insert = 0;
  14473. if (flush === Z_FINISH) {
  14474. /*** FLUSH_BLOCK(s, 1); ***/
  14475. flush_block_only(s, true);
  14476. if (s.strm.avail_out === 0) {
  14477. return BS_FINISH_STARTED;
  14478. }
  14479. /***/
  14480. return BS_FINISH_DONE;
  14481. }
  14482. if (s.strstart > s.block_start) {
  14483. /*** FLUSH_BLOCK(s, 0); ***/
  14484. flush_block_only(s, false);
  14485. if (s.strm.avail_out === 0) {
  14486. return BS_NEED_MORE;
  14487. }
  14488. /***/
  14489. }
  14490. return BS_NEED_MORE;
  14491. }
  14492. /* ===========================================================================
  14493. * Compress as much as possible from the input stream, return the current
  14494. * block state.
  14495. * This function does not perform lazy evaluation of matches and inserts
  14496. * new strings in the dictionary only for unmatched strings or for short
  14497. * matches. It is used only for the fast compression options.
  14498. */
  14499. function deflate_fast(s, flush) {
  14500. var hash_head; /* head of the hash chain */
  14501. var bflush; /* set if current block must be flushed */
  14502. for (;;) {
  14503. /* Make sure that we always have enough lookahead, except
  14504. * at the end of the input file. We need MAX_MATCH bytes
  14505. * for the next match, plus MIN_MATCH bytes to insert the
  14506. * string following the next match.
  14507. */
  14508. if (s.lookahead < MIN_LOOKAHEAD) {
  14509. fill_window(s);
  14510. if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
  14511. return BS_NEED_MORE;
  14512. }
  14513. if (s.lookahead === 0) {
  14514. break; /* flush the current block */
  14515. }
  14516. }
  14517. /* Insert the string window[strstart .. strstart+2] in the
  14518. * dictionary, and set hash_head to the head of the hash chain:
  14519. */
  14520. hash_head = 0/*NIL*/;
  14521. if (s.lookahead >= MIN_MATCH) {
  14522. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  14523. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  14524. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  14525. s.head[s.ins_h] = s.strstart;
  14526. /***/
  14527. }
  14528. /* Find the longest match, discarding those <= prev_length.
  14529. * At this point we have always match_length < MIN_MATCH
  14530. */
  14531. if (hash_head !== 0/*NIL*/ && ((s.strstart - hash_head) <= (s.w_size - MIN_LOOKAHEAD))) {
  14532. /* To simplify the code, we prevent matches with the string
  14533. * of window index 0 (in particular we have to avoid a match
  14534. * of the string with itself at the start of the input file).
  14535. */
  14536. s.match_length = longest_match(s, hash_head);
  14537. /* longest_match() sets match_start */
  14538. }
  14539. if (s.match_length >= MIN_MATCH) {
  14540. // check_match(s, s.strstart, s.match_start, s.match_length); // for debug only
  14541. /*** _tr_tally_dist(s, s.strstart - s.match_start,
  14542. s.match_length - MIN_MATCH, bflush); ***/
  14543. bflush = trees._tr_tally(s, s.strstart - s.match_start, s.match_length - MIN_MATCH);
  14544. s.lookahead -= s.match_length;
  14545. /* Insert new strings in the hash table only if the match length
  14546. * is not too large. This saves time but degrades compression.
  14547. */
  14548. if (s.match_length <= s.max_lazy_match/*max_insert_length*/ && s.lookahead >= MIN_MATCH) {
  14549. s.match_length--; /* string at strstart already in table */
  14550. do {
  14551. s.strstart++;
  14552. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  14553. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  14554. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  14555. s.head[s.ins_h] = s.strstart;
  14556. /***/
  14557. /* strstart never exceeds WSIZE-MAX_MATCH, so there are
  14558. * always MIN_MATCH bytes ahead.
  14559. */
  14560. } while (--s.match_length !== 0);
  14561. s.strstart++;
  14562. } else
  14563. {
  14564. s.strstart += s.match_length;
  14565. s.match_length = 0;
  14566. s.ins_h = s.window[s.strstart];
  14567. /* UPDATE_HASH(s, s.ins_h, s.window[s.strstart+1]); */
  14568. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + 1]) & s.hash_mask;
  14569. //#if MIN_MATCH != 3
  14570. // Call UPDATE_HASH() MIN_MATCH-3 more times
  14571. //#endif
  14572. /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not
  14573. * matter since it will be recomputed at next deflate call.
  14574. */
  14575. }
  14576. } else {
  14577. /* No match, output a literal byte */
  14578. //Tracevv((stderr,"%c", s.window[s.strstart]));
  14579. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  14580. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  14581. s.lookahead--;
  14582. s.strstart++;
  14583. }
  14584. if (bflush) {
  14585. /*** FLUSH_BLOCK(s, 0); ***/
  14586. flush_block_only(s, false);
  14587. if (s.strm.avail_out === 0) {
  14588. return BS_NEED_MORE;
  14589. }
  14590. /***/
  14591. }
  14592. }
  14593. s.insert = ((s.strstart < (MIN_MATCH-1)) ? s.strstart : MIN_MATCH-1);
  14594. if (flush === Z_FINISH) {
  14595. /*** FLUSH_BLOCK(s, 1); ***/
  14596. flush_block_only(s, true);
  14597. if (s.strm.avail_out === 0) {
  14598. return BS_FINISH_STARTED;
  14599. }
  14600. /***/
  14601. return BS_FINISH_DONE;
  14602. }
  14603. if (s.last_lit) {
  14604. /*** FLUSH_BLOCK(s, 0); ***/
  14605. flush_block_only(s, false);
  14606. if (s.strm.avail_out === 0) {
  14607. return BS_NEED_MORE;
  14608. }
  14609. /***/
  14610. }
  14611. return BS_BLOCK_DONE;
  14612. }
  14613. /* ===========================================================================
  14614. * Same as above, but achieves better compression. We use a lazy
  14615. * evaluation for matches: a match is finally adopted only if there is
  14616. * no better match at the next window position.
  14617. */
  14618. function deflate_slow(s, flush) {
  14619. var hash_head; /* head of hash chain */
  14620. var bflush; /* set if current block must be flushed */
  14621. var max_insert;
  14622. /* Process the input block. */
  14623. for (;;) {
  14624. /* Make sure that we always have enough lookahead, except
  14625. * at the end of the input file. We need MAX_MATCH bytes
  14626. * for the next match, plus MIN_MATCH bytes to insert the
  14627. * string following the next match.
  14628. */
  14629. if (s.lookahead < MIN_LOOKAHEAD) {
  14630. fill_window(s);
  14631. if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
  14632. return BS_NEED_MORE;
  14633. }
  14634. if (s.lookahead === 0) { break; } /* flush the current block */
  14635. }
  14636. /* Insert the string window[strstart .. strstart+2] in the
  14637. * dictionary, and set hash_head to the head of the hash chain:
  14638. */
  14639. hash_head = 0/*NIL*/;
  14640. if (s.lookahead >= MIN_MATCH) {
  14641. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  14642. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  14643. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  14644. s.head[s.ins_h] = s.strstart;
  14645. /***/
  14646. }
  14647. /* Find the longest match, discarding those <= prev_length.
  14648. */
  14649. s.prev_length = s.match_length;
  14650. s.prev_match = s.match_start;
  14651. s.match_length = MIN_MATCH-1;
  14652. if (hash_head !== 0/*NIL*/ && s.prev_length < s.max_lazy_match &&
  14653. s.strstart - hash_head <= (s.w_size-MIN_LOOKAHEAD)/*MAX_DIST(s)*/) {
  14654. /* To simplify the code, we prevent matches with the string
  14655. * of window index 0 (in particular we have to avoid a match
  14656. * of the string with itself at the start of the input file).
  14657. */
  14658. s.match_length = longest_match(s, hash_head);
  14659. /* longest_match() sets match_start */
  14660. if (s.match_length <= 5 &&
  14661. (s.strategy === Z_FILTERED || (s.match_length === MIN_MATCH && s.strstart - s.match_start > 4096/*TOO_FAR*/))) {
  14662. /* If prev_match is also MIN_MATCH, match_start is garbage
  14663. * but we will ignore the current match anyway.
  14664. */
  14665. s.match_length = MIN_MATCH-1;
  14666. }
  14667. }
  14668. /* If there was a match at the previous step and the current
  14669. * match is not better, output the previous match:
  14670. */
  14671. if (s.prev_length >= MIN_MATCH && s.match_length <= s.prev_length) {
  14672. max_insert = s.strstart + s.lookahead - MIN_MATCH;
  14673. /* Do not insert strings in hash table beyond this. */
  14674. //check_match(s, s.strstart-1, s.prev_match, s.prev_length);
  14675. /***_tr_tally_dist(s, s.strstart - 1 - s.prev_match,
  14676. s.prev_length - MIN_MATCH, bflush);***/
  14677. bflush = trees._tr_tally(s, s.strstart - 1- s.prev_match, s.prev_length - MIN_MATCH);
  14678. /* Insert in hash table all strings up to the end of the match.
  14679. * strstart-1 and strstart are already inserted. If there is not
  14680. * enough lookahead, the last two strings are not inserted in
  14681. * the hash table.
  14682. */
  14683. s.lookahead -= s.prev_length-1;
  14684. s.prev_length -= 2;
  14685. do {
  14686. if (++s.strstart <= max_insert) {
  14687. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  14688. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  14689. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  14690. s.head[s.ins_h] = s.strstart;
  14691. /***/
  14692. }
  14693. } while (--s.prev_length !== 0);
  14694. s.match_available = 0;
  14695. s.match_length = MIN_MATCH-1;
  14696. s.strstart++;
  14697. if (bflush) {
  14698. /*** FLUSH_BLOCK(s, 0); ***/
  14699. flush_block_only(s, false);
  14700. if (s.strm.avail_out === 0) {
  14701. return BS_NEED_MORE;
  14702. }
  14703. /***/
  14704. }
  14705. } else if (s.match_available) {
  14706. /* If there was no match at the previous position, output a
  14707. * single literal. If there was a match but the current match
  14708. * is longer, truncate the previous match to a single literal.
  14709. */
  14710. //Tracevv((stderr,"%c", s->window[s->strstart-1]));
  14711. /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
  14712. bflush = trees._tr_tally(s, 0, s.window[s.strstart-1]);
  14713. if (bflush) {
  14714. /*** FLUSH_BLOCK_ONLY(s, 0) ***/
  14715. flush_block_only(s, false);
  14716. /***/
  14717. }
  14718. s.strstart++;
  14719. s.lookahead--;
  14720. if (s.strm.avail_out === 0) {
  14721. return BS_NEED_MORE;
  14722. }
  14723. } else {
  14724. /* There is no previous match to compare with, wait for
  14725. * the next step to decide.
  14726. */
  14727. s.match_available = 1;
  14728. s.strstart++;
  14729. s.lookahead--;
  14730. }
  14731. }
  14732. //Assert (flush != Z_NO_FLUSH, "no flush?");
  14733. if (s.match_available) {
  14734. //Tracevv((stderr,"%c", s->window[s->strstart-1]));
  14735. /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
  14736. bflush = trees._tr_tally(s, 0, s.window[s.strstart-1]);
  14737. s.match_available = 0;
  14738. }
  14739. s.insert = s.strstart < MIN_MATCH-1 ? s.strstart : MIN_MATCH-1;
  14740. if (flush === Z_FINISH) {
  14741. /*** FLUSH_BLOCK(s, 1); ***/
  14742. flush_block_only(s, true);
  14743. if (s.strm.avail_out === 0) {
  14744. return BS_FINISH_STARTED;
  14745. }
  14746. /***/
  14747. return BS_FINISH_DONE;
  14748. }
  14749. if (s.last_lit) {
  14750. /*** FLUSH_BLOCK(s, 0); ***/
  14751. flush_block_only(s, false);
  14752. if (s.strm.avail_out === 0) {
  14753. return BS_NEED_MORE;
  14754. }
  14755. /***/
  14756. }
  14757. return BS_BLOCK_DONE;
  14758. }
  14759. /* ===========================================================================
  14760. * For Z_RLE, simply look for runs of bytes, generate matches only of distance
  14761. * one. Do not maintain a hash table. (It will be regenerated if this run of
  14762. * deflate switches away from Z_RLE.)
  14763. */
  14764. function deflate_rle(s, flush) {
  14765. var bflush; /* set if current block must be flushed */
  14766. var prev; /* byte at distance one to match */
  14767. var scan, strend; /* scan goes up to strend for length of run */
  14768. var _win = s.window;
  14769. for (;;) {
  14770. /* Make sure that we always have enough lookahead, except
  14771. * at the end of the input file. We need MAX_MATCH bytes
  14772. * for the longest run, plus one for the unrolled loop.
  14773. */
  14774. if (s.lookahead <= MAX_MATCH) {
  14775. fill_window(s);
  14776. if (s.lookahead <= MAX_MATCH && flush === Z_NO_FLUSH) {
  14777. return BS_NEED_MORE;
  14778. }
  14779. if (s.lookahead === 0) { break; } /* flush the current block */
  14780. }
  14781. /* See how many times the previous byte repeats */
  14782. s.match_length = 0;
  14783. if (s.lookahead >= MIN_MATCH && s.strstart > 0) {
  14784. scan = s.strstart - 1;
  14785. prev = _win[scan];
  14786. if (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan]) {
  14787. strend = s.strstart + MAX_MATCH;
  14788. do {
  14789. /*jshint noempty:false*/
  14790. } while (prev === _win[++scan] && prev === _win[++scan] &&
  14791. prev === _win[++scan] && prev === _win[++scan] &&
  14792. prev === _win[++scan] && prev === _win[++scan] &&
  14793. prev === _win[++scan] && prev === _win[++scan] &&
  14794. scan < strend);
  14795. s.match_length = MAX_MATCH - (strend - scan);
  14796. if (s.match_length > s.lookahead) {
  14797. s.match_length = s.lookahead;
  14798. }
  14799. }
  14800. //Assert(scan <= s->window+(uInt)(s->window_size-1), "wild scan");
  14801. }
  14802. /* Emit match if have run of MIN_MATCH or longer, else emit literal */
  14803. if (s.match_length >= MIN_MATCH) {
  14804. //check_match(s, s.strstart, s.strstart - 1, s.match_length);
  14805. /*** _tr_tally_dist(s, 1, s.match_length - MIN_MATCH, bflush); ***/
  14806. bflush = trees._tr_tally(s, 1, s.match_length - MIN_MATCH);
  14807. s.lookahead -= s.match_length;
  14808. s.strstart += s.match_length;
  14809. s.match_length = 0;
  14810. } else {
  14811. /* No match, output a literal byte */
  14812. //Tracevv((stderr,"%c", s->window[s->strstart]));
  14813. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  14814. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  14815. s.lookahead--;
  14816. s.strstart++;
  14817. }
  14818. if (bflush) {
  14819. /*** FLUSH_BLOCK(s, 0); ***/
  14820. flush_block_only(s, false);
  14821. if (s.strm.avail_out === 0) {
  14822. return BS_NEED_MORE;
  14823. }
  14824. /***/
  14825. }
  14826. }
  14827. s.insert = 0;
  14828. if (flush === Z_FINISH) {
  14829. /*** FLUSH_BLOCK(s, 1); ***/
  14830. flush_block_only(s, true);
  14831. if (s.strm.avail_out === 0) {
  14832. return BS_FINISH_STARTED;
  14833. }
  14834. /***/
  14835. return BS_FINISH_DONE;
  14836. }
  14837. if (s.last_lit) {
  14838. /*** FLUSH_BLOCK(s, 0); ***/
  14839. flush_block_only(s, false);
  14840. if (s.strm.avail_out === 0) {
  14841. return BS_NEED_MORE;
  14842. }
  14843. /***/
  14844. }
  14845. return BS_BLOCK_DONE;
  14846. }
  14847. /* ===========================================================================
  14848. * For Z_HUFFMAN_ONLY, do not look for matches. Do not maintain a hash table.
  14849. * (It will be regenerated if this run of deflate switches away from Huffman.)
  14850. */
  14851. function deflate_huff(s, flush) {
  14852. var bflush; /* set if current block must be flushed */
  14853. for (;;) {
  14854. /* Make sure that we have a literal to write. */
  14855. if (s.lookahead === 0) {
  14856. fill_window(s);
  14857. if (s.lookahead === 0) {
  14858. if (flush === Z_NO_FLUSH) {
  14859. return BS_NEED_MORE;
  14860. }
  14861. break; /* flush the current block */
  14862. }
  14863. }
  14864. /* Output a literal byte */
  14865. s.match_length = 0;
  14866. //Tracevv((stderr,"%c", s->window[s->strstart]));
  14867. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  14868. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  14869. s.lookahead--;
  14870. s.strstart++;
  14871. if (bflush) {
  14872. /*** FLUSH_BLOCK(s, 0); ***/
  14873. flush_block_only(s, false);
  14874. if (s.strm.avail_out === 0) {
  14875. return BS_NEED_MORE;
  14876. }
  14877. /***/
  14878. }
  14879. }
  14880. s.insert = 0;
  14881. if (flush === Z_FINISH) {
  14882. /*** FLUSH_BLOCK(s, 1); ***/
  14883. flush_block_only(s, true);
  14884. if (s.strm.avail_out === 0) {
  14885. return BS_FINISH_STARTED;
  14886. }
  14887. /***/
  14888. return BS_FINISH_DONE;
  14889. }
  14890. if (s.last_lit) {
  14891. /*** FLUSH_BLOCK(s, 0); ***/
  14892. flush_block_only(s, false);
  14893. if (s.strm.avail_out === 0) {
  14894. return BS_NEED_MORE;
  14895. }
  14896. /***/
  14897. }
  14898. return BS_BLOCK_DONE;
  14899. }
  14900. /* Values for max_lazy_match, good_match and max_chain_length, depending on
  14901. * the desired pack level (0..9). The values given below have been tuned to
  14902. * exclude worst case performance for pathological files. Better values may be
  14903. * found for specific files.
  14904. */
  14905. var Config = function (good_length, max_lazy, nice_length, max_chain, func) {
  14906. this.good_length = good_length;
  14907. this.max_lazy = max_lazy;
  14908. this.nice_length = nice_length;
  14909. this.max_chain = max_chain;
  14910. this.func = func;
  14911. };
  14912. var configuration_table;
  14913. configuration_table = [
  14914. /* good lazy nice chain */
  14915. new Config(0, 0, 0, 0, deflate_stored), /* 0 store only */
  14916. new Config(4, 4, 8, 4, deflate_fast), /* 1 max speed, no lazy matches */
  14917. new Config(4, 5, 16, 8, deflate_fast), /* 2 */
  14918. new Config(4, 6, 32, 32, deflate_fast), /* 3 */
  14919. new Config(4, 4, 16, 16, deflate_slow), /* 4 lazy matches */
  14920. new Config(8, 16, 32, 32, deflate_slow), /* 5 */
  14921. new Config(8, 16, 128, 128, deflate_slow), /* 6 */
  14922. new Config(8, 32, 128, 256, deflate_slow), /* 7 */
  14923. new Config(32, 128, 258, 1024, deflate_slow), /* 8 */
  14924. new Config(32, 258, 258, 4096, deflate_slow) /* 9 max compression */
  14925. ];
  14926. /* ===========================================================================
  14927. * Initialize the "longest match" routines for a new zlib stream
  14928. */
  14929. function lm_init(s) {
  14930. s.window_size = 2 * s.w_size;
  14931. /*** CLEAR_HASH(s); ***/
  14932. zero(s.head); // Fill with NIL (= 0);
  14933. /* Set the default configuration parameters:
  14934. */
  14935. s.max_lazy_match = configuration_table[s.level].max_lazy;
  14936. s.good_match = configuration_table[s.level].good_length;
  14937. s.nice_match = configuration_table[s.level].nice_length;
  14938. s.max_chain_length = configuration_table[s.level].max_chain;
  14939. s.strstart = 0;
  14940. s.block_start = 0;
  14941. s.lookahead = 0;
  14942. s.insert = 0;
  14943. s.match_length = s.prev_length = MIN_MATCH - 1;
  14944. s.match_available = 0;
  14945. s.ins_h = 0;
  14946. }
  14947. function DeflateState() {
  14948. this.strm = null; /* pointer back to this zlib stream */
  14949. this.status = 0; /* as the name implies */
  14950. this.pending_buf = null; /* output still pending */
  14951. this.pending_buf_size = 0; /* size of pending_buf */
  14952. this.pending_out = 0; /* next pending byte to output to the stream */
  14953. this.pending = 0; /* nb of bytes in the pending buffer */
  14954. this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
  14955. this.gzhead = null; /* gzip header information to write */
  14956. this.gzindex = 0; /* where in extra, name, or comment */
  14957. this.method = Z_DEFLATED; /* can only be DEFLATED */
  14958. this.last_flush = -1; /* value of flush param for previous deflate call */
  14959. this.w_size = 0; /* LZ77 window size (32K by default) */
  14960. this.w_bits = 0; /* log2(w_size) (8..16) */
  14961. this.w_mask = 0; /* w_size - 1 */
  14962. this.window = null;
  14963. /* Sliding window. Input bytes are read into the second half of the window,
  14964. * and move to the first half later to keep a dictionary of at least wSize
  14965. * bytes. With this organization, matches are limited to a distance of
  14966. * wSize-MAX_MATCH bytes, but this ensures that IO is always
  14967. * performed with a length multiple of the block size.
  14968. */
  14969. this.window_size = 0;
  14970. /* Actual size of window: 2*wSize, except when the user input buffer
  14971. * is directly used as sliding window.
  14972. */
  14973. this.prev = null;
  14974. /* Link to older string with same hash index. To limit the size of this
  14975. * array to 64K, this link is maintained only for the last 32K strings.
  14976. * An index in this array is thus a window index modulo 32K.
  14977. */
  14978. this.head = null; /* Heads of the hash chains or NIL. */
  14979. this.ins_h = 0; /* hash index of string to be inserted */
  14980. this.hash_size = 0; /* number of elements in hash table */
  14981. this.hash_bits = 0; /* log2(hash_size) */
  14982. this.hash_mask = 0; /* hash_size-1 */
  14983. this.hash_shift = 0;
  14984. /* Number of bits by which ins_h must be shifted at each input
  14985. * step. It must be such that after MIN_MATCH steps, the oldest
  14986. * byte no longer takes part in the hash key, that is:
  14987. * hash_shift * MIN_MATCH >= hash_bits
  14988. */
  14989. this.block_start = 0;
  14990. /* Window position at the beginning of the current output block. Gets
  14991. * negative when the window is moved backwards.
  14992. */
  14993. this.match_length = 0; /* length of best match */
  14994. this.prev_match = 0; /* previous match */
  14995. this.match_available = 0; /* set if previous match exists */
  14996. this.strstart = 0; /* start of string to insert */
  14997. this.match_start = 0; /* start of matching string */
  14998. this.lookahead = 0; /* number of valid bytes ahead in window */
  14999. this.prev_length = 0;
  15000. /* Length of the best match at previous step. Matches not greater than this
  15001. * are discarded. This is used in the lazy match evaluation.
  15002. */
  15003. this.max_chain_length = 0;
  15004. /* To speed up deflation, hash chains are never searched beyond this
  15005. * length. A higher limit improves compression ratio but degrades the
  15006. * speed.
  15007. */
  15008. this.max_lazy_match = 0;
  15009. /* Attempt to find a better match only when the current match is strictly
  15010. * smaller than this value. This mechanism is used only for compression
  15011. * levels >= 4.
  15012. */
  15013. // That's alias to max_lazy_match, don't use directly
  15014. //this.max_insert_length = 0;
  15015. /* Insert new strings in the hash table only if the match length is not
  15016. * greater than this length. This saves time but degrades compression.
  15017. * max_insert_length is used only for compression levels <= 3.
  15018. */
  15019. this.level = 0; /* compression level (1..9) */
  15020. this.strategy = 0; /* favor or force Huffman coding*/
  15021. this.good_match = 0;
  15022. /* Use a faster search when the previous match is longer than this */
  15023. this.nice_match = 0; /* Stop searching when current match exceeds this */
  15024. /* used by trees.c: */
  15025. /* Didn't use ct_data typedef below to suppress compiler warning */
  15026. // struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */
  15027. // struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */
  15028. // struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */
  15029. // Use flat array of DOUBLE size, with interleaved fata,
  15030. // because JS does not support effective
  15031. this.dyn_ltree = new utils.Buf16(HEAP_SIZE * 2);
  15032. this.dyn_dtree = new utils.Buf16((2*D_CODES+1) * 2);
  15033. this.bl_tree = new utils.Buf16((2*BL_CODES+1) * 2);
  15034. zero(this.dyn_ltree);
  15035. zero(this.dyn_dtree);
  15036. zero(this.bl_tree);
  15037. this.l_desc = null; /* desc. for literal tree */
  15038. this.d_desc = null; /* desc. for distance tree */
  15039. this.bl_desc = null; /* desc. for bit length tree */
  15040. //ush bl_count[MAX_BITS+1];
  15041. this.bl_count = new utils.Buf16(MAX_BITS+1);
  15042. /* number of codes at each bit length for an optimal tree */
  15043. //int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */
  15044. this.heap = new utils.Buf16(2*L_CODES+1); /* heap used to build the Huffman trees */
  15045. zero(this.heap);
  15046. this.heap_len = 0; /* number of elements in the heap */
  15047. this.heap_max = 0; /* element of largest frequency */
  15048. /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.
  15049. * The same heap array is used to build all trees.
  15050. */
  15051. this.depth = new utils.Buf16(2*L_CODES+1); //uch depth[2*L_CODES+1];
  15052. zero(this.depth);
  15053. /* Depth of each subtree used as tie breaker for trees of equal frequency
  15054. */
  15055. this.l_buf = 0; /* buffer index for literals or lengths */
  15056. this.lit_bufsize = 0;
  15057. /* Size of match buffer for literals/lengths. There are 4 reasons for
  15058. * limiting lit_bufsize to 64K:
  15059. * - frequencies can be kept in 16 bit counters
  15060. * - if compression is not successful for the first block, all input
  15061. * data is still in the window so we can still emit a stored block even
  15062. * when input comes from standard input. (This can also be done for
  15063. * all blocks if lit_bufsize is not greater than 32K.)
  15064. * - if compression is not successful for a file smaller than 64K, we can
  15065. * even emit a stored file instead of a stored block (saving 5 bytes).
  15066. * This is applicable only for zip (not gzip or zlib).
  15067. * - creating new Huffman trees less frequently may not provide fast
  15068. * adaptation to changes in the input data statistics. (Take for
  15069. * example a binary file with poorly compressible code followed by
  15070. * a highly compressible string table.) Smaller buffer sizes give
  15071. * fast adaptation but have of course the overhead of transmitting
  15072. * trees more frequently.
  15073. * - I can't count above 4
  15074. */
  15075. this.last_lit = 0; /* running index in l_buf */
  15076. this.d_buf = 0;
  15077. /* Buffer index for distances. To simplify the code, d_buf and l_buf have
  15078. * the same number of elements. To use different lengths, an extra flag
  15079. * array would be necessary.
  15080. */
  15081. this.opt_len = 0; /* bit length of current block with optimal trees */
  15082. this.static_len = 0; /* bit length of current block with static trees */
  15083. this.matches = 0; /* number of string matches in current block */
  15084. this.insert = 0; /* bytes at end of window left to insert */
  15085. this.bi_buf = 0;
  15086. /* Output buffer. bits are inserted starting at the bottom (least
  15087. * significant bits).
  15088. */
  15089. this.bi_valid = 0;
  15090. /* Number of valid bits in bi_buf. All bits above the last valid bit
  15091. * are always zero.
  15092. */
  15093. // Used for window memory init. We safely ignore it for JS. That makes
  15094. // sense only for pointers and memory check tools.
  15095. //this.high_water = 0;
  15096. /* High water mark offset in window for initialized bytes -- bytes above
  15097. * this are set to zero in order to avoid memory check warnings when
  15098. * longest match routines access bytes past the input. This is then
  15099. * updated to the new high water mark.
  15100. */
  15101. }
  15102. function deflateResetKeep(strm) {
  15103. var s;
  15104. if (!strm || !strm.state) {
  15105. return err(strm, Z_STREAM_ERROR);
  15106. }
  15107. strm.total_in = strm.total_out = 0;
  15108. strm.data_type = Z_UNKNOWN;
  15109. s = strm.state;
  15110. s.pending = 0;
  15111. s.pending_out = 0;
  15112. if (s.wrap < 0) {
  15113. s.wrap = -s.wrap;
  15114. /* was made negative by deflate(..., Z_FINISH); */
  15115. }
  15116. s.status = (s.wrap ? INIT_STATE : BUSY_STATE);
  15117. strm.adler = (s.wrap === 2) ?
  15118. 0 // crc32(0, Z_NULL, 0)
  15119. :
  15120. 1; // adler32(0, Z_NULL, 0)
  15121. s.last_flush = Z_NO_FLUSH;
  15122. trees._tr_init(s);
  15123. return Z_OK;
  15124. }
  15125. function deflateReset(strm) {
  15126. var ret = deflateResetKeep(strm);
  15127. if (ret === Z_OK) {
  15128. lm_init(strm.state);
  15129. }
  15130. return ret;
  15131. }
  15132. function deflateSetHeader(strm, head) {
  15133. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  15134. if (strm.state.wrap !== 2) { return Z_STREAM_ERROR; }
  15135. strm.state.gzhead = head;
  15136. return Z_OK;
  15137. }
  15138. function deflateInit2(strm, level, method, windowBits, memLevel, strategy) {
  15139. if (!strm) { // === Z_NULL
  15140. return Z_STREAM_ERROR;
  15141. }
  15142. var wrap = 1;
  15143. if (level === Z_DEFAULT_COMPRESSION) {
  15144. level = 6;
  15145. }
  15146. if (windowBits < 0) { /* suppress zlib wrapper */
  15147. wrap = 0;
  15148. windowBits = -windowBits;
  15149. }
  15150. else if (windowBits > 15) {
  15151. wrap = 2; /* write gzip wrapper instead */
  15152. windowBits -= 16;
  15153. }
  15154. if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method !== Z_DEFLATED ||
  15155. windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||
  15156. strategy < 0 || strategy > Z_FIXED) {
  15157. return err(strm, Z_STREAM_ERROR);
  15158. }
  15159. if (windowBits === 8) {
  15160. windowBits = 9;
  15161. }
  15162. /* until 256-byte window bug fixed */
  15163. var s = new DeflateState();
  15164. strm.state = s;
  15165. s.strm = strm;
  15166. s.wrap = wrap;
  15167. s.gzhead = null;
  15168. s.w_bits = windowBits;
  15169. s.w_size = 1 << s.w_bits;
  15170. s.w_mask = s.w_size - 1;
  15171. s.hash_bits = memLevel + 7;
  15172. s.hash_size = 1 << s.hash_bits;
  15173. s.hash_mask = s.hash_size - 1;
  15174. s.hash_shift = ~~((s.hash_bits + MIN_MATCH - 1) / MIN_MATCH);
  15175. s.window = new utils.Buf8(s.w_size * 2);
  15176. s.head = new utils.Buf16(s.hash_size);
  15177. s.prev = new utils.Buf16(s.w_size);
  15178. // Don't need mem init magic for JS.
  15179. //s.high_water = 0; /* nothing written to s->window yet */
  15180. s.lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */
  15181. s.pending_buf_size = s.lit_bufsize * 4;
  15182. s.pending_buf = new utils.Buf8(s.pending_buf_size);
  15183. s.d_buf = s.lit_bufsize >> 1;
  15184. s.l_buf = (1 + 2) * s.lit_bufsize;
  15185. s.level = level;
  15186. s.strategy = strategy;
  15187. s.method = method;
  15188. return deflateReset(strm);
  15189. }
  15190. function deflateInit(strm, level) {
  15191. return deflateInit2(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY);
  15192. }
  15193. function deflate(strm, flush) {
  15194. var old_flush, s;
  15195. var beg, val; // for gzip header write only
  15196. if (!strm || !strm.state ||
  15197. flush > Z_BLOCK || flush < 0) {
  15198. return strm ? err(strm, Z_STREAM_ERROR) : Z_STREAM_ERROR;
  15199. }
  15200. s = strm.state;
  15201. if (!strm.output ||
  15202. (!strm.input && strm.avail_in !== 0) ||
  15203. (s.status === FINISH_STATE && flush !== Z_FINISH)) {
  15204. return err(strm, (strm.avail_out === 0) ? Z_BUF_ERROR : Z_STREAM_ERROR);
  15205. }
  15206. s.strm = strm; /* just in case */
  15207. old_flush = s.last_flush;
  15208. s.last_flush = flush;
  15209. /* Write the header */
  15210. if (s.status === INIT_STATE) {
  15211. if (s.wrap === 2) { // GZIP header
  15212. strm.adler = 0; //crc32(0L, Z_NULL, 0);
  15213. put_byte(s, 31);
  15214. put_byte(s, 139);
  15215. put_byte(s, 8);
  15216. if (!s.gzhead) { // s->gzhead == Z_NULL
  15217. put_byte(s, 0);
  15218. put_byte(s, 0);
  15219. put_byte(s, 0);
  15220. put_byte(s, 0);
  15221. put_byte(s, 0);
  15222. put_byte(s, s.level === 9 ? 2 :
  15223. (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
  15224. 4 : 0));
  15225. put_byte(s, OS_CODE);
  15226. s.status = BUSY_STATE;
  15227. }
  15228. else {
  15229. put_byte(s, (s.gzhead.text ? 1 : 0) +
  15230. (s.gzhead.hcrc ? 2 : 0) +
  15231. (!s.gzhead.extra ? 0 : 4) +
  15232. (!s.gzhead.name ? 0 : 8) +
  15233. (!s.gzhead.comment ? 0 : 16)
  15234. );
  15235. put_byte(s, s.gzhead.time & 0xff);
  15236. put_byte(s, (s.gzhead.time >> 8) & 0xff);
  15237. put_byte(s, (s.gzhead.time >> 16) & 0xff);
  15238. put_byte(s, (s.gzhead.time >> 24) & 0xff);
  15239. put_byte(s, s.level === 9 ? 2 :
  15240. (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
  15241. 4 : 0));
  15242. put_byte(s, s.gzhead.os & 0xff);
  15243. if (s.gzhead.extra && s.gzhead.extra.length) {
  15244. put_byte(s, s.gzhead.extra.length & 0xff);
  15245. put_byte(s, (s.gzhead.extra.length >> 8) & 0xff);
  15246. }
  15247. if (s.gzhead.hcrc) {
  15248. strm.adler = crc32(strm.adler, s.pending_buf, s.pending, 0);
  15249. }
  15250. s.gzindex = 0;
  15251. s.status = EXTRA_STATE;
  15252. }
  15253. }
  15254. else // DEFLATE header
  15255. {
  15256. var header = (Z_DEFLATED + ((s.w_bits - 8) << 4)) << 8;
  15257. var level_flags = -1;
  15258. if (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2) {
  15259. level_flags = 0;
  15260. } else if (s.level < 6) {
  15261. level_flags = 1;
  15262. } else if (s.level === 6) {
  15263. level_flags = 2;
  15264. } else {
  15265. level_flags = 3;
  15266. }
  15267. header |= (level_flags << 6);
  15268. if (s.strstart !== 0) { header |= PRESET_DICT; }
  15269. header += 31 - (header % 31);
  15270. s.status = BUSY_STATE;
  15271. putShortMSB(s, header);
  15272. /* Save the adler32 of the preset dictionary: */
  15273. if (s.strstart !== 0) {
  15274. putShortMSB(s, strm.adler >>> 16);
  15275. putShortMSB(s, strm.adler & 0xffff);
  15276. }
  15277. strm.adler = 1; // adler32(0L, Z_NULL, 0);
  15278. }
  15279. }
  15280. //#ifdef GZIP
  15281. if (s.status === EXTRA_STATE) {
  15282. if (s.gzhead.extra/* != Z_NULL*/) {
  15283. beg = s.pending; /* start of bytes to update crc */
  15284. while (s.gzindex < (s.gzhead.extra.length & 0xffff)) {
  15285. if (s.pending === s.pending_buf_size) {
  15286. if (s.gzhead.hcrc && s.pending > beg) {
  15287. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  15288. }
  15289. flush_pending(strm);
  15290. beg = s.pending;
  15291. if (s.pending === s.pending_buf_size) {
  15292. break;
  15293. }
  15294. }
  15295. put_byte(s, s.gzhead.extra[s.gzindex] & 0xff);
  15296. s.gzindex++;
  15297. }
  15298. if (s.gzhead.hcrc && s.pending > beg) {
  15299. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  15300. }
  15301. if (s.gzindex === s.gzhead.extra.length) {
  15302. s.gzindex = 0;
  15303. s.status = NAME_STATE;
  15304. }
  15305. }
  15306. else {
  15307. s.status = NAME_STATE;
  15308. }
  15309. }
  15310. if (s.status === NAME_STATE) {
  15311. if (s.gzhead.name/* != Z_NULL*/) {
  15312. beg = s.pending; /* start of bytes to update crc */
  15313. //int val;
  15314. do {
  15315. if (s.pending === s.pending_buf_size) {
  15316. if (s.gzhead.hcrc && s.pending > beg) {
  15317. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  15318. }
  15319. flush_pending(strm);
  15320. beg = s.pending;
  15321. if (s.pending === s.pending_buf_size) {
  15322. val = 1;
  15323. break;
  15324. }
  15325. }
  15326. // JS specific: little magic to add zero terminator to end of string
  15327. if (s.gzindex < s.gzhead.name.length) {
  15328. val = s.gzhead.name.charCodeAt(s.gzindex++) & 0xff;
  15329. } else {
  15330. val = 0;
  15331. }
  15332. put_byte(s, val);
  15333. } while (val !== 0);
  15334. if (s.gzhead.hcrc && s.pending > beg) {
  15335. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  15336. }
  15337. if (val === 0) {
  15338. s.gzindex = 0;
  15339. s.status = COMMENT_STATE;
  15340. }
  15341. }
  15342. else {
  15343. s.status = COMMENT_STATE;
  15344. }
  15345. }
  15346. if (s.status === COMMENT_STATE) {
  15347. if (s.gzhead.comment/* != Z_NULL*/) {
  15348. beg = s.pending; /* start of bytes to update crc */
  15349. //int val;
  15350. do {
  15351. if (s.pending === s.pending_buf_size) {
  15352. if (s.gzhead.hcrc && s.pending > beg) {
  15353. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  15354. }
  15355. flush_pending(strm);
  15356. beg = s.pending;
  15357. if (s.pending === s.pending_buf_size) {
  15358. val = 1;
  15359. break;
  15360. }
  15361. }
  15362. // JS specific: little magic to add zero terminator to end of string
  15363. if (s.gzindex < s.gzhead.comment.length) {
  15364. val = s.gzhead.comment.charCodeAt(s.gzindex++) & 0xff;
  15365. } else {
  15366. val = 0;
  15367. }
  15368. put_byte(s, val);
  15369. } while (val !== 0);
  15370. if (s.gzhead.hcrc && s.pending > beg) {
  15371. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  15372. }
  15373. if (val === 0) {
  15374. s.status = HCRC_STATE;
  15375. }
  15376. }
  15377. else {
  15378. s.status = HCRC_STATE;
  15379. }
  15380. }
  15381. if (s.status === HCRC_STATE) {
  15382. if (s.gzhead.hcrc) {
  15383. if (s.pending + 2 > s.pending_buf_size) {
  15384. flush_pending(strm);
  15385. }
  15386. if (s.pending + 2 <= s.pending_buf_size) {
  15387. put_byte(s, strm.adler & 0xff);
  15388. put_byte(s, (strm.adler >> 8) & 0xff);
  15389. strm.adler = 0; //crc32(0L, Z_NULL, 0);
  15390. s.status = BUSY_STATE;
  15391. }
  15392. }
  15393. else {
  15394. s.status = BUSY_STATE;
  15395. }
  15396. }
  15397. //#endif
  15398. /* Flush as much pending output as possible */
  15399. if (s.pending !== 0) {
  15400. flush_pending(strm);
  15401. if (strm.avail_out === 0) {
  15402. /* Since avail_out is 0, deflate will be called again with
  15403. * more output space, but possibly with both pending and
  15404. * avail_in equal to zero. There won't be anything to do,
  15405. * but this is not an error situation so make sure we
  15406. * return OK instead of BUF_ERROR at next call of deflate:
  15407. */
  15408. s.last_flush = -1;
  15409. return Z_OK;
  15410. }
  15411. /* Make sure there is something to do and avoid duplicate consecutive
  15412. * flushes. For repeated and useless calls with Z_FINISH, we keep
  15413. * returning Z_STREAM_END instead of Z_BUF_ERROR.
  15414. */
  15415. } else if (strm.avail_in === 0 && rank(flush) <= rank(old_flush) &&
  15416. flush !== Z_FINISH) {
  15417. return err(strm, Z_BUF_ERROR);
  15418. }
  15419. /* User must not provide more input after the first FINISH: */
  15420. if (s.status === FINISH_STATE && strm.avail_in !== 0) {
  15421. return err(strm, Z_BUF_ERROR);
  15422. }
  15423. /* Start a new block or continue the current one.
  15424. */
  15425. if (strm.avail_in !== 0 || s.lookahead !== 0 ||
  15426. (flush !== Z_NO_FLUSH && s.status !== FINISH_STATE)) {
  15427. var bstate = (s.strategy === Z_HUFFMAN_ONLY) ? deflate_huff(s, flush) :
  15428. (s.strategy === Z_RLE ? deflate_rle(s, flush) :
  15429. configuration_table[s.level].func(s, flush));
  15430. if (bstate === BS_FINISH_STARTED || bstate === BS_FINISH_DONE) {
  15431. s.status = FINISH_STATE;
  15432. }
  15433. if (bstate === BS_NEED_MORE || bstate === BS_FINISH_STARTED) {
  15434. if (strm.avail_out === 0) {
  15435. s.last_flush = -1;
  15436. /* avoid BUF_ERROR next call, see above */
  15437. }
  15438. return Z_OK;
  15439. /* If flush != Z_NO_FLUSH && avail_out == 0, the next call
  15440. * of deflate should use the same flush parameter to make sure
  15441. * that the flush is complete. So we don't have to output an
  15442. * empty block here, this will be done at next call. This also
  15443. * ensures that for a very small output buffer, we emit at most
  15444. * one empty block.
  15445. */
  15446. }
  15447. if (bstate === BS_BLOCK_DONE) {
  15448. if (flush === Z_PARTIAL_FLUSH) {
  15449. trees._tr_align(s);
  15450. }
  15451. else if (flush !== Z_BLOCK) { /* FULL_FLUSH or SYNC_FLUSH */
  15452. trees._tr_stored_block(s, 0, 0, false);
  15453. /* For a full flush, this empty block will be recognized
  15454. * as a special marker by inflate_sync().
  15455. */
  15456. if (flush === Z_FULL_FLUSH) {
  15457. /*** CLEAR_HASH(s); ***/ /* forget history */
  15458. zero(s.head); // Fill with NIL (= 0);
  15459. if (s.lookahead === 0) {
  15460. s.strstart = 0;
  15461. s.block_start = 0;
  15462. s.insert = 0;
  15463. }
  15464. }
  15465. }
  15466. flush_pending(strm);
  15467. if (strm.avail_out === 0) {
  15468. s.last_flush = -1; /* avoid BUF_ERROR at next call, see above */
  15469. return Z_OK;
  15470. }
  15471. }
  15472. }
  15473. //Assert(strm->avail_out > 0, "bug2");
  15474. //if (strm.avail_out <= 0) { throw new Error("bug2");}
  15475. if (flush !== Z_FINISH) { return Z_OK; }
  15476. if (s.wrap <= 0) { return Z_STREAM_END; }
  15477. /* Write the trailer */
  15478. if (s.wrap === 2) {
  15479. put_byte(s, strm.adler & 0xff);
  15480. put_byte(s, (strm.adler >> 8) & 0xff);
  15481. put_byte(s, (strm.adler >> 16) & 0xff);
  15482. put_byte(s, (strm.adler >> 24) & 0xff);
  15483. put_byte(s, strm.total_in & 0xff);
  15484. put_byte(s, (strm.total_in >> 8) & 0xff);
  15485. put_byte(s, (strm.total_in >> 16) & 0xff);
  15486. put_byte(s, (strm.total_in >> 24) & 0xff);
  15487. }
  15488. else
  15489. {
  15490. putShortMSB(s, strm.adler >>> 16);
  15491. putShortMSB(s, strm.adler & 0xffff);
  15492. }
  15493. flush_pending(strm);
  15494. /* If avail_out is zero, the application will call deflate again
  15495. * to flush the rest.
  15496. */
  15497. if (s.wrap > 0) { s.wrap = -s.wrap; }
  15498. /* write the trailer only once! */
  15499. return s.pending !== 0 ? Z_OK : Z_STREAM_END;
  15500. }
  15501. function deflateEnd(strm) {
  15502. var status;
  15503. if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) {
  15504. return Z_STREAM_ERROR;
  15505. }
  15506. status = strm.state.status;
  15507. if (status !== INIT_STATE &&
  15508. status !== EXTRA_STATE &&
  15509. status !== NAME_STATE &&
  15510. status !== COMMENT_STATE &&
  15511. status !== HCRC_STATE &&
  15512. status !== BUSY_STATE &&
  15513. status !== FINISH_STATE
  15514. ) {
  15515. return err(strm, Z_STREAM_ERROR);
  15516. }
  15517. strm.state = null;
  15518. return status === BUSY_STATE ? err(strm, Z_DATA_ERROR) : Z_OK;
  15519. }
  15520. /* =========================================================================
  15521. * Copy the source state to the destination state
  15522. */
  15523. //function deflateCopy(dest, source) {
  15524. //
  15525. //}
  15526. exports.deflateInit = deflateInit;
  15527. exports.deflateInit2 = deflateInit2;
  15528. exports.deflateReset = deflateReset;
  15529. exports.deflateResetKeep = deflateResetKeep;
  15530. exports.deflateSetHeader = deflateSetHeader;
  15531. exports.deflate = deflate;
  15532. exports.deflateEnd = deflateEnd;
  15533. exports.deflateInfo = 'pako deflate (from Nodeca project)';
  15534. /* Not implemented
  15535. exports.deflateBound = deflateBound;
  15536. exports.deflateCopy = deflateCopy;
  15537. exports.deflateSetDictionary = deflateSetDictionary;
  15538. exports.deflateParams = deflateParams;
  15539. exports.deflatePending = deflatePending;
  15540. exports.deflatePrime = deflatePrime;
  15541. exports.deflateTune = deflateTune;
  15542. */
  15543. },{"../utils/common":52,"./adler32":54,"./crc32":56,"./messages":62,"./trees":63}],58:[function(require,module,exports){
  15544. 'use strict';
  15545. function GZheader() {
  15546. /* true if compressed data believed to be text */
  15547. this.text = 0;
  15548. /* modification time */
  15549. this.time = 0;
  15550. /* extra flags (not used when writing a gzip file) */
  15551. this.xflags = 0;
  15552. /* operating system */
  15553. this.os = 0;
  15554. /* pointer to extra field or Z_NULL if none */
  15555. this.extra = null;
  15556. /* extra field length (valid if extra != Z_NULL) */
  15557. this.extra_len = 0; // Actually, we don't need it in JS,
  15558. // but leave for few code modifications
  15559. //
  15560. // Setup limits is not necessary because in js we should not preallocate memory
  15561. // for inflate use constant limit in 65536 bytes
  15562. //
  15563. /* space at extra (only when reading header) */
  15564. // this.extra_max = 0;
  15565. /* pointer to zero-terminated file name or Z_NULL */
  15566. this.name = '';
  15567. /* space at name (only when reading header) */
  15568. // this.name_max = 0;
  15569. /* pointer to zero-terminated comment or Z_NULL */
  15570. this.comment = '';
  15571. /* space at comment (only when reading header) */
  15572. // this.comm_max = 0;
  15573. /* true if there was or will be a header crc */
  15574. this.hcrc = 0;
  15575. /* true when done reading gzip header (not used when writing a gzip file) */
  15576. this.done = false;
  15577. }
  15578. module.exports = GZheader;
  15579. },{}],59:[function(require,module,exports){
  15580. 'use strict';
  15581. // See state defs from inflate.js
  15582. var BAD = 30; /* got a data error -- remain here until reset */
  15583. var TYPE = 12; /* i: waiting for type bits, including last-flag bit */
  15584. /*
  15585. Decode literal, length, and distance codes and write out the resulting
  15586. literal and match bytes until either not enough input or output is
  15587. available, an end-of-block is encountered, or a data error is encountered.
  15588. When large enough input and output buffers are supplied to inflate(), for
  15589. example, a 16K input buffer and a 64K output buffer, more than 95% of the
  15590. inflate execution time is spent in this routine.
  15591. Entry assumptions:
  15592. state.mode === LEN
  15593. strm.avail_in >= 6
  15594. strm.avail_out >= 258
  15595. start >= strm.avail_out
  15596. state.bits < 8
  15597. On return, state.mode is one of:
  15598. LEN -- ran out of enough output space or enough available input
  15599. TYPE -- reached end of block code, inflate() to interpret next block
  15600. BAD -- error in block data
  15601. Notes:
  15602. - The maximum input bits used by a length/distance pair is 15 bits for the
  15603. length code, 5 bits for the length extra, 15 bits for the distance code,
  15604. and 13 bits for the distance extra. This totals 48 bits, or six bytes.
  15605. Therefore if strm.avail_in >= 6, then there is enough input to avoid
  15606. checking for available input while decoding.
  15607. - The maximum bytes that a single length/distance pair can output is 258
  15608. bytes, which is the maximum length that can be coded. inflate_fast()
  15609. requires strm.avail_out >= 258 for each loop to avoid checking for
  15610. output space.
  15611. */
  15612. module.exports = function inflate_fast(strm, start) {
  15613. var state;
  15614. var _in; /* local strm.input */
  15615. var last; /* have enough input while in < last */
  15616. var _out; /* local strm.output */
  15617. var beg; /* inflate()'s initial strm.output */
  15618. var end; /* while out < end, enough space available */
  15619. //#ifdef INFLATE_STRICT
  15620. var dmax; /* maximum distance from zlib header */
  15621. //#endif
  15622. var wsize; /* window size or zero if not using window */
  15623. var whave; /* valid bytes in the window */
  15624. var wnext; /* window write index */
  15625. // Use `s_window` instead `window`, avoid conflict with instrumentation tools
  15626. var s_window; /* allocated sliding window, if wsize != 0 */
  15627. var hold; /* local strm.hold */
  15628. var bits; /* local strm.bits */
  15629. var lcode; /* local strm.lencode */
  15630. var dcode; /* local strm.distcode */
  15631. var lmask; /* mask for first level of length codes */
  15632. var dmask; /* mask for first level of distance codes */
  15633. var here; /* retrieved table entry */
  15634. var op; /* code bits, operation, extra bits, or */
  15635. /* window position, window bytes to copy */
  15636. var len; /* match length, unused bytes */
  15637. var dist; /* match distance */
  15638. var from; /* where to copy match from */
  15639. var from_source;
  15640. var input, output; // JS specific, because we have no pointers
  15641. /* copy state to local variables */
  15642. state = strm.state;
  15643. //here = state.here;
  15644. _in = strm.next_in;
  15645. input = strm.input;
  15646. last = _in + (strm.avail_in - 5);
  15647. _out = strm.next_out;
  15648. output = strm.output;
  15649. beg = _out - (start - strm.avail_out);
  15650. end = _out + (strm.avail_out - 257);
  15651. //#ifdef INFLATE_STRICT
  15652. dmax = state.dmax;
  15653. //#endif
  15654. wsize = state.wsize;
  15655. whave = state.whave;
  15656. wnext = state.wnext;
  15657. s_window = state.window;
  15658. hold = state.hold;
  15659. bits = state.bits;
  15660. lcode = state.lencode;
  15661. dcode = state.distcode;
  15662. lmask = (1 << state.lenbits) - 1;
  15663. dmask = (1 << state.distbits) - 1;
  15664. /* decode literals and length/distances until end-of-block or not enough
  15665. input data or output space */
  15666. top:
  15667. do {
  15668. if (bits < 15) {
  15669. hold += input[_in++] << bits;
  15670. bits += 8;
  15671. hold += input[_in++] << bits;
  15672. bits += 8;
  15673. }
  15674. here = lcode[hold & lmask];
  15675. dolen:
  15676. for (;;) { // Goto emulation
  15677. op = here >>> 24/*here.bits*/;
  15678. hold >>>= op;
  15679. bits -= op;
  15680. op = (here >>> 16) & 0xff/*here.op*/;
  15681. if (op === 0) { /* literal */
  15682. //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
  15683. // "inflate: literal '%c'\n" :
  15684. // "inflate: literal 0x%02x\n", here.val));
  15685. output[_out++] = here & 0xffff/*here.val*/;
  15686. }
  15687. else if (op & 16) { /* length base */
  15688. len = here & 0xffff/*here.val*/;
  15689. op &= 15; /* number of extra bits */
  15690. if (op) {
  15691. if (bits < op) {
  15692. hold += input[_in++] << bits;
  15693. bits += 8;
  15694. }
  15695. len += hold & ((1 << op) - 1);
  15696. hold >>>= op;
  15697. bits -= op;
  15698. }
  15699. //Tracevv((stderr, "inflate: length %u\n", len));
  15700. if (bits < 15) {
  15701. hold += input[_in++] << bits;
  15702. bits += 8;
  15703. hold += input[_in++] << bits;
  15704. bits += 8;
  15705. }
  15706. here = dcode[hold & dmask];
  15707. dodist:
  15708. for (;;) { // goto emulation
  15709. op = here >>> 24/*here.bits*/;
  15710. hold >>>= op;
  15711. bits -= op;
  15712. op = (here >>> 16) & 0xff/*here.op*/;
  15713. if (op & 16) { /* distance base */
  15714. dist = here & 0xffff/*here.val*/;
  15715. op &= 15; /* number of extra bits */
  15716. if (bits < op) {
  15717. hold += input[_in++] << bits;
  15718. bits += 8;
  15719. if (bits < op) {
  15720. hold += input[_in++] << bits;
  15721. bits += 8;
  15722. }
  15723. }
  15724. dist += hold & ((1 << op) - 1);
  15725. //#ifdef INFLATE_STRICT
  15726. if (dist > dmax) {
  15727. strm.msg = 'invalid distance too far back';
  15728. state.mode = BAD;
  15729. break top;
  15730. }
  15731. //#endif
  15732. hold >>>= op;
  15733. bits -= op;
  15734. //Tracevv((stderr, "inflate: distance %u\n", dist));
  15735. op = _out - beg; /* max distance in output */
  15736. if (dist > op) { /* see if copy from window */
  15737. op = dist - op; /* distance back in window */
  15738. if (op > whave) {
  15739. if (state.sane) {
  15740. strm.msg = 'invalid distance too far back';
  15741. state.mode = BAD;
  15742. break top;
  15743. }
  15744. // (!) This block is disabled in zlib defailts,
  15745. // don't enable it for binary compatibility
  15746. //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
  15747. // if (len <= op - whave) {
  15748. // do {
  15749. // output[_out++] = 0;
  15750. // } while (--len);
  15751. // continue top;
  15752. // }
  15753. // len -= op - whave;
  15754. // do {
  15755. // output[_out++] = 0;
  15756. // } while (--op > whave);
  15757. // if (op === 0) {
  15758. // from = _out - dist;
  15759. // do {
  15760. // output[_out++] = output[from++];
  15761. // } while (--len);
  15762. // continue top;
  15763. // }
  15764. //#endif
  15765. }
  15766. from = 0; // window index
  15767. from_source = s_window;
  15768. if (wnext === 0) { /* very common case */
  15769. from += wsize - op;
  15770. if (op < len) { /* some from window */
  15771. len -= op;
  15772. do {
  15773. output[_out++] = s_window[from++];
  15774. } while (--op);
  15775. from = _out - dist; /* rest from output */
  15776. from_source = output;
  15777. }
  15778. }
  15779. else if (wnext < op) { /* wrap around window */
  15780. from += wsize + wnext - op;
  15781. op -= wnext;
  15782. if (op < len) { /* some from end of window */
  15783. len -= op;
  15784. do {
  15785. output[_out++] = s_window[from++];
  15786. } while (--op);
  15787. from = 0;
  15788. if (wnext < len) { /* some from start of window */
  15789. op = wnext;
  15790. len -= op;
  15791. do {
  15792. output[_out++] = s_window[from++];
  15793. } while (--op);
  15794. from = _out - dist; /* rest from output */
  15795. from_source = output;
  15796. }
  15797. }
  15798. }
  15799. else { /* contiguous in window */
  15800. from += wnext - op;
  15801. if (op < len) { /* some from window */
  15802. len -= op;
  15803. do {
  15804. output[_out++] = s_window[from++];
  15805. } while (--op);
  15806. from = _out - dist; /* rest from output */
  15807. from_source = output;
  15808. }
  15809. }
  15810. while (len > 2) {
  15811. output[_out++] = from_source[from++];
  15812. output[_out++] = from_source[from++];
  15813. output[_out++] = from_source[from++];
  15814. len -= 3;
  15815. }
  15816. if (len) {
  15817. output[_out++] = from_source[from++];
  15818. if (len > 1) {
  15819. output[_out++] = from_source[from++];
  15820. }
  15821. }
  15822. }
  15823. else {
  15824. from = _out - dist; /* copy direct from output */
  15825. do { /* minimum length is three */
  15826. output[_out++] = output[from++];
  15827. output[_out++] = output[from++];
  15828. output[_out++] = output[from++];
  15829. len -= 3;
  15830. } while (len > 2);
  15831. if (len) {
  15832. output[_out++] = output[from++];
  15833. if (len > 1) {
  15834. output[_out++] = output[from++];
  15835. }
  15836. }
  15837. }
  15838. }
  15839. else if ((op & 64) === 0) { /* 2nd level distance code */
  15840. here = dcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
  15841. continue dodist;
  15842. }
  15843. else {
  15844. strm.msg = 'invalid distance code';
  15845. state.mode = BAD;
  15846. break top;
  15847. }
  15848. break; // need to emulate goto via "continue"
  15849. }
  15850. }
  15851. else if ((op & 64) === 0) { /* 2nd level length code */
  15852. here = lcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
  15853. continue dolen;
  15854. }
  15855. else if (op & 32) { /* end-of-block */
  15856. //Tracevv((stderr, "inflate: end of block\n"));
  15857. state.mode = TYPE;
  15858. break top;
  15859. }
  15860. else {
  15861. strm.msg = 'invalid literal/length code';
  15862. state.mode = BAD;
  15863. break top;
  15864. }
  15865. break; // need to emulate goto via "continue"
  15866. }
  15867. } while (_in < last && _out < end);
  15868. /* return unused bytes (on entry, bits < 8, so in won't go too far back) */
  15869. len = bits >> 3;
  15870. _in -= len;
  15871. bits -= len << 3;
  15872. hold &= (1 << bits) - 1;
  15873. /* update state and return */
  15874. strm.next_in = _in;
  15875. strm.next_out = _out;
  15876. strm.avail_in = (_in < last ? 5 + (last - _in) : 5 - (_in - last));
  15877. strm.avail_out = (_out < end ? 257 + (end - _out) : 257 - (_out - end));
  15878. state.hold = hold;
  15879. state.bits = bits;
  15880. return;
  15881. };
  15882. },{}],60:[function(require,module,exports){
  15883. 'use strict';
  15884. var utils = require('../utils/common');
  15885. var adler32 = require('./adler32');
  15886. var crc32 = require('./crc32');
  15887. var inflate_fast = require('./inffast');
  15888. var inflate_table = require('./inftrees');
  15889. var CODES = 0;
  15890. var LENS = 1;
  15891. var DISTS = 2;
  15892. /* Public constants ==========================================================*/
  15893. /* ===========================================================================*/
  15894. /* Allowed flush values; see deflate() and inflate() below for details */
  15895. //var Z_NO_FLUSH = 0;
  15896. //var Z_PARTIAL_FLUSH = 1;
  15897. //var Z_SYNC_FLUSH = 2;
  15898. //var Z_FULL_FLUSH = 3;
  15899. var Z_FINISH = 4;
  15900. var Z_BLOCK = 5;
  15901. var Z_TREES = 6;
  15902. /* Return codes for the compression/decompression functions. Negative values
  15903. * are errors, positive values are used for special but normal events.
  15904. */
  15905. var Z_OK = 0;
  15906. var Z_STREAM_END = 1;
  15907. var Z_NEED_DICT = 2;
  15908. //var Z_ERRNO = -1;
  15909. var Z_STREAM_ERROR = -2;
  15910. var Z_DATA_ERROR = -3;
  15911. var Z_MEM_ERROR = -4;
  15912. var Z_BUF_ERROR = -5;
  15913. //var Z_VERSION_ERROR = -6;
  15914. /* The deflate compression method */
  15915. var Z_DEFLATED = 8;
  15916. /* STATES ====================================================================*/
  15917. /* ===========================================================================*/
  15918. var HEAD = 1; /* i: waiting for magic header */
  15919. var FLAGS = 2; /* i: waiting for method and flags (gzip) */
  15920. var TIME = 3; /* i: waiting for modification time (gzip) */
  15921. var OS = 4; /* i: waiting for extra flags and operating system (gzip) */
  15922. var EXLEN = 5; /* i: waiting for extra length (gzip) */
  15923. var EXTRA = 6; /* i: waiting for extra bytes (gzip) */
  15924. var NAME = 7; /* i: waiting for end of file name (gzip) */
  15925. var COMMENT = 8; /* i: waiting for end of comment (gzip) */
  15926. var HCRC = 9; /* i: waiting for header crc (gzip) */
  15927. var DICTID = 10; /* i: waiting for dictionary check value */
  15928. var DICT = 11; /* waiting for inflateSetDictionary() call */
  15929. var TYPE = 12; /* i: waiting for type bits, including last-flag bit */
  15930. var TYPEDO = 13; /* i: same, but skip check to exit inflate on new block */
  15931. var STORED = 14; /* i: waiting for stored size (length and complement) */
  15932. var COPY_ = 15; /* i/o: same as COPY below, but only first time in */
  15933. var COPY = 16; /* i/o: waiting for input or output to copy stored block */
  15934. var TABLE = 17; /* i: waiting for dynamic block table lengths */
  15935. var LENLENS = 18; /* i: waiting for code length code lengths */
  15936. var CODELENS = 19; /* i: waiting for length/lit and distance code lengths */
  15937. var LEN_ = 20; /* i: same as LEN below, but only first time in */
  15938. var LEN = 21; /* i: waiting for length/lit/eob code */
  15939. var LENEXT = 22; /* i: waiting for length extra bits */
  15940. var DIST = 23; /* i: waiting for distance code */
  15941. var DISTEXT = 24; /* i: waiting for distance extra bits */
  15942. var MATCH = 25; /* o: waiting for output space to copy string */
  15943. var LIT = 26; /* o: waiting for output space to write literal */
  15944. var CHECK = 27; /* i: waiting for 32-bit check value */
  15945. var LENGTH = 28; /* i: waiting for 32-bit length (gzip) */
  15946. var DONE = 29; /* finished check, done -- remain here until reset */
  15947. var BAD = 30; /* got a data error -- remain here until reset */
  15948. var MEM = 31; /* got an inflate() memory error -- remain here until reset */
  15949. var SYNC = 32; /* looking for synchronization bytes to restart inflate() */
  15950. /* ===========================================================================*/
  15951. var ENOUGH_LENS = 852;
  15952. var ENOUGH_DISTS = 592;
  15953. //var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
  15954. var MAX_WBITS = 15;
  15955. /* 32K LZ77 window */
  15956. var DEF_WBITS = MAX_WBITS;
  15957. function ZSWAP32(q) {
  15958. return (((q >>> 24) & 0xff) +
  15959. ((q >>> 8) & 0xff00) +
  15960. ((q & 0xff00) << 8) +
  15961. ((q & 0xff) << 24));
  15962. }
  15963. function InflateState() {
  15964. this.mode = 0; /* current inflate mode */
  15965. this.last = false; /* true if processing last block */
  15966. this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
  15967. this.havedict = false; /* true if dictionary provided */
  15968. this.flags = 0; /* gzip header method and flags (0 if zlib) */
  15969. this.dmax = 0; /* zlib header max distance (INFLATE_STRICT) */
  15970. this.check = 0; /* protected copy of check value */
  15971. this.total = 0; /* protected copy of output count */
  15972. // TODO: may be {}
  15973. this.head = null; /* where to save gzip header information */
  15974. /* sliding window */
  15975. this.wbits = 0; /* log base 2 of requested window size */
  15976. this.wsize = 0; /* window size or zero if not using window */
  15977. this.whave = 0; /* valid bytes in the window */
  15978. this.wnext = 0; /* window write index */
  15979. this.window = null; /* allocated sliding window, if needed */
  15980. /* bit accumulator */
  15981. this.hold = 0; /* input bit accumulator */
  15982. this.bits = 0; /* number of bits in "in" */
  15983. /* for string and stored block copying */
  15984. this.length = 0; /* literal or length of data to copy */
  15985. this.offset = 0; /* distance back to copy string from */
  15986. /* for table and code decoding */
  15987. this.extra = 0; /* extra bits needed */
  15988. /* fixed and dynamic code tables */
  15989. this.lencode = null; /* starting table for length/literal codes */
  15990. this.distcode = null; /* starting table for distance codes */
  15991. this.lenbits = 0; /* index bits for lencode */
  15992. this.distbits = 0; /* index bits for distcode */
  15993. /* dynamic table building */
  15994. this.ncode = 0; /* number of code length code lengths */
  15995. this.nlen = 0; /* number of length code lengths */
  15996. this.ndist = 0; /* number of distance code lengths */
  15997. this.have = 0; /* number of code lengths in lens[] */
  15998. this.next = null; /* next available space in codes[] */
  15999. this.lens = new utils.Buf16(320); /* temporary storage for code lengths */
  16000. this.work = new utils.Buf16(288); /* work area for code table building */
  16001. /*
  16002. because we don't have pointers in js, we use lencode and distcode directly
  16003. as buffers so we don't need codes
  16004. */
  16005. //this.codes = new utils.Buf32(ENOUGH); /* space for code tables */
  16006. this.lendyn = null; /* dynamic table for length/literal codes (JS specific) */
  16007. this.distdyn = null; /* dynamic table for distance codes (JS specific) */
  16008. this.sane = 0; /* if false, allow invalid distance too far */
  16009. this.back = 0; /* bits back of last unprocessed length/lit */
  16010. this.was = 0; /* initial length of match */
  16011. }
  16012. function inflateResetKeep(strm) {
  16013. var state;
  16014. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  16015. state = strm.state;
  16016. strm.total_in = strm.total_out = state.total = 0;
  16017. strm.msg = ''; /*Z_NULL*/
  16018. if (state.wrap) { /* to support ill-conceived Java test suite */
  16019. strm.adler = state.wrap & 1;
  16020. }
  16021. state.mode = HEAD;
  16022. state.last = 0;
  16023. state.havedict = 0;
  16024. state.dmax = 32768;
  16025. state.head = null/*Z_NULL*/;
  16026. state.hold = 0;
  16027. state.bits = 0;
  16028. //state.lencode = state.distcode = state.next = state.codes;
  16029. state.lencode = state.lendyn = new utils.Buf32(ENOUGH_LENS);
  16030. state.distcode = state.distdyn = new utils.Buf32(ENOUGH_DISTS);
  16031. state.sane = 1;
  16032. state.back = -1;
  16033. //Tracev((stderr, "inflate: reset\n"));
  16034. return Z_OK;
  16035. }
  16036. function inflateReset(strm) {
  16037. var state;
  16038. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  16039. state = strm.state;
  16040. state.wsize = 0;
  16041. state.whave = 0;
  16042. state.wnext = 0;
  16043. return inflateResetKeep(strm);
  16044. }
  16045. function inflateReset2(strm, windowBits) {
  16046. var wrap;
  16047. var state;
  16048. /* get the state */
  16049. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  16050. state = strm.state;
  16051. /* extract wrap request from windowBits parameter */
  16052. if (windowBits < 0) {
  16053. wrap = 0;
  16054. windowBits = -windowBits;
  16055. }
  16056. else {
  16057. wrap = (windowBits >> 4) + 1;
  16058. if (windowBits < 48) {
  16059. windowBits &= 15;
  16060. }
  16061. }
  16062. /* set number of window bits, free window if different */
  16063. if (windowBits && (windowBits < 8 || windowBits > 15)) {
  16064. return Z_STREAM_ERROR;
  16065. }
  16066. if (state.window !== null && state.wbits !== windowBits) {
  16067. state.window = null;
  16068. }
  16069. /* update state and reset the rest of it */
  16070. state.wrap = wrap;
  16071. state.wbits = windowBits;
  16072. return inflateReset(strm);
  16073. }
  16074. function inflateInit2(strm, windowBits) {
  16075. var ret;
  16076. var state;
  16077. if (!strm) { return Z_STREAM_ERROR; }
  16078. //strm.msg = Z_NULL; /* in case we return an error */
  16079. state = new InflateState();
  16080. //if (state === Z_NULL) return Z_MEM_ERROR;
  16081. //Tracev((stderr, "inflate: allocated\n"));
  16082. strm.state = state;
  16083. state.window = null/*Z_NULL*/;
  16084. ret = inflateReset2(strm, windowBits);
  16085. if (ret !== Z_OK) {
  16086. strm.state = null/*Z_NULL*/;
  16087. }
  16088. return ret;
  16089. }
  16090. function inflateInit(strm) {
  16091. return inflateInit2(strm, DEF_WBITS);
  16092. }
  16093. /*
  16094. Return state with length and distance decoding tables and index sizes set to
  16095. fixed code decoding. Normally this returns fixed tables from inffixed.h.
  16096. If BUILDFIXED is defined, then instead this routine builds the tables the
  16097. first time it's called, and returns those tables the first time and
  16098. thereafter. This reduces the size of the code by about 2K bytes, in
  16099. exchange for a little execution time. However, BUILDFIXED should not be
  16100. used for threaded applications, since the rewriting of the tables and virgin
  16101. may not be thread-safe.
  16102. */
  16103. var virgin = true;
  16104. var lenfix, distfix; // We have no pointers in JS, so keep tables separate
  16105. function fixedtables(state) {
  16106. /* build fixed huffman tables if first call (may not be thread safe) */
  16107. if (virgin) {
  16108. var sym;
  16109. lenfix = new utils.Buf32(512);
  16110. distfix = new utils.Buf32(32);
  16111. /* literal/length table */
  16112. sym = 0;
  16113. while (sym < 144) { state.lens[sym++] = 8; }
  16114. while (sym < 256) { state.lens[sym++] = 9; }
  16115. while (sym < 280) { state.lens[sym++] = 7; }
  16116. while (sym < 288) { state.lens[sym++] = 8; }
  16117. inflate_table(LENS, state.lens, 0, 288, lenfix, 0, state.work, {bits: 9});
  16118. /* distance table */
  16119. sym = 0;
  16120. while (sym < 32) { state.lens[sym++] = 5; }
  16121. inflate_table(DISTS, state.lens, 0, 32, distfix, 0, state.work, {bits: 5});
  16122. /* do this just once */
  16123. virgin = false;
  16124. }
  16125. state.lencode = lenfix;
  16126. state.lenbits = 9;
  16127. state.distcode = distfix;
  16128. state.distbits = 5;
  16129. }
  16130. /*
  16131. Update the window with the last wsize (normally 32K) bytes written before
  16132. returning. If window does not exist yet, create it. This is only called
  16133. when a window is already in use, or when output has been written during this
  16134. inflate call, but the end of the deflate stream has not been reached yet.
  16135. It is also called to create a window for dictionary data when a dictionary
  16136. is loaded.
  16137. Providing output buffers larger than 32K to inflate() should provide a speed
  16138. advantage, since only the last 32K of output is copied to the sliding window
  16139. upon return from inflate(), and since all distances after the first 32K of
  16140. output will fall in the output data, making match copies simpler and faster.
  16141. The advantage may be dependent on the size of the processor's data caches.
  16142. */
  16143. function updatewindow(strm, src, end, copy) {
  16144. var dist;
  16145. var state = strm.state;
  16146. /* if it hasn't been done already, allocate space for the window */
  16147. if (state.window === null) {
  16148. state.wsize = 1 << state.wbits;
  16149. state.wnext = 0;
  16150. state.whave = 0;
  16151. state.window = new utils.Buf8(state.wsize);
  16152. }
  16153. /* copy state->wsize or less output bytes into the circular window */
  16154. if (copy >= state.wsize) {
  16155. utils.arraySet(state.window,src, end - state.wsize, state.wsize, 0);
  16156. state.wnext = 0;
  16157. state.whave = state.wsize;
  16158. }
  16159. else {
  16160. dist = state.wsize - state.wnext;
  16161. if (dist > copy) {
  16162. dist = copy;
  16163. }
  16164. //zmemcpy(state->window + state->wnext, end - copy, dist);
  16165. utils.arraySet(state.window,src, end - copy, dist, state.wnext);
  16166. copy -= dist;
  16167. if (copy) {
  16168. //zmemcpy(state->window, end - copy, copy);
  16169. utils.arraySet(state.window,src, end - copy, copy, 0);
  16170. state.wnext = copy;
  16171. state.whave = state.wsize;
  16172. }
  16173. else {
  16174. state.wnext += dist;
  16175. if (state.wnext === state.wsize) { state.wnext = 0; }
  16176. if (state.whave < state.wsize) { state.whave += dist; }
  16177. }
  16178. }
  16179. return 0;
  16180. }
  16181. function inflate(strm, flush) {
  16182. var state;
  16183. var input, output; // input/output buffers
  16184. var next; /* next input INDEX */
  16185. var put; /* next output INDEX */
  16186. var have, left; /* available input and output */
  16187. var hold; /* bit buffer */
  16188. var bits; /* bits in bit buffer */
  16189. var _in, _out; /* save starting available input and output */
  16190. var copy; /* number of stored or match bytes to copy */
  16191. var from; /* where to copy match bytes from */
  16192. var from_source;
  16193. var here = 0; /* current decoding table entry */
  16194. var here_bits, here_op, here_val; // paked "here" denormalized (JS specific)
  16195. //var last; /* parent table entry */
  16196. var last_bits, last_op, last_val; // paked "last" denormalized (JS specific)
  16197. var len; /* length to copy for repeats, bits to drop */
  16198. var ret; /* return code */
  16199. var hbuf = new utils.Buf8(4); /* buffer for gzip header crc calculation */
  16200. var opts;
  16201. var n; // temporary var for NEED_BITS
  16202. var order = /* permutation of code lengths */
  16203. [16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15];
  16204. if (!strm || !strm.state || !strm.output ||
  16205. (!strm.input && strm.avail_in !== 0)) {
  16206. return Z_STREAM_ERROR;
  16207. }
  16208. state = strm.state;
  16209. if (state.mode === TYPE) { state.mode = TYPEDO; } /* skip check */
  16210. //--- LOAD() ---
  16211. put = strm.next_out;
  16212. output = strm.output;
  16213. left = strm.avail_out;
  16214. next = strm.next_in;
  16215. input = strm.input;
  16216. have = strm.avail_in;
  16217. hold = state.hold;
  16218. bits = state.bits;
  16219. //---
  16220. _in = have;
  16221. _out = left;
  16222. ret = Z_OK;
  16223. inf_leave: // goto emulation
  16224. for (;;) {
  16225. switch (state.mode) {
  16226. case HEAD:
  16227. if (state.wrap === 0) {
  16228. state.mode = TYPEDO;
  16229. break;
  16230. }
  16231. //=== NEEDBITS(16);
  16232. while (bits < 16) {
  16233. if (have === 0) { break inf_leave; }
  16234. have--;
  16235. hold += input[next++] << bits;
  16236. bits += 8;
  16237. }
  16238. //===//
  16239. if ((state.wrap & 2) && hold === 0x8b1f) { /* gzip header */
  16240. state.check = 0/*crc32(0L, Z_NULL, 0)*/;
  16241. //=== CRC2(state.check, hold);
  16242. hbuf[0] = hold & 0xff;
  16243. hbuf[1] = (hold >>> 8) & 0xff;
  16244. state.check = crc32(state.check, hbuf, 2, 0);
  16245. //===//
  16246. //=== INITBITS();
  16247. hold = 0;
  16248. bits = 0;
  16249. //===//
  16250. state.mode = FLAGS;
  16251. break;
  16252. }
  16253. state.flags = 0; /* expect zlib header */
  16254. if (state.head) {
  16255. state.head.done = false;
  16256. }
  16257. if (!(state.wrap & 1) || /* check if zlib header allowed */
  16258. (((hold & 0xff)/*BITS(8)*/ << 8) + (hold >> 8)) % 31) {
  16259. strm.msg = 'incorrect header check';
  16260. state.mode = BAD;
  16261. break;
  16262. }
  16263. if ((hold & 0x0f)/*BITS(4)*/ !== Z_DEFLATED) {
  16264. strm.msg = 'unknown compression method';
  16265. state.mode = BAD;
  16266. break;
  16267. }
  16268. //--- DROPBITS(4) ---//
  16269. hold >>>= 4;
  16270. bits -= 4;
  16271. //---//
  16272. len = (hold & 0x0f)/*BITS(4)*/ + 8;
  16273. if (state.wbits === 0) {
  16274. state.wbits = len;
  16275. }
  16276. else if (len > state.wbits) {
  16277. strm.msg = 'invalid window size';
  16278. state.mode = BAD;
  16279. break;
  16280. }
  16281. state.dmax = 1 << len;
  16282. //Tracev((stderr, "inflate: zlib header ok\n"));
  16283. strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
  16284. state.mode = hold & 0x200 ? DICTID : TYPE;
  16285. //=== INITBITS();
  16286. hold = 0;
  16287. bits = 0;
  16288. //===//
  16289. break;
  16290. case FLAGS:
  16291. //=== NEEDBITS(16); */
  16292. while (bits < 16) {
  16293. if (have === 0) { break inf_leave; }
  16294. have--;
  16295. hold += input[next++] << bits;
  16296. bits += 8;
  16297. }
  16298. //===//
  16299. state.flags = hold;
  16300. if ((state.flags & 0xff) !== Z_DEFLATED) {
  16301. strm.msg = 'unknown compression method';
  16302. state.mode = BAD;
  16303. break;
  16304. }
  16305. if (state.flags & 0xe000) {
  16306. strm.msg = 'unknown header flags set';
  16307. state.mode = BAD;
  16308. break;
  16309. }
  16310. if (state.head) {
  16311. state.head.text = ((hold >> 8) & 1);
  16312. }
  16313. if (state.flags & 0x0200) {
  16314. //=== CRC2(state.check, hold);
  16315. hbuf[0] = hold & 0xff;
  16316. hbuf[1] = (hold >>> 8) & 0xff;
  16317. state.check = crc32(state.check, hbuf, 2, 0);
  16318. //===//
  16319. }
  16320. //=== INITBITS();
  16321. hold = 0;
  16322. bits = 0;
  16323. //===//
  16324. state.mode = TIME;
  16325. /* falls through */
  16326. case TIME:
  16327. //=== NEEDBITS(32); */
  16328. while (bits < 32) {
  16329. if (have === 0) { break inf_leave; }
  16330. have--;
  16331. hold += input[next++] << bits;
  16332. bits += 8;
  16333. }
  16334. //===//
  16335. if (state.head) {
  16336. state.head.time = hold;
  16337. }
  16338. if (state.flags & 0x0200) {
  16339. //=== CRC4(state.check, hold)
  16340. hbuf[0] = hold & 0xff;
  16341. hbuf[1] = (hold >>> 8) & 0xff;
  16342. hbuf[2] = (hold >>> 16) & 0xff;
  16343. hbuf[3] = (hold >>> 24) & 0xff;
  16344. state.check = crc32(state.check, hbuf, 4, 0);
  16345. //===
  16346. }
  16347. //=== INITBITS();
  16348. hold = 0;
  16349. bits = 0;
  16350. //===//
  16351. state.mode = OS;
  16352. /* falls through */
  16353. case OS:
  16354. //=== NEEDBITS(16); */
  16355. while (bits < 16) {
  16356. if (have === 0) { break inf_leave; }
  16357. have--;
  16358. hold += input[next++] << bits;
  16359. bits += 8;
  16360. }
  16361. //===//
  16362. if (state.head) {
  16363. state.head.xflags = (hold & 0xff);
  16364. state.head.os = (hold >> 8);
  16365. }
  16366. if (state.flags & 0x0200) {
  16367. //=== CRC2(state.check, hold);
  16368. hbuf[0] = hold & 0xff;
  16369. hbuf[1] = (hold >>> 8) & 0xff;
  16370. state.check = crc32(state.check, hbuf, 2, 0);
  16371. //===//
  16372. }
  16373. //=== INITBITS();
  16374. hold = 0;
  16375. bits = 0;
  16376. //===//
  16377. state.mode = EXLEN;
  16378. /* falls through */
  16379. case EXLEN:
  16380. if (state.flags & 0x0400) {
  16381. //=== NEEDBITS(16); */
  16382. while (bits < 16) {
  16383. if (have === 0) { break inf_leave; }
  16384. have--;
  16385. hold += input[next++] << bits;
  16386. bits += 8;
  16387. }
  16388. //===//
  16389. state.length = hold;
  16390. if (state.head) {
  16391. state.head.extra_len = hold;
  16392. }
  16393. if (state.flags & 0x0200) {
  16394. //=== CRC2(state.check, hold);
  16395. hbuf[0] = hold & 0xff;
  16396. hbuf[1] = (hold >>> 8) & 0xff;
  16397. state.check = crc32(state.check, hbuf, 2, 0);
  16398. //===//
  16399. }
  16400. //=== INITBITS();
  16401. hold = 0;
  16402. bits = 0;
  16403. //===//
  16404. }
  16405. else if (state.head) {
  16406. state.head.extra = null/*Z_NULL*/;
  16407. }
  16408. state.mode = EXTRA;
  16409. /* falls through */
  16410. case EXTRA:
  16411. if (state.flags & 0x0400) {
  16412. copy = state.length;
  16413. if (copy > have) { copy = have; }
  16414. if (copy) {
  16415. if (state.head) {
  16416. len = state.head.extra_len - state.length;
  16417. if (!state.head.extra) {
  16418. // Use untyped array for more conveniend processing later
  16419. state.head.extra = new Array(state.head.extra_len);
  16420. }
  16421. utils.arraySet(
  16422. state.head.extra,
  16423. input,
  16424. next,
  16425. // extra field is limited to 65536 bytes
  16426. // - no need for additional size check
  16427. copy,
  16428. /*len + copy > state.head.extra_max - len ? state.head.extra_max : copy,*/
  16429. len
  16430. );
  16431. //zmemcpy(state.head.extra + len, next,
  16432. // len + copy > state.head.extra_max ?
  16433. // state.head.extra_max - len : copy);
  16434. }
  16435. if (state.flags & 0x0200) {
  16436. state.check = crc32(state.check, input, copy, next);
  16437. }
  16438. have -= copy;
  16439. next += copy;
  16440. state.length -= copy;
  16441. }
  16442. if (state.length) { break inf_leave; }
  16443. }
  16444. state.length = 0;
  16445. state.mode = NAME;
  16446. /* falls through */
  16447. case NAME:
  16448. if (state.flags & 0x0800) {
  16449. if (have === 0) { break inf_leave; }
  16450. copy = 0;
  16451. do {
  16452. // TODO: 2 or 1 bytes?
  16453. len = input[next + copy++];
  16454. /* use constant limit because in js we should not preallocate memory */
  16455. if (state.head && len &&
  16456. (state.length < 65536 /*state.head.name_max*/)) {
  16457. state.head.name += String.fromCharCode(len);
  16458. }
  16459. } while (len && copy < have);
  16460. if (state.flags & 0x0200) {
  16461. state.check = crc32(state.check, input, copy, next);
  16462. }
  16463. have -= copy;
  16464. next += copy;
  16465. if (len) { break inf_leave; }
  16466. }
  16467. else if (state.head) {
  16468. state.head.name = null;
  16469. }
  16470. state.length = 0;
  16471. state.mode = COMMENT;
  16472. /* falls through */
  16473. case COMMENT:
  16474. if (state.flags & 0x1000) {
  16475. if (have === 0) { break inf_leave; }
  16476. copy = 0;
  16477. do {
  16478. len = input[next + copy++];
  16479. /* use constant limit because in js we should not preallocate memory */
  16480. if (state.head && len &&
  16481. (state.length < 65536 /*state.head.comm_max*/)) {
  16482. state.head.comment += String.fromCharCode(len);
  16483. }
  16484. } while (len && copy < have);
  16485. if (state.flags & 0x0200) {
  16486. state.check = crc32(state.check, input, copy, next);
  16487. }
  16488. have -= copy;
  16489. next += copy;
  16490. if (len) { break inf_leave; }
  16491. }
  16492. else if (state.head) {
  16493. state.head.comment = null;
  16494. }
  16495. state.mode = HCRC;
  16496. /* falls through */
  16497. case HCRC:
  16498. if (state.flags & 0x0200) {
  16499. //=== NEEDBITS(16); */
  16500. while (bits < 16) {
  16501. if (have === 0) { break inf_leave; }
  16502. have--;
  16503. hold += input[next++] << bits;
  16504. bits += 8;
  16505. }
  16506. //===//
  16507. if (hold !== (state.check & 0xffff)) {
  16508. strm.msg = 'header crc mismatch';
  16509. state.mode = BAD;
  16510. break;
  16511. }
  16512. //=== INITBITS();
  16513. hold = 0;
  16514. bits = 0;
  16515. //===//
  16516. }
  16517. if (state.head) {
  16518. state.head.hcrc = ((state.flags >> 9) & 1);
  16519. state.head.done = true;
  16520. }
  16521. strm.adler = state.check = 0 /*crc32(0L, Z_NULL, 0)*/;
  16522. state.mode = TYPE;
  16523. break;
  16524. case DICTID:
  16525. //=== NEEDBITS(32); */
  16526. while (bits < 32) {
  16527. if (have === 0) { break inf_leave; }
  16528. have--;
  16529. hold += input[next++] << bits;
  16530. bits += 8;
  16531. }
  16532. //===//
  16533. strm.adler = state.check = ZSWAP32(hold);
  16534. //=== INITBITS();
  16535. hold = 0;
  16536. bits = 0;
  16537. //===//
  16538. state.mode = DICT;
  16539. /* falls through */
  16540. case DICT:
  16541. if (state.havedict === 0) {
  16542. //--- RESTORE() ---
  16543. strm.next_out = put;
  16544. strm.avail_out = left;
  16545. strm.next_in = next;
  16546. strm.avail_in = have;
  16547. state.hold = hold;
  16548. state.bits = bits;
  16549. //---
  16550. return Z_NEED_DICT;
  16551. }
  16552. strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
  16553. state.mode = TYPE;
  16554. /* falls through */
  16555. case TYPE:
  16556. if (flush === Z_BLOCK || flush === Z_TREES) { break inf_leave; }
  16557. /* falls through */
  16558. case TYPEDO:
  16559. if (state.last) {
  16560. //--- BYTEBITS() ---//
  16561. hold >>>= bits & 7;
  16562. bits -= bits & 7;
  16563. //---//
  16564. state.mode = CHECK;
  16565. break;
  16566. }
  16567. //=== NEEDBITS(3); */
  16568. while (bits < 3) {
  16569. if (have === 0) { break inf_leave; }
  16570. have--;
  16571. hold += input[next++] << bits;
  16572. bits += 8;
  16573. }
  16574. //===//
  16575. state.last = (hold & 0x01)/*BITS(1)*/;
  16576. //--- DROPBITS(1) ---//
  16577. hold >>>= 1;
  16578. bits -= 1;
  16579. //---//
  16580. switch ((hold & 0x03)/*BITS(2)*/) {
  16581. case 0: /* stored block */
  16582. //Tracev((stderr, "inflate: stored block%s\n",
  16583. // state.last ? " (last)" : ""));
  16584. state.mode = STORED;
  16585. break;
  16586. case 1: /* fixed block */
  16587. fixedtables(state);
  16588. //Tracev((stderr, "inflate: fixed codes block%s\n",
  16589. // state.last ? " (last)" : ""));
  16590. state.mode = LEN_; /* decode codes */
  16591. if (flush === Z_TREES) {
  16592. //--- DROPBITS(2) ---//
  16593. hold >>>= 2;
  16594. bits -= 2;
  16595. //---//
  16596. break inf_leave;
  16597. }
  16598. break;
  16599. case 2: /* dynamic block */
  16600. //Tracev((stderr, "inflate: dynamic codes block%s\n",
  16601. // state.last ? " (last)" : ""));
  16602. state.mode = TABLE;
  16603. break;
  16604. case 3:
  16605. strm.msg = 'invalid block type';
  16606. state.mode = BAD;
  16607. }
  16608. //--- DROPBITS(2) ---//
  16609. hold >>>= 2;
  16610. bits -= 2;
  16611. //---//
  16612. break;
  16613. case STORED:
  16614. //--- BYTEBITS() ---// /* go to byte boundary */
  16615. hold >>>= bits & 7;
  16616. bits -= bits & 7;
  16617. //---//
  16618. //=== NEEDBITS(32); */
  16619. while (bits < 32) {
  16620. if (have === 0) { break inf_leave; }
  16621. have--;
  16622. hold += input[next++] << bits;
  16623. bits += 8;
  16624. }
  16625. //===//
  16626. if ((hold & 0xffff) !== ((hold >>> 16) ^ 0xffff)) {
  16627. strm.msg = 'invalid stored block lengths';
  16628. state.mode = BAD;
  16629. break;
  16630. }
  16631. state.length = hold & 0xffff;
  16632. //Tracev((stderr, "inflate: stored length %u\n",
  16633. // state.length));
  16634. //=== INITBITS();
  16635. hold = 0;
  16636. bits = 0;
  16637. //===//
  16638. state.mode = COPY_;
  16639. if (flush === Z_TREES) { break inf_leave; }
  16640. /* falls through */
  16641. case COPY_:
  16642. state.mode = COPY;
  16643. /* falls through */
  16644. case COPY:
  16645. copy = state.length;
  16646. if (copy) {
  16647. if (copy > have) { copy = have; }
  16648. if (copy > left) { copy = left; }
  16649. if (copy === 0) { break inf_leave; }
  16650. //--- zmemcpy(put, next, copy); ---
  16651. utils.arraySet(output, input, next, copy, put);
  16652. //---//
  16653. have -= copy;
  16654. next += copy;
  16655. left -= copy;
  16656. put += copy;
  16657. state.length -= copy;
  16658. break;
  16659. }
  16660. //Tracev((stderr, "inflate: stored end\n"));
  16661. state.mode = TYPE;
  16662. break;
  16663. case TABLE:
  16664. //=== NEEDBITS(14); */
  16665. while (bits < 14) {
  16666. if (have === 0) { break inf_leave; }
  16667. have--;
  16668. hold += input[next++] << bits;
  16669. bits += 8;
  16670. }
  16671. //===//
  16672. state.nlen = (hold & 0x1f)/*BITS(5)*/ + 257;
  16673. //--- DROPBITS(5) ---//
  16674. hold >>>= 5;
  16675. bits -= 5;
  16676. //---//
  16677. state.ndist = (hold & 0x1f)/*BITS(5)*/ + 1;
  16678. //--- DROPBITS(5) ---//
  16679. hold >>>= 5;
  16680. bits -= 5;
  16681. //---//
  16682. state.ncode = (hold & 0x0f)/*BITS(4)*/ + 4;
  16683. //--- DROPBITS(4) ---//
  16684. hold >>>= 4;
  16685. bits -= 4;
  16686. //---//
  16687. //#ifndef PKZIP_BUG_WORKAROUND
  16688. if (state.nlen > 286 || state.ndist > 30) {
  16689. strm.msg = 'too many length or distance symbols';
  16690. state.mode = BAD;
  16691. break;
  16692. }
  16693. //#endif
  16694. //Tracev((stderr, "inflate: table sizes ok\n"));
  16695. state.have = 0;
  16696. state.mode = LENLENS;
  16697. /* falls through */
  16698. case LENLENS:
  16699. while (state.have < state.ncode) {
  16700. //=== NEEDBITS(3);
  16701. while (bits < 3) {
  16702. if (have === 0) { break inf_leave; }
  16703. have--;
  16704. hold += input[next++] << bits;
  16705. bits += 8;
  16706. }
  16707. //===//
  16708. state.lens[order[state.have++]] = (hold & 0x07);//BITS(3);
  16709. //--- DROPBITS(3) ---//
  16710. hold >>>= 3;
  16711. bits -= 3;
  16712. //---//
  16713. }
  16714. while (state.have < 19) {
  16715. state.lens[order[state.have++]] = 0;
  16716. }
  16717. // We have separate tables & no pointers. 2 commented lines below not needed.
  16718. //state.next = state.codes;
  16719. //state.lencode = state.next;
  16720. // Switch to use dynamic table
  16721. state.lencode = state.lendyn;
  16722. state.lenbits = 7;
  16723. opts = {bits: state.lenbits};
  16724. ret = inflate_table(CODES, state.lens, 0, 19, state.lencode, 0, state.work, opts);
  16725. state.lenbits = opts.bits;
  16726. if (ret) {
  16727. strm.msg = 'invalid code lengths set';
  16728. state.mode = BAD;
  16729. break;
  16730. }
  16731. //Tracev((stderr, "inflate: code lengths ok\n"));
  16732. state.have = 0;
  16733. state.mode = CODELENS;
  16734. /* falls through */
  16735. case CODELENS:
  16736. while (state.have < state.nlen + state.ndist) {
  16737. for (;;) {
  16738. here = state.lencode[hold & ((1 << state.lenbits) - 1)];/*BITS(state.lenbits)*/
  16739. here_bits = here >>> 24;
  16740. here_op = (here >>> 16) & 0xff;
  16741. here_val = here & 0xffff;
  16742. if ((here_bits) <= bits) { break; }
  16743. //--- PULLBYTE() ---//
  16744. if (have === 0) { break inf_leave; }
  16745. have--;
  16746. hold += input[next++] << bits;
  16747. bits += 8;
  16748. //---//
  16749. }
  16750. if (here_val < 16) {
  16751. //--- DROPBITS(here.bits) ---//
  16752. hold >>>= here_bits;
  16753. bits -= here_bits;
  16754. //---//
  16755. state.lens[state.have++] = here_val;
  16756. }
  16757. else {
  16758. if (here_val === 16) {
  16759. //=== NEEDBITS(here.bits + 2);
  16760. n = here_bits + 2;
  16761. while (bits < n) {
  16762. if (have === 0) { break inf_leave; }
  16763. have--;
  16764. hold += input[next++] << bits;
  16765. bits += 8;
  16766. }
  16767. //===//
  16768. //--- DROPBITS(here.bits) ---//
  16769. hold >>>= here_bits;
  16770. bits -= here_bits;
  16771. //---//
  16772. if (state.have === 0) {
  16773. strm.msg = 'invalid bit length repeat';
  16774. state.mode = BAD;
  16775. break;
  16776. }
  16777. len = state.lens[state.have - 1];
  16778. copy = 3 + (hold & 0x03);//BITS(2);
  16779. //--- DROPBITS(2) ---//
  16780. hold >>>= 2;
  16781. bits -= 2;
  16782. //---//
  16783. }
  16784. else if (here_val === 17) {
  16785. //=== NEEDBITS(here.bits + 3);
  16786. n = here_bits + 3;
  16787. while (bits < n) {
  16788. if (have === 0) { break inf_leave; }
  16789. have--;
  16790. hold += input[next++] << bits;
  16791. bits += 8;
  16792. }
  16793. //===//
  16794. //--- DROPBITS(here.bits) ---//
  16795. hold >>>= here_bits;
  16796. bits -= here_bits;
  16797. //---//
  16798. len = 0;
  16799. copy = 3 + (hold & 0x07);//BITS(3);
  16800. //--- DROPBITS(3) ---//
  16801. hold >>>= 3;
  16802. bits -= 3;
  16803. //---//
  16804. }
  16805. else {
  16806. //=== NEEDBITS(here.bits + 7);
  16807. n = here_bits + 7;
  16808. while (bits < n) {
  16809. if (have === 0) { break inf_leave; }
  16810. have--;
  16811. hold += input[next++] << bits;
  16812. bits += 8;
  16813. }
  16814. //===//
  16815. //--- DROPBITS(here.bits) ---//
  16816. hold >>>= here_bits;
  16817. bits -= here_bits;
  16818. //---//
  16819. len = 0;
  16820. copy = 11 + (hold & 0x7f);//BITS(7);
  16821. //--- DROPBITS(7) ---//
  16822. hold >>>= 7;
  16823. bits -= 7;
  16824. //---//
  16825. }
  16826. if (state.have + copy > state.nlen + state.ndist) {
  16827. strm.msg = 'invalid bit length repeat';
  16828. state.mode = BAD;
  16829. break;
  16830. }
  16831. while (copy--) {
  16832. state.lens[state.have++] = len;
  16833. }
  16834. }
  16835. }
  16836. /* handle error breaks in while */
  16837. if (state.mode === BAD) { break; }
  16838. /* check for end-of-block code (better have one) */
  16839. if (state.lens[256] === 0) {
  16840. strm.msg = 'invalid code -- missing end-of-block';
  16841. state.mode = BAD;
  16842. break;
  16843. }
  16844. /* build code tables -- note: do not change the lenbits or distbits
  16845. values here (9 and 6) without reading the comments in inftrees.h
  16846. concerning the ENOUGH constants, which depend on those values */
  16847. state.lenbits = 9;
  16848. opts = {bits: state.lenbits};
  16849. ret = inflate_table(LENS, state.lens, 0, state.nlen, state.lencode, 0, state.work, opts);
  16850. // We have separate tables & no pointers. 2 commented lines below not needed.
  16851. // state.next_index = opts.table_index;
  16852. state.lenbits = opts.bits;
  16853. // state.lencode = state.next;
  16854. if (ret) {
  16855. strm.msg = 'invalid literal/lengths set';
  16856. state.mode = BAD;
  16857. break;
  16858. }
  16859. state.distbits = 6;
  16860. //state.distcode.copy(state.codes);
  16861. // Switch to use dynamic table
  16862. state.distcode = state.distdyn;
  16863. opts = {bits: state.distbits};
  16864. ret = inflate_table(DISTS, state.lens, state.nlen, state.ndist, state.distcode, 0, state.work, opts);
  16865. // We have separate tables & no pointers. 2 commented lines below not needed.
  16866. // state.next_index = opts.table_index;
  16867. state.distbits = opts.bits;
  16868. // state.distcode = state.next;
  16869. if (ret) {
  16870. strm.msg = 'invalid distances set';
  16871. state.mode = BAD;
  16872. break;
  16873. }
  16874. //Tracev((stderr, 'inflate: codes ok\n'));
  16875. state.mode = LEN_;
  16876. if (flush === Z_TREES) { break inf_leave; }
  16877. /* falls through */
  16878. case LEN_:
  16879. state.mode = LEN;
  16880. /* falls through */
  16881. case LEN:
  16882. if (have >= 6 && left >= 258) {
  16883. //--- RESTORE() ---
  16884. strm.next_out = put;
  16885. strm.avail_out = left;
  16886. strm.next_in = next;
  16887. strm.avail_in = have;
  16888. state.hold = hold;
  16889. state.bits = bits;
  16890. //---
  16891. inflate_fast(strm, _out);
  16892. //--- LOAD() ---
  16893. put = strm.next_out;
  16894. output = strm.output;
  16895. left = strm.avail_out;
  16896. next = strm.next_in;
  16897. input = strm.input;
  16898. have = strm.avail_in;
  16899. hold = state.hold;
  16900. bits = state.bits;
  16901. //---
  16902. if (state.mode === TYPE) {
  16903. state.back = -1;
  16904. }
  16905. break;
  16906. }
  16907. state.back = 0;
  16908. for (;;) {
  16909. here = state.lencode[hold & ((1 << state.lenbits) -1)]; /*BITS(state.lenbits)*/
  16910. here_bits = here >>> 24;
  16911. here_op = (here >>> 16) & 0xff;
  16912. here_val = here & 0xffff;
  16913. if (here_bits <= bits) { break; }
  16914. //--- PULLBYTE() ---//
  16915. if (have === 0) { break inf_leave; }
  16916. have--;
  16917. hold += input[next++] << bits;
  16918. bits += 8;
  16919. //---//
  16920. }
  16921. if (here_op && (here_op & 0xf0) === 0) {
  16922. last_bits = here_bits;
  16923. last_op = here_op;
  16924. last_val = here_val;
  16925. for (;;) {
  16926. here = state.lencode[last_val +
  16927. ((hold & ((1 << (last_bits + last_op)) -1))/*BITS(last.bits + last.op)*/ >> last_bits)];
  16928. here_bits = here >>> 24;
  16929. here_op = (here >>> 16) & 0xff;
  16930. here_val = here & 0xffff;
  16931. if ((last_bits + here_bits) <= bits) { break; }
  16932. //--- PULLBYTE() ---//
  16933. if (have === 0) { break inf_leave; }
  16934. have--;
  16935. hold += input[next++] << bits;
  16936. bits += 8;
  16937. //---//
  16938. }
  16939. //--- DROPBITS(last.bits) ---//
  16940. hold >>>= last_bits;
  16941. bits -= last_bits;
  16942. //---//
  16943. state.back += last_bits;
  16944. }
  16945. //--- DROPBITS(here.bits) ---//
  16946. hold >>>= here_bits;
  16947. bits -= here_bits;
  16948. //---//
  16949. state.back += here_bits;
  16950. state.length = here_val;
  16951. if (here_op === 0) {
  16952. //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
  16953. // "inflate: literal '%c'\n" :
  16954. // "inflate: literal 0x%02x\n", here.val));
  16955. state.mode = LIT;
  16956. break;
  16957. }
  16958. if (here_op & 32) {
  16959. //Tracevv((stderr, "inflate: end of block\n"));
  16960. state.back = -1;
  16961. state.mode = TYPE;
  16962. break;
  16963. }
  16964. if (here_op & 64) {
  16965. strm.msg = 'invalid literal/length code';
  16966. state.mode = BAD;
  16967. break;
  16968. }
  16969. state.extra = here_op & 15;
  16970. state.mode = LENEXT;
  16971. /* falls through */
  16972. case LENEXT:
  16973. if (state.extra) {
  16974. //=== NEEDBITS(state.extra);
  16975. n = state.extra;
  16976. while (bits < n) {
  16977. if (have === 0) { break inf_leave; }
  16978. have--;
  16979. hold += input[next++] << bits;
  16980. bits += 8;
  16981. }
  16982. //===//
  16983. state.length += hold & ((1 << state.extra) -1)/*BITS(state.extra)*/;
  16984. //--- DROPBITS(state.extra) ---//
  16985. hold >>>= state.extra;
  16986. bits -= state.extra;
  16987. //---//
  16988. state.back += state.extra;
  16989. }
  16990. //Tracevv((stderr, "inflate: length %u\n", state.length));
  16991. state.was = state.length;
  16992. state.mode = DIST;
  16993. /* falls through */
  16994. case DIST:
  16995. for (;;) {
  16996. here = state.distcode[hold & ((1 << state.distbits) -1)];/*BITS(state.distbits)*/
  16997. here_bits = here >>> 24;
  16998. here_op = (here >>> 16) & 0xff;
  16999. here_val = here & 0xffff;
  17000. if ((here_bits) <= bits) { break; }
  17001. //--- PULLBYTE() ---//
  17002. if (have === 0) { break inf_leave; }
  17003. have--;
  17004. hold += input[next++] << bits;
  17005. bits += 8;
  17006. //---//
  17007. }
  17008. if ((here_op & 0xf0) === 0) {
  17009. last_bits = here_bits;
  17010. last_op = here_op;
  17011. last_val = here_val;
  17012. for (;;) {
  17013. here = state.distcode[last_val +
  17014. ((hold & ((1 << (last_bits + last_op)) -1))/*BITS(last.bits + last.op)*/ >> last_bits)];
  17015. here_bits = here >>> 24;
  17016. here_op = (here >>> 16) & 0xff;
  17017. here_val = here & 0xffff;
  17018. if ((last_bits + here_bits) <= bits) { break; }
  17019. //--- PULLBYTE() ---//
  17020. if (have === 0) { break inf_leave; }
  17021. have--;
  17022. hold += input[next++] << bits;
  17023. bits += 8;
  17024. //---//
  17025. }
  17026. //--- DROPBITS(last.bits) ---//
  17027. hold >>>= last_bits;
  17028. bits -= last_bits;
  17029. //---//
  17030. state.back += last_bits;
  17031. }
  17032. //--- DROPBITS(here.bits) ---//
  17033. hold >>>= here_bits;
  17034. bits -= here_bits;
  17035. //---//
  17036. state.back += here_bits;
  17037. if (here_op & 64) {
  17038. strm.msg = 'invalid distance code';
  17039. state.mode = BAD;
  17040. break;
  17041. }
  17042. state.offset = here_val;
  17043. state.extra = (here_op) & 15;
  17044. state.mode = DISTEXT;
  17045. /* falls through */
  17046. case DISTEXT:
  17047. if (state.extra) {
  17048. //=== NEEDBITS(state.extra);
  17049. n = state.extra;
  17050. while (bits < n) {
  17051. if (have === 0) { break inf_leave; }
  17052. have--;
  17053. hold += input[next++] << bits;
  17054. bits += 8;
  17055. }
  17056. //===//
  17057. state.offset += hold & ((1 << state.extra) -1)/*BITS(state.extra)*/;
  17058. //--- DROPBITS(state.extra) ---//
  17059. hold >>>= state.extra;
  17060. bits -= state.extra;
  17061. //---//
  17062. state.back += state.extra;
  17063. }
  17064. //#ifdef INFLATE_STRICT
  17065. if (state.offset > state.dmax) {
  17066. strm.msg = 'invalid distance too far back';
  17067. state.mode = BAD;
  17068. break;
  17069. }
  17070. //#endif
  17071. //Tracevv((stderr, "inflate: distance %u\n", state.offset));
  17072. state.mode = MATCH;
  17073. /* falls through */
  17074. case MATCH:
  17075. if (left === 0) { break inf_leave; }
  17076. copy = _out - left;
  17077. if (state.offset > copy) { /* copy from window */
  17078. copy = state.offset - copy;
  17079. if (copy > state.whave) {
  17080. if (state.sane) {
  17081. strm.msg = 'invalid distance too far back';
  17082. state.mode = BAD;
  17083. break;
  17084. }
  17085. // (!) This block is disabled in zlib defailts,
  17086. // don't enable it for binary compatibility
  17087. //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
  17088. // Trace((stderr, "inflate.c too far\n"));
  17089. // copy -= state.whave;
  17090. // if (copy > state.length) { copy = state.length; }
  17091. // if (copy > left) { copy = left; }
  17092. // left -= copy;
  17093. // state.length -= copy;
  17094. // do {
  17095. // output[put++] = 0;
  17096. // } while (--copy);
  17097. // if (state.length === 0) { state.mode = LEN; }
  17098. // break;
  17099. //#endif
  17100. }
  17101. if (copy > state.wnext) {
  17102. copy -= state.wnext;
  17103. from = state.wsize - copy;
  17104. }
  17105. else {
  17106. from = state.wnext - copy;
  17107. }
  17108. if (copy > state.length) { copy = state.length; }
  17109. from_source = state.window;
  17110. }
  17111. else { /* copy from output */
  17112. from_source = output;
  17113. from = put - state.offset;
  17114. copy = state.length;
  17115. }
  17116. if (copy > left) { copy = left; }
  17117. left -= copy;
  17118. state.length -= copy;
  17119. do {
  17120. output[put++] = from_source[from++];
  17121. } while (--copy);
  17122. if (state.length === 0) { state.mode = LEN; }
  17123. break;
  17124. case LIT:
  17125. if (left === 0) { break inf_leave; }
  17126. output[put++] = state.length;
  17127. left--;
  17128. state.mode = LEN;
  17129. break;
  17130. case CHECK:
  17131. if (state.wrap) {
  17132. //=== NEEDBITS(32);
  17133. while (bits < 32) {
  17134. if (have === 0) { break inf_leave; }
  17135. have--;
  17136. // Use '|' insdead of '+' to make sure that result is signed
  17137. hold |= input[next++] << bits;
  17138. bits += 8;
  17139. }
  17140. //===//
  17141. _out -= left;
  17142. strm.total_out += _out;
  17143. state.total += _out;
  17144. if (_out) {
  17145. strm.adler = state.check =
  17146. /*UPDATE(state.check, put - _out, _out);*/
  17147. (state.flags ? crc32(state.check, output, _out, put - _out) : adler32(state.check, output, _out, put - _out));
  17148. }
  17149. _out = left;
  17150. // NB: crc32 stored as signed 32-bit int, ZSWAP32 returns signed too
  17151. if ((state.flags ? hold : ZSWAP32(hold)) !== state.check) {
  17152. strm.msg = 'incorrect data check';
  17153. state.mode = BAD;
  17154. break;
  17155. }
  17156. //=== INITBITS();
  17157. hold = 0;
  17158. bits = 0;
  17159. //===//
  17160. //Tracev((stderr, "inflate: check matches trailer\n"));
  17161. }
  17162. state.mode = LENGTH;
  17163. /* falls through */
  17164. case LENGTH:
  17165. if (state.wrap && state.flags) {
  17166. //=== NEEDBITS(32);
  17167. while (bits < 32) {
  17168. if (have === 0) { break inf_leave; }
  17169. have--;
  17170. hold += input[next++] << bits;
  17171. bits += 8;
  17172. }
  17173. //===//
  17174. if (hold !== (state.total & 0xffffffff)) {
  17175. strm.msg = 'incorrect length check';
  17176. state.mode = BAD;
  17177. break;
  17178. }
  17179. //=== INITBITS();
  17180. hold = 0;
  17181. bits = 0;
  17182. //===//
  17183. //Tracev((stderr, "inflate: length matches trailer\n"));
  17184. }
  17185. state.mode = DONE;
  17186. /* falls through */
  17187. case DONE:
  17188. ret = Z_STREAM_END;
  17189. break inf_leave;
  17190. case BAD:
  17191. ret = Z_DATA_ERROR;
  17192. break inf_leave;
  17193. case MEM:
  17194. return Z_MEM_ERROR;
  17195. case SYNC:
  17196. /* falls through */
  17197. default:
  17198. return Z_STREAM_ERROR;
  17199. }
  17200. }
  17201. // inf_leave <- here is real place for "goto inf_leave", emulated via "break inf_leave"
  17202. /*
  17203. Return from inflate(), updating the total counts and the check value.
  17204. If there was no progress during the inflate() call, return a buffer
  17205. error. Call updatewindow() to create and/or update the window state.
  17206. Note: a memory error from inflate() is non-recoverable.
  17207. */
  17208. //--- RESTORE() ---
  17209. strm.next_out = put;
  17210. strm.avail_out = left;
  17211. strm.next_in = next;
  17212. strm.avail_in = have;
  17213. state.hold = hold;
  17214. state.bits = bits;
  17215. //---
  17216. if (state.wsize || (_out !== strm.avail_out && state.mode < BAD &&
  17217. (state.mode < CHECK || flush !== Z_FINISH))) {
  17218. if (updatewindow(strm, strm.output, strm.next_out, _out - strm.avail_out)) {
  17219. state.mode = MEM;
  17220. return Z_MEM_ERROR;
  17221. }
  17222. }
  17223. _in -= strm.avail_in;
  17224. _out -= strm.avail_out;
  17225. strm.total_in += _in;
  17226. strm.total_out += _out;
  17227. state.total += _out;
  17228. if (state.wrap && _out) {
  17229. strm.adler = state.check = /*UPDATE(state.check, strm.next_out - _out, _out);*/
  17230. (state.flags ? crc32(state.check, output, _out, strm.next_out - _out) : adler32(state.check, output, _out, strm.next_out - _out));
  17231. }
  17232. strm.data_type = state.bits + (state.last ? 64 : 0) +
  17233. (state.mode === TYPE ? 128 : 0) +
  17234. (state.mode === LEN_ || state.mode === COPY_ ? 256 : 0);
  17235. if (((_in === 0 && _out === 0) || flush === Z_FINISH) && ret === Z_OK) {
  17236. ret = Z_BUF_ERROR;
  17237. }
  17238. return ret;
  17239. }
  17240. function inflateEnd(strm) {
  17241. if (!strm || !strm.state /*|| strm->zfree == (free_func)0*/) {
  17242. return Z_STREAM_ERROR;
  17243. }
  17244. var state = strm.state;
  17245. if (state.window) {
  17246. state.window = null;
  17247. }
  17248. strm.state = null;
  17249. return Z_OK;
  17250. }
  17251. function inflateGetHeader(strm, head) {
  17252. var state;
  17253. /* check state */
  17254. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  17255. state = strm.state;
  17256. if ((state.wrap & 2) === 0) { return Z_STREAM_ERROR; }
  17257. /* save header structure */
  17258. state.head = head;
  17259. head.done = false;
  17260. return Z_OK;
  17261. }
  17262. exports.inflateReset = inflateReset;
  17263. exports.inflateReset2 = inflateReset2;
  17264. exports.inflateResetKeep = inflateResetKeep;
  17265. exports.inflateInit = inflateInit;
  17266. exports.inflateInit2 = inflateInit2;
  17267. exports.inflate = inflate;
  17268. exports.inflateEnd = inflateEnd;
  17269. exports.inflateGetHeader = inflateGetHeader;
  17270. exports.inflateInfo = 'pako inflate (from Nodeca project)';
  17271. /* Not implemented
  17272. exports.inflateCopy = inflateCopy;
  17273. exports.inflateGetDictionary = inflateGetDictionary;
  17274. exports.inflateMark = inflateMark;
  17275. exports.inflatePrime = inflatePrime;
  17276. exports.inflateSetDictionary = inflateSetDictionary;
  17277. exports.inflateSync = inflateSync;
  17278. exports.inflateSyncPoint = inflateSyncPoint;
  17279. exports.inflateUndermine = inflateUndermine;
  17280. */
  17281. },{"../utils/common":52,"./adler32":54,"./crc32":56,"./inffast":59,"./inftrees":61}],61:[function(require,module,exports){
  17282. 'use strict';
  17283. var utils = require('../utils/common');
  17284. var MAXBITS = 15;
  17285. var ENOUGH_LENS = 852;
  17286. var ENOUGH_DISTS = 592;
  17287. //var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
  17288. var CODES = 0;
  17289. var LENS = 1;
  17290. var DISTS = 2;
  17291. var lbase = [ /* Length codes 257..285 base */
  17292. 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
  17293. 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0
  17294. ];
  17295. var lext = [ /* Length codes 257..285 extra */
  17296. 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,
  17297. 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 72, 78
  17298. ];
  17299. var dbase = [ /* Distance codes 0..29 base */
  17300. 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
  17301. 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
  17302. 8193, 12289, 16385, 24577, 0, 0
  17303. ];
  17304. var dext = [ /* Distance codes 0..29 extra */
  17305. 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,
  17306. 23, 23, 24, 24, 25, 25, 26, 26, 27, 27,
  17307. 28, 28, 29, 29, 64, 64
  17308. ];
  17309. module.exports = function inflate_table(type, lens, lens_index, codes, table, table_index, work, opts)
  17310. {
  17311. var bits = opts.bits;
  17312. //here = opts.here; /* table entry for duplication */
  17313. var len = 0; /* a code's length in bits */
  17314. var sym = 0; /* index of code symbols */
  17315. var min = 0, max = 0; /* minimum and maximum code lengths */
  17316. var root = 0; /* number of index bits for root table */
  17317. var curr = 0; /* number of index bits for current table */
  17318. var drop = 0; /* code bits to drop for sub-table */
  17319. var left = 0; /* number of prefix codes available */
  17320. var used = 0; /* code entries in table used */
  17321. var huff = 0; /* Huffman code */
  17322. var incr; /* for incrementing code, index */
  17323. var fill; /* index for replicating entries */
  17324. var low; /* low bits for current root entry */
  17325. var mask; /* mask for low root bits */
  17326. var next; /* next available space in table */
  17327. var base = null; /* base value table to use */
  17328. var base_index = 0;
  17329. // var shoextra; /* extra bits table to use */
  17330. var end; /* use base and extra for symbol > end */
  17331. var count = new utils.Buf16(MAXBITS+1); //[MAXBITS+1]; /* number of codes of each length */
  17332. var offs = new utils.Buf16(MAXBITS+1); //[MAXBITS+1]; /* offsets in table for each length */
  17333. var extra = null;
  17334. var extra_index = 0;
  17335. var here_bits, here_op, here_val;
  17336. /*
  17337. Process a set of code lengths to create a canonical Huffman code. The
  17338. code lengths are lens[0..codes-1]. Each length corresponds to the
  17339. symbols 0..codes-1. The Huffman code is generated by first sorting the
  17340. symbols by length from short to long, and retaining the symbol order
  17341. for codes with equal lengths. Then the code starts with all zero bits
  17342. for the first code of the shortest length, and the codes are integer
  17343. increments for the same length, and zeros are appended as the length
  17344. increases. For the deflate format, these bits are stored backwards
  17345. from their more natural integer increment ordering, and so when the
  17346. decoding tables are built in the large loop below, the integer codes
  17347. are incremented backwards.
  17348. This routine assumes, but does not check, that all of the entries in
  17349. lens[] are in the range 0..MAXBITS. The caller must assure this.
  17350. 1..MAXBITS is interpreted as that code length. zero means that that
  17351. symbol does not occur in this code.
  17352. The codes are sorted by computing a count of codes for each length,
  17353. creating from that a table of starting indices for each length in the
  17354. sorted table, and then entering the symbols in order in the sorted
  17355. table. The sorted table is work[], with that space being provided by
  17356. the caller.
  17357. The length counts are used for other purposes as well, i.e. finding
  17358. the minimum and maximum length codes, determining if there are any
  17359. codes at all, checking for a valid set of lengths, and looking ahead
  17360. at length counts to determine sub-table sizes when building the
  17361. decoding tables.
  17362. */
  17363. /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */
  17364. for (len = 0; len <= MAXBITS; len++) {
  17365. count[len] = 0;
  17366. }
  17367. for (sym = 0; sym < codes; sym++) {
  17368. count[lens[lens_index + sym]]++;
  17369. }
  17370. /* bound code lengths, force root to be within code lengths */
  17371. root = bits;
  17372. for (max = MAXBITS; max >= 1; max--) {
  17373. if (count[max] !== 0) { break; }
  17374. }
  17375. if (root > max) {
  17376. root = max;
  17377. }
  17378. if (max === 0) { /* no symbols to code at all */
  17379. //table.op[opts.table_index] = 64; //here.op = (var char)64; /* invalid code marker */
  17380. //table.bits[opts.table_index] = 1; //here.bits = (var char)1;
  17381. //table.val[opts.table_index++] = 0; //here.val = (var short)0;
  17382. table[table_index++] = (1 << 24) | (64 << 16) | 0;
  17383. //table.op[opts.table_index] = 64;
  17384. //table.bits[opts.table_index] = 1;
  17385. //table.val[opts.table_index++] = 0;
  17386. table[table_index++] = (1 << 24) | (64 << 16) | 0;
  17387. opts.bits = 1;
  17388. return 0; /* no symbols, but wait for decoding to report error */
  17389. }
  17390. for (min = 1; min < max; min++) {
  17391. if (count[min] !== 0) { break; }
  17392. }
  17393. if (root < min) {
  17394. root = min;
  17395. }
  17396. /* check for an over-subscribed or incomplete set of lengths */
  17397. left = 1;
  17398. for (len = 1; len <= MAXBITS; len++) {
  17399. left <<= 1;
  17400. left -= count[len];
  17401. if (left < 0) {
  17402. return -1;
  17403. } /* over-subscribed */
  17404. }
  17405. if (left > 0 && (type === CODES || max !== 1)) {
  17406. return -1; /* incomplete set */
  17407. }
  17408. /* generate offsets into symbol table for each length for sorting */
  17409. offs[1] = 0;
  17410. for (len = 1; len < MAXBITS; len++) {
  17411. offs[len + 1] = offs[len] + count[len];
  17412. }
  17413. /* sort symbols by length, by symbol order within each length */
  17414. for (sym = 0; sym < codes; sym++) {
  17415. if (lens[lens_index + sym] !== 0) {
  17416. work[offs[lens[lens_index + sym]]++] = sym;
  17417. }
  17418. }
  17419. /*
  17420. Create and fill in decoding tables. In this loop, the table being
  17421. filled is at next and has curr index bits. The code being used is huff
  17422. with length len. That code is converted to an index by dropping drop
  17423. bits off of the bottom. For codes where len is less than drop + curr,
  17424. those top drop + curr - len bits are incremented through all values to
  17425. fill the table with replicated entries.
  17426. root is the number of index bits for the root table. When len exceeds
  17427. root, sub-tables are created pointed to by the root entry with an index
  17428. of the low root bits of huff. This is saved in low to check for when a
  17429. new sub-table should be started. drop is zero when the root table is
  17430. being filled, and drop is root when sub-tables are being filled.
  17431. When a new sub-table is needed, it is necessary to look ahead in the
  17432. code lengths to determine what size sub-table is needed. The length
  17433. counts are used for this, and so count[] is decremented as codes are
  17434. entered in the tables.
  17435. used keeps track of how many table entries have been allocated from the
  17436. provided *table space. It is checked for LENS and DIST tables against
  17437. the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in
  17438. the initial root table size constants. See the comments in inftrees.h
  17439. for more information.
  17440. sym increments through all symbols, and the loop terminates when
  17441. all codes of length max, i.e. all codes, have been processed. This
  17442. routine permits incomplete codes, so another loop after this one fills
  17443. in the rest of the decoding tables with invalid code markers.
  17444. */
  17445. /* set up for code type */
  17446. // poor man optimization - use if-else instead of switch,
  17447. // to avoid deopts in old v8
  17448. if (type === CODES) {
  17449. base = extra = work; /* dummy value--not used */
  17450. end = 19;
  17451. } else if (type === LENS) {
  17452. base = lbase;
  17453. base_index -= 257;
  17454. extra = lext;
  17455. extra_index -= 257;
  17456. end = 256;
  17457. } else { /* DISTS */
  17458. base = dbase;
  17459. extra = dext;
  17460. end = -1;
  17461. }
  17462. /* initialize opts for loop */
  17463. huff = 0; /* starting code */
  17464. sym = 0; /* starting code symbol */
  17465. len = min; /* starting code length */
  17466. next = table_index; /* current table to fill in */
  17467. curr = root; /* current table index bits */
  17468. drop = 0; /* current bits to drop from code for index */
  17469. low = -1; /* trigger new sub-table when len > root */
  17470. used = 1 << root; /* use root table entries */
  17471. mask = used - 1; /* mask for comparing low */
  17472. /* check available table space */
  17473. if ((type === LENS && used > ENOUGH_LENS) ||
  17474. (type === DISTS && used > ENOUGH_DISTS)) {
  17475. return 1;
  17476. }
  17477. var i=0;
  17478. /* process all codes and make table entries */
  17479. for (;;) {
  17480. i++;
  17481. /* create table entry */
  17482. here_bits = len - drop;
  17483. if (work[sym] < end) {
  17484. here_op = 0;
  17485. here_val = work[sym];
  17486. }
  17487. else if (work[sym] > end) {
  17488. here_op = extra[extra_index + work[sym]];
  17489. here_val = base[base_index + work[sym]];
  17490. }
  17491. else {
  17492. here_op = 32 + 64; /* end of block */
  17493. here_val = 0;
  17494. }
  17495. /* replicate for those indices with low len bits equal to huff */
  17496. incr = 1 << (len - drop);
  17497. fill = 1 << curr;
  17498. min = fill; /* save offset to next table */
  17499. do {
  17500. fill -= incr;
  17501. table[next + (huff >> drop) + fill] = (here_bits << 24) | (here_op << 16) | here_val |0;
  17502. } while (fill !== 0);
  17503. /* backwards increment the len-bit code huff */
  17504. incr = 1 << (len - 1);
  17505. while (huff & incr) {
  17506. incr >>= 1;
  17507. }
  17508. if (incr !== 0) {
  17509. huff &= incr - 1;
  17510. huff += incr;
  17511. } else {
  17512. huff = 0;
  17513. }
  17514. /* go to next symbol, update count, len */
  17515. sym++;
  17516. if (--count[len] === 0) {
  17517. if (len === max) { break; }
  17518. len = lens[lens_index + work[sym]];
  17519. }
  17520. /* create new sub-table if needed */
  17521. if (len > root && (huff & mask) !== low) {
  17522. /* if first time, transition to sub-tables */
  17523. if (drop === 0) {
  17524. drop = root;
  17525. }
  17526. /* increment past last table */
  17527. next += min; /* here min is 1 << curr */
  17528. /* determine length of next table */
  17529. curr = len - drop;
  17530. left = 1 << curr;
  17531. while (curr + drop < max) {
  17532. left -= count[curr + drop];
  17533. if (left <= 0) { break; }
  17534. curr++;
  17535. left <<= 1;
  17536. }
  17537. /* check for enough space */
  17538. used += 1 << curr;
  17539. if ((type === LENS && used > ENOUGH_LENS) ||
  17540. (type === DISTS && used > ENOUGH_DISTS)) {
  17541. return 1;
  17542. }
  17543. /* point entry in root table to sub-table */
  17544. low = huff & mask;
  17545. /*table.op[low] = curr;
  17546. table.bits[low] = root;
  17547. table.val[low] = next - opts.table_index;*/
  17548. table[low] = (root << 24) | (curr << 16) | (next - table_index) |0;
  17549. }
  17550. }
  17551. /* fill in remaining table entry if code is incomplete (guaranteed to have
  17552. at most one remaining entry, since if the code is incomplete, the
  17553. maximum code length that was allowed to get this far is one bit) */
  17554. if (huff !== 0) {
  17555. //table.op[next + huff] = 64; /* invalid code marker */
  17556. //table.bits[next + huff] = len - drop;
  17557. //table.val[next + huff] = 0;
  17558. table[next + huff] = ((len - drop) << 24) | (64 << 16) |0;
  17559. }
  17560. /* set return parameters */
  17561. //opts.table_index += used;
  17562. opts.bits = root;
  17563. return 0;
  17564. };
  17565. },{"../utils/common":52}],62:[function(require,module,exports){
  17566. 'use strict';
  17567. module.exports = {
  17568. '2': 'need dictionary', /* Z_NEED_DICT 2 */
  17569. '1': 'stream end', /* Z_STREAM_END 1 */
  17570. '0': '', /* Z_OK 0 */
  17571. '-1': 'file error', /* Z_ERRNO (-1) */
  17572. '-2': 'stream error', /* Z_STREAM_ERROR (-2) */
  17573. '-3': 'data error', /* Z_DATA_ERROR (-3) */
  17574. '-4': 'insufficient memory', /* Z_MEM_ERROR (-4) */
  17575. '-5': 'buffer error', /* Z_BUF_ERROR (-5) */
  17576. '-6': 'incompatible version' /* Z_VERSION_ERROR (-6) */
  17577. };
  17578. },{}],63:[function(require,module,exports){
  17579. 'use strict';
  17580. var utils = require('../utils/common');
  17581. /* Public constants ==========================================================*/
  17582. /* ===========================================================================*/
  17583. //var Z_FILTERED = 1;
  17584. //var Z_HUFFMAN_ONLY = 2;
  17585. //var Z_RLE = 3;
  17586. var Z_FIXED = 4;
  17587. //var Z_DEFAULT_STRATEGY = 0;
  17588. /* Possible values of the data_type field (though see inflate()) */
  17589. var Z_BINARY = 0;
  17590. var Z_TEXT = 1;
  17591. //var Z_ASCII = 1; // = Z_TEXT
  17592. var Z_UNKNOWN = 2;
  17593. /*============================================================================*/
  17594. function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
  17595. // From zutil.h
  17596. var STORED_BLOCK = 0;
  17597. var STATIC_TREES = 1;
  17598. var DYN_TREES = 2;
  17599. /* The three kinds of block type */
  17600. var MIN_MATCH = 3;
  17601. var MAX_MATCH = 258;
  17602. /* The minimum and maximum match lengths */
  17603. // From deflate.h
  17604. /* ===========================================================================
  17605. * Internal compression state.
  17606. */
  17607. var LENGTH_CODES = 29;
  17608. /* number of length codes, not counting the special END_BLOCK code */
  17609. var LITERALS = 256;
  17610. /* number of literal bytes 0..255 */
  17611. var L_CODES = LITERALS + 1 + LENGTH_CODES;
  17612. /* number of Literal or Length codes, including the END_BLOCK code */
  17613. var D_CODES = 30;
  17614. /* number of distance codes */
  17615. var BL_CODES = 19;
  17616. /* number of codes used to transfer the bit lengths */
  17617. var HEAP_SIZE = 2*L_CODES + 1;
  17618. /* maximum heap size */
  17619. var MAX_BITS = 15;
  17620. /* All codes must not exceed MAX_BITS bits */
  17621. var Buf_size = 16;
  17622. /* size of bit buffer in bi_buf */
  17623. /* ===========================================================================
  17624. * Constants
  17625. */
  17626. var MAX_BL_BITS = 7;
  17627. /* Bit length codes must not exceed MAX_BL_BITS bits */
  17628. var END_BLOCK = 256;
  17629. /* end of block literal code */
  17630. var REP_3_6 = 16;
  17631. /* repeat previous bit length 3-6 times (2 bits of repeat count) */
  17632. var REPZ_3_10 = 17;
  17633. /* repeat a zero length 3-10 times (3 bits of repeat count) */
  17634. var REPZ_11_138 = 18;
  17635. /* repeat a zero length 11-138 times (7 bits of repeat count) */
  17636. var extra_lbits = /* extra bits for each length code */
  17637. [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];
  17638. var extra_dbits = /* extra bits for each distance code */
  17639. [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];
  17640. var extra_blbits = /* extra bits for each bit length code */
  17641. [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7];
  17642. var bl_order =
  17643. [16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];
  17644. /* The lengths of the bit length codes are sent in order of decreasing
  17645. * probability, to avoid transmitting the lengths for unused bit length codes.
  17646. */
  17647. /* ===========================================================================
  17648. * Local data. These are initialized only once.
  17649. */
  17650. // We pre-fill arrays with 0 to avoid uninitialized gaps
  17651. var DIST_CODE_LEN = 512; /* see definition of array dist_code below */
  17652. // !!!! Use flat array insdead of structure, Freq = i*2, Len = i*2+1
  17653. var static_ltree = new Array((L_CODES+2) * 2);
  17654. zero(static_ltree);
  17655. /* The static literal tree. Since the bit lengths are imposed, there is no
  17656. * need for the L_CODES extra codes used during heap construction. However
  17657. * The codes 286 and 287 are needed to build a canonical tree (see _tr_init
  17658. * below).
  17659. */
  17660. var static_dtree = new Array(D_CODES * 2);
  17661. zero(static_dtree);
  17662. /* The static distance tree. (Actually a trivial tree since all codes use
  17663. * 5 bits.)
  17664. */
  17665. var _dist_code = new Array(DIST_CODE_LEN);
  17666. zero(_dist_code);
  17667. /* Distance codes. The first 256 values correspond to the distances
  17668. * 3 .. 258, the last 256 values correspond to the top 8 bits of
  17669. * the 15 bit distances.
  17670. */
  17671. var _length_code = new Array(MAX_MATCH-MIN_MATCH+1);
  17672. zero(_length_code);
  17673. /* length code for each normalized match length (0 == MIN_MATCH) */
  17674. var base_length = new Array(LENGTH_CODES);
  17675. zero(base_length);
  17676. /* First normalized length for each code (0 = MIN_MATCH) */
  17677. var base_dist = new Array(D_CODES);
  17678. zero(base_dist);
  17679. /* First normalized distance for each code (0 = distance of 1) */
  17680. var StaticTreeDesc = function (static_tree, extra_bits, extra_base, elems, max_length) {
  17681. this.static_tree = static_tree; /* static tree or NULL */
  17682. this.extra_bits = extra_bits; /* extra bits for each code or NULL */
  17683. this.extra_base = extra_base; /* base index for extra_bits */
  17684. this.elems = elems; /* max number of elements in the tree */
  17685. this.max_length = max_length; /* max bit length for the codes */
  17686. // show if `static_tree` has data or dummy - needed for monomorphic objects
  17687. this.has_stree = static_tree && static_tree.length;
  17688. };
  17689. var static_l_desc;
  17690. var static_d_desc;
  17691. var static_bl_desc;
  17692. var TreeDesc = function(dyn_tree, stat_desc) {
  17693. this.dyn_tree = dyn_tree; /* the dynamic tree */
  17694. this.max_code = 0; /* largest code with non zero frequency */
  17695. this.stat_desc = stat_desc; /* the corresponding static tree */
  17696. };
  17697. function d_code(dist) {
  17698. return dist < 256 ? _dist_code[dist] : _dist_code[256 + (dist >>> 7)];
  17699. }
  17700. /* ===========================================================================
  17701. * Output a short LSB first on the stream.
  17702. * IN assertion: there is enough room in pendingBuf.
  17703. */
  17704. function put_short (s, w) {
  17705. // put_byte(s, (uch)((w) & 0xff));
  17706. // put_byte(s, (uch)((ush)(w) >> 8));
  17707. s.pending_buf[s.pending++] = (w) & 0xff;
  17708. s.pending_buf[s.pending++] = (w >>> 8) & 0xff;
  17709. }
  17710. /* ===========================================================================
  17711. * Send a value on a given number of bits.
  17712. * IN assertion: length <= 16 and value fits in length bits.
  17713. */
  17714. function send_bits(s, value, length) {
  17715. if (s.bi_valid > (Buf_size - length)) {
  17716. s.bi_buf |= (value << s.bi_valid) & 0xffff;
  17717. put_short(s, s.bi_buf);
  17718. s.bi_buf = value >> (Buf_size - s.bi_valid);
  17719. s.bi_valid += length - Buf_size;
  17720. } else {
  17721. s.bi_buf |= (value << s.bi_valid) & 0xffff;
  17722. s.bi_valid += length;
  17723. }
  17724. }
  17725. function send_code(s, c, tree) {
  17726. send_bits(s, tree[c*2]/*.Code*/, tree[c*2 + 1]/*.Len*/);
  17727. }
  17728. /* ===========================================================================
  17729. * Reverse the first len bits of a code, using straightforward code (a faster
  17730. * method would use a table)
  17731. * IN assertion: 1 <= len <= 15
  17732. */
  17733. function bi_reverse(code, len) {
  17734. var res = 0;
  17735. do {
  17736. res |= code & 1;
  17737. code >>>= 1;
  17738. res <<= 1;
  17739. } while (--len > 0);
  17740. return res >>> 1;
  17741. }
  17742. /* ===========================================================================
  17743. * Flush the bit buffer, keeping at most 7 bits in it.
  17744. */
  17745. function bi_flush(s) {
  17746. if (s.bi_valid === 16) {
  17747. put_short(s, s.bi_buf);
  17748. s.bi_buf = 0;
  17749. s.bi_valid = 0;
  17750. } else if (s.bi_valid >= 8) {
  17751. s.pending_buf[s.pending++] = s.bi_buf & 0xff;
  17752. s.bi_buf >>= 8;
  17753. s.bi_valid -= 8;
  17754. }
  17755. }
  17756. /* ===========================================================================
  17757. * Compute the optimal bit lengths for a tree and update the total bit length
  17758. * for the current block.
  17759. * IN assertion: the fields freq and dad are set, heap[heap_max] and
  17760. * above are the tree nodes sorted by increasing frequency.
  17761. * OUT assertions: the field len is set to the optimal bit length, the
  17762. * array bl_count contains the frequencies for each bit length.
  17763. * The length opt_len is updated; static_len is also updated if stree is
  17764. * not null.
  17765. */
  17766. function gen_bitlen(s, desc)
  17767. // deflate_state *s;
  17768. // tree_desc *desc; /* the tree descriptor */
  17769. {
  17770. var tree = desc.dyn_tree;
  17771. var max_code = desc.max_code;
  17772. var stree = desc.stat_desc.static_tree;
  17773. var has_stree = desc.stat_desc.has_stree;
  17774. var extra = desc.stat_desc.extra_bits;
  17775. var base = desc.stat_desc.extra_base;
  17776. var max_length = desc.stat_desc.max_length;
  17777. var h; /* heap index */
  17778. var n, m; /* iterate over the tree elements */
  17779. var bits; /* bit length */
  17780. var xbits; /* extra bits */
  17781. var f; /* frequency */
  17782. var overflow = 0; /* number of elements with bit length too large */
  17783. for (bits = 0; bits <= MAX_BITS; bits++) {
  17784. s.bl_count[bits] = 0;
  17785. }
  17786. /* In a first pass, compute the optimal bit lengths (which may
  17787. * overflow in the case of the bit length tree).
  17788. */
  17789. tree[s.heap[s.heap_max]*2 + 1]/*.Len*/ = 0; /* root of the heap */
  17790. for (h = s.heap_max+1; h < HEAP_SIZE; h++) {
  17791. n = s.heap[h];
  17792. bits = tree[tree[n*2 +1]/*.Dad*/ * 2 + 1]/*.Len*/ + 1;
  17793. if (bits > max_length) {
  17794. bits = max_length;
  17795. overflow++;
  17796. }
  17797. tree[n*2 + 1]/*.Len*/ = bits;
  17798. /* We overwrite tree[n].Dad which is no longer needed */
  17799. if (n > max_code) { continue; } /* not a leaf node */
  17800. s.bl_count[bits]++;
  17801. xbits = 0;
  17802. if (n >= base) {
  17803. xbits = extra[n-base];
  17804. }
  17805. f = tree[n * 2]/*.Freq*/;
  17806. s.opt_len += f * (bits + xbits);
  17807. if (has_stree) {
  17808. s.static_len += f * (stree[n*2 + 1]/*.Len*/ + xbits);
  17809. }
  17810. }
  17811. if (overflow === 0) { return; }
  17812. // Trace((stderr,"\nbit length overflow\n"));
  17813. /* This happens for example on obj2 and pic of the Calgary corpus */
  17814. /* Find the first bit length which could increase: */
  17815. do {
  17816. bits = max_length-1;
  17817. while (s.bl_count[bits] === 0) { bits--; }
  17818. s.bl_count[bits]--; /* move one leaf down the tree */
  17819. s.bl_count[bits+1] += 2; /* move one overflow item as its brother */
  17820. s.bl_count[max_length]--;
  17821. /* The brother of the overflow item also moves one step up,
  17822. * but this does not affect bl_count[max_length]
  17823. */
  17824. overflow -= 2;
  17825. } while (overflow > 0);
  17826. /* Now recompute all bit lengths, scanning in increasing frequency.
  17827. * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all
  17828. * lengths instead of fixing only the wrong ones. This idea is taken
  17829. * from 'ar' written by Haruhiko Okumura.)
  17830. */
  17831. for (bits = max_length; bits !== 0; bits--) {
  17832. n = s.bl_count[bits];
  17833. while (n !== 0) {
  17834. m = s.heap[--h];
  17835. if (m > max_code) { continue; }
  17836. if (tree[m*2 + 1]/*.Len*/ !== bits) {
  17837. // Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits));
  17838. s.opt_len += (bits - tree[m*2 + 1]/*.Len*/)*tree[m*2]/*.Freq*/;
  17839. tree[m*2 + 1]/*.Len*/ = bits;
  17840. }
  17841. n--;
  17842. }
  17843. }
  17844. }
  17845. /* ===========================================================================
  17846. * Generate the codes for a given tree and bit counts (which need not be
  17847. * optimal).
  17848. * IN assertion: the array bl_count contains the bit length statistics for
  17849. * the given tree and the field len is set for all tree elements.
  17850. * OUT assertion: the field code is set for all tree elements of non
  17851. * zero code length.
  17852. */
  17853. function gen_codes(tree, max_code, bl_count)
  17854. // ct_data *tree; /* the tree to decorate */
  17855. // int max_code; /* largest code with non zero frequency */
  17856. // ushf *bl_count; /* number of codes at each bit length */
  17857. {
  17858. var next_code = new Array(MAX_BITS+1); /* next code value for each bit length */
  17859. var code = 0; /* running code value */
  17860. var bits; /* bit index */
  17861. var n; /* code index */
  17862. /* The distribution counts are first used to generate the code values
  17863. * without bit reversal.
  17864. */
  17865. for (bits = 1; bits <= MAX_BITS; bits++) {
  17866. next_code[bits] = code = (code + bl_count[bits-1]) << 1;
  17867. }
  17868. /* Check that the bit counts in bl_count are consistent. The last code
  17869. * must be all ones.
  17870. */
  17871. //Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,
  17872. // "inconsistent bit counts");
  17873. //Tracev((stderr,"\ngen_codes: max_code %d ", max_code));
  17874. for (n = 0; n <= max_code; n++) {
  17875. var len = tree[n*2 + 1]/*.Len*/;
  17876. if (len === 0) { continue; }
  17877. /* Now reverse the bits */
  17878. tree[n*2]/*.Code*/ = bi_reverse(next_code[len]++, len);
  17879. //Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ",
  17880. // n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1));
  17881. }
  17882. }
  17883. /* ===========================================================================
  17884. * Initialize the various 'constant' tables.
  17885. */
  17886. function tr_static_init() {
  17887. var n; /* iterates over tree elements */
  17888. var bits; /* bit counter */
  17889. var length; /* length value */
  17890. var code; /* code value */
  17891. var dist; /* distance index */
  17892. var bl_count = new Array(MAX_BITS+1);
  17893. /* number of codes at each bit length for an optimal tree */
  17894. // do check in _tr_init()
  17895. //if (static_init_done) return;
  17896. /* For some embedded targets, global variables are not initialized: */
  17897. /*#ifdef NO_INIT_GLOBAL_POINTERS
  17898. static_l_desc.static_tree = static_ltree;
  17899. static_l_desc.extra_bits = extra_lbits;
  17900. static_d_desc.static_tree = static_dtree;
  17901. static_d_desc.extra_bits = extra_dbits;
  17902. static_bl_desc.extra_bits = extra_blbits;
  17903. #endif*/
  17904. /* Initialize the mapping length (0..255) -> length code (0..28) */
  17905. length = 0;
  17906. for (code = 0; code < LENGTH_CODES-1; code++) {
  17907. base_length[code] = length;
  17908. for (n = 0; n < (1<<extra_lbits[code]); n++) {
  17909. _length_code[length++] = code;
  17910. }
  17911. }
  17912. //Assert (length == 256, "tr_static_init: length != 256");
  17913. /* Note that the length 255 (match length 258) can be represented
  17914. * in two different ways: code 284 + 5 bits or code 285, so we
  17915. * overwrite length_code[255] to use the best encoding:
  17916. */
  17917. _length_code[length-1] = code;
  17918. /* Initialize the mapping dist (0..32K) -> dist code (0..29) */
  17919. dist = 0;
  17920. for (code = 0 ; code < 16; code++) {
  17921. base_dist[code] = dist;
  17922. for (n = 0; n < (1<<extra_dbits[code]); n++) {
  17923. _dist_code[dist++] = code;
  17924. }
  17925. }
  17926. //Assert (dist == 256, "tr_static_init: dist != 256");
  17927. dist >>= 7; /* from now on, all distances are divided by 128 */
  17928. for (; code < D_CODES; code++) {
  17929. base_dist[code] = dist << 7;
  17930. for (n = 0; n < (1<<(extra_dbits[code]-7)); n++) {
  17931. _dist_code[256 + dist++] = code;
  17932. }
  17933. }
  17934. //Assert (dist == 256, "tr_static_init: 256+dist != 512");
  17935. /* Construct the codes of the static literal tree */
  17936. for (bits = 0; bits <= MAX_BITS; bits++) {
  17937. bl_count[bits] = 0;
  17938. }
  17939. n = 0;
  17940. while (n <= 143) {
  17941. static_ltree[n*2 + 1]/*.Len*/ = 8;
  17942. n++;
  17943. bl_count[8]++;
  17944. }
  17945. while (n <= 255) {
  17946. static_ltree[n*2 + 1]/*.Len*/ = 9;
  17947. n++;
  17948. bl_count[9]++;
  17949. }
  17950. while (n <= 279) {
  17951. static_ltree[n*2 + 1]/*.Len*/ = 7;
  17952. n++;
  17953. bl_count[7]++;
  17954. }
  17955. while (n <= 287) {
  17956. static_ltree[n*2 + 1]/*.Len*/ = 8;
  17957. n++;
  17958. bl_count[8]++;
  17959. }
  17960. /* Codes 286 and 287 do not exist, but we must include them in the
  17961. * tree construction to get a canonical Huffman tree (longest code
  17962. * all ones)
  17963. */
  17964. gen_codes(static_ltree, L_CODES+1, bl_count);
  17965. /* The static distance tree is trivial: */
  17966. for (n = 0; n < D_CODES; n++) {
  17967. static_dtree[n*2 + 1]/*.Len*/ = 5;
  17968. static_dtree[n*2]/*.Code*/ = bi_reverse(n, 5);
  17969. }
  17970. // Now data ready and we can init static trees
  17971. static_l_desc = new StaticTreeDesc(static_ltree, extra_lbits, LITERALS+1, L_CODES, MAX_BITS);
  17972. static_d_desc = new StaticTreeDesc(static_dtree, extra_dbits, 0, D_CODES, MAX_BITS);
  17973. static_bl_desc =new StaticTreeDesc(new Array(0), extra_blbits, 0, BL_CODES, MAX_BL_BITS);
  17974. //static_init_done = true;
  17975. }
  17976. /* ===========================================================================
  17977. * Initialize a new block.
  17978. */
  17979. function init_block(s) {
  17980. var n; /* iterates over tree elements */
  17981. /* Initialize the trees. */
  17982. for (n = 0; n < L_CODES; n++) { s.dyn_ltree[n*2]/*.Freq*/ = 0; }
  17983. for (n = 0; n < D_CODES; n++) { s.dyn_dtree[n*2]/*.Freq*/ = 0; }
  17984. for (n = 0; n < BL_CODES; n++) { s.bl_tree[n*2]/*.Freq*/ = 0; }
  17985. s.dyn_ltree[END_BLOCK*2]/*.Freq*/ = 1;
  17986. s.opt_len = s.static_len = 0;
  17987. s.last_lit = s.matches = 0;
  17988. }
  17989. /* ===========================================================================
  17990. * Flush the bit buffer and align the output on a byte boundary
  17991. */
  17992. function bi_windup(s)
  17993. {
  17994. if (s.bi_valid > 8) {
  17995. put_short(s, s.bi_buf);
  17996. } else if (s.bi_valid > 0) {
  17997. //put_byte(s, (Byte)s->bi_buf);
  17998. s.pending_buf[s.pending++] = s.bi_buf;
  17999. }
  18000. s.bi_buf = 0;
  18001. s.bi_valid = 0;
  18002. }
  18003. /* ===========================================================================
  18004. * Copy a stored block, storing first the length and its
  18005. * one's complement if requested.
  18006. */
  18007. function copy_block(s, buf, len, header)
  18008. //DeflateState *s;
  18009. //charf *buf; /* the input data */
  18010. //unsigned len; /* its length */
  18011. //int header; /* true if block header must be written */
  18012. {
  18013. bi_windup(s); /* align on byte boundary */
  18014. if (header) {
  18015. put_short(s, len);
  18016. put_short(s, ~len);
  18017. }
  18018. // while (len--) {
  18019. // put_byte(s, *buf++);
  18020. // }
  18021. utils.arraySet(s.pending_buf, s.window, buf, len, s.pending);
  18022. s.pending += len;
  18023. }
  18024. /* ===========================================================================
  18025. * Compares to subtrees, using the tree depth as tie breaker when
  18026. * the subtrees have equal frequency. This minimizes the worst case length.
  18027. */
  18028. function smaller(tree, n, m, depth) {
  18029. var _n2 = n*2;
  18030. var _m2 = m*2;
  18031. return (tree[_n2]/*.Freq*/ < tree[_m2]/*.Freq*/ ||
  18032. (tree[_n2]/*.Freq*/ === tree[_m2]/*.Freq*/ && depth[n] <= depth[m]));
  18033. }
  18034. /* ===========================================================================
  18035. * Restore the heap property by moving down the tree starting at node k,
  18036. * exchanging a node with the smallest of its two sons if necessary, stopping
  18037. * when the heap property is re-established (each father smaller than its
  18038. * two sons).
  18039. */
  18040. function pqdownheap(s, tree, k)
  18041. // deflate_state *s;
  18042. // ct_data *tree; /* the tree to restore */
  18043. // int k; /* node to move down */
  18044. {
  18045. var v = s.heap[k];
  18046. var j = k << 1; /* left son of k */
  18047. while (j <= s.heap_len) {
  18048. /* Set j to the smallest of the two sons: */
  18049. if (j < s.heap_len &&
  18050. smaller(tree, s.heap[j+1], s.heap[j], s.depth)) {
  18051. j++;
  18052. }
  18053. /* Exit if v is smaller than both sons */
  18054. if (smaller(tree, v, s.heap[j], s.depth)) { break; }
  18055. /* Exchange v with the smallest son */
  18056. s.heap[k] = s.heap[j];
  18057. k = j;
  18058. /* And continue down the tree, setting j to the left son of k */
  18059. j <<= 1;
  18060. }
  18061. s.heap[k] = v;
  18062. }
  18063. // inlined manually
  18064. // var SMALLEST = 1;
  18065. /* ===========================================================================
  18066. * Send the block data compressed using the given Huffman trees
  18067. */
  18068. function compress_block(s, ltree, dtree)
  18069. // deflate_state *s;
  18070. // const ct_data *ltree; /* literal tree */
  18071. // const ct_data *dtree; /* distance tree */
  18072. {
  18073. var dist; /* distance of matched string */
  18074. var lc; /* match length or unmatched char (if dist == 0) */
  18075. var lx = 0; /* running index in l_buf */
  18076. var code; /* the code to send */
  18077. var extra; /* number of extra bits to send */
  18078. if (s.last_lit !== 0) {
  18079. do {
  18080. dist = (s.pending_buf[s.d_buf + lx*2] << 8) | (s.pending_buf[s.d_buf + lx*2 + 1]);
  18081. lc = s.pending_buf[s.l_buf + lx];
  18082. lx++;
  18083. if (dist === 0) {
  18084. send_code(s, lc, ltree); /* send a literal byte */
  18085. //Tracecv(isgraph(lc), (stderr," '%c' ", lc));
  18086. } else {
  18087. /* Here, lc is the match length - MIN_MATCH */
  18088. code = _length_code[lc];
  18089. send_code(s, code+LITERALS+1, ltree); /* send the length code */
  18090. extra = extra_lbits[code];
  18091. if (extra !== 0) {
  18092. lc -= base_length[code];
  18093. send_bits(s, lc, extra); /* send the extra length bits */
  18094. }
  18095. dist--; /* dist is now the match distance - 1 */
  18096. code = d_code(dist);
  18097. //Assert (code < D_CODES, "bad d_code");
  18098. send_code(s, code, dtree); /* send the distance code */
  18099. extra = extra_dbits[code];
  18100. if (extra !== 0) {
  18101. dist -= base_dist[code];
  18102. send_bits(s, dist, extra); /* send the extra distance bits */
  18103. }
  18104. } /* literal or match pair ? */
  18105. /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */
  18106. //Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx,
  18107. // "pendingBuf overflow");
  18108. } while (lx < s.last_lit);
  18109. }
  18110. send_code(s, END_BLOCK, ltree);
  18111. }
  18112. /* ===========================================================================
  18113. * Construct one Huffman tree and assigns the code bit strings and lengths.
  18114. * Update the total bit length for the current block.
  18115. * IN assertion: the field freq is set for all tree elements.
  18116. * OUT assertions: the fields len and code are set to the optimal bit length
  18117. * and corresponding code. The length opt_len is updated; static_len is
  18118. * also updated if stree is not null. The field max_code is set.
  18119. */
  18120. function build_tree(s, desc)
  18121. // deflate_state *s;
  18122. // tree_desc *desc; /* the tree descriptor */
  18123. {
  18124. var tree = desc.dyn_tree;
  18125. var stree = desc.stat_desc.static_tree;
  18126. var has_stree = desc.stat_desc.has_stree;
  18127. var elems = desc.stat_desc.elems;
  18128. var n, m; /* iterate over heap elements */
  18129. var max_code = -1; /* largest code with non zero frequency */
  18130. var node; /* new node being created */
  18131. /* Construct the initial heap, with least frequent element in
  18132. * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
  18133. * heap[0] is not used.
  18134. */
  18135. s.heap_len = 0;
  18136. s.heap_max = HEAP_SIZE;
  18137. for (n = 0; n < elems; n++) {
  18138. if (tree[n * 2]/*.Freq*/ !== 0) {
  18139. s.heap[++s.heap_len] = max_code = n;
  18140. s.depth[n] = 0;
  18141. } else {
  18142. tree[n*2 + 1]/*.Len*/ = 0;
  18143. }
  18144. }
  18145. /* The pkzip format requires that at least one distance code exists,
  18146. * and that at least one bit should be sent even if there is only one
  18147. * possible code. So to avoid special checks later on we force at least
  18148. * two codes of non zero frequency.
  18149. */
  18150. while (s.heap_len < 2) {
  18151. node = s.heap[++s.heap_len] = (max_code < 2 ? ++max_code : 0);
  18152. tree[node * 2]/*.Freq*/ = 1;
  18153. s.depth[node] = 0;
  18154. s.opt_len--;
  18155. if (has_stree) {
  18156. s.static_len -= stree[node*2 + 1]/*.Len*/;
  18157. }
  18158. /* node is 0 or 1 so it does not have extra bits */
  18159. }
  18160. desc.max_code = max_code;
  18161. /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
  18162. * establish sub-heaps of increasing lengths:
  18163. */
  18164. for (n = (s.heap_len >> 1/*int /2*/); n >= 1; n--) { pqdownheap(s, tree, n); }
  18165. /* Construct the Huffman tree by repeatedly combining the least two
  18166. * frequent nodes.
  18167. */
  18168. node = elems; /* next internal node of the tree */
  18169. do {
  18170. //pqremove(s, tree, n); /* n = node of least frequency */
  18171. /*** pqremove ***/
  18172. n = s.heap[1/*SMALLEST*/];
  18173. s.heap[1/*SMALLEST*/] = s.heap[s.heap_len--];
  18174. pqdownheap(s, tree, 1/*SMALLEST*/);
  18175. /***/
  18176. m = s.heap[1/*SMALLEST*/]; /* m = node of next least frequency */
  18177. s.heap[--s.heap_max] = n; /* keep the nodes sorted by frequency */
  18178. s.heap[--s.heap_max] = m;
  18179. /* Create a new node father of n and m */
  18180. tree[node * 2]/*.Freq*/ = tree[n * 2]/*.Freq*/ + tree[m * 2]/*.Freq*/;
  18181. s.depth[node] = (s.depth[n] >= s.depth[m] ? s.depth[n] : s.depth[m]) + 1;
  18182. tree[n*2 + 1]/*.Dad*/ = tree[m*2 + 1]/*.Dad*/ = node;
  18183. /* and insert the new node in the heap */
  18184. s.heap[1/*SMALLEST*/] = node++;
  18185. pqdownheap(s, tree, 1/*SMALLEST*/);
  18186. } while (s.heap_len >= 2);
  18187. s.heap[--s.heap_max] = s.heap[1/*SMALLEST*/];
  18188. /* At this point, the fields freq and dad are set. We can now
  18189. * generate the bit lengths.
  18190. */
  18191. gen_bitlen(s, desc);
  18192. /* The field len is now set, we can generate the bit codes */
  18193. gen_codes(tree, max_code, s.bl_count);
  18194. }
  18195. /* ===========================================================================
  18196. * Scan a literal or distance tree to determine the frequencies of the codes
  18197. * in the bit length tree.
  18198. */
  18199. function scan_tree(s, tree, max_code)
  18200. // deflate_state *s;
  18201. // ct_data *tree; /* the tree to be scanned */
  18202. // int max_code; /* and its largest code of non zero frequency */
  18203. {
  18204. var n; /* iterates over all tree elements */
  18205. var prevlen = -1; /* last emitted length */
  18206. var curlen; /* length of current code */
  18207. var nextlen = tree[0*2 + 1]/*.Len*/; /* length of next code */
  18208. var count = 0; /* repeat count of the current code */
  18209. var max_count = 7; /* max repeat count */
  18210. var min_count = 4; /* min repeat count */
  18211. if (nextlen === 0) {
  18212. max_count = 138;
  18213. min_count = 3;
  18214. }
  18215. tree[(max_code+1)*2 + 1]/*.Len*/ = 0xffff; /* guard */
  18216. for (n = 0; n <= max_code; n++) {
  18217. curlen = nextlen;
  18218. nextlen = tree[(n+1)*2 + 1]/*.Len*/;
  18219. if (++count < max_count && curlen === nextlen) {
  18220. continue;
  18221. } else if (count < min_count) {
  18222. s.bl_tree[curlen * 2]/*.Freq*/ += count;
  18223. } else if (curlen !== 0) {
  18224. if (curlen !== prevlen) { s.bl_tree[curlen * 2]/*.Freq*/++; }
  18225. s.bl_tree[REP_3_6*2]/*.Freq*/++;
  18226. } else if (count <= 10) {
  18227. s.bl_tree[REPZ_3_10*2]/*.Freq*/++;
  18228. } else {
  18229. s.bl_tree[REPZ_11_138*2]/*.Freq*/++;
  18230. }
  18231. count = 0;
  18232. prevlen = curlen;
  18233. if (nextlen === 0) {
  18234. max_count = 138;
  18235. min_count = 3;
  18236. } else if (curlen === nextlen) {
  18237. max_count = 6;
  18238. min_count = 3;
  18239. } else {
  18240. max_count = 7;
  18241. min_count = 4;
  18242. }
  18243. }
  18244. }
  18245. /* ===========================================================================
  18246. * Send a literal or distance tree in compressed form, using the codes in
  18247. * bl_tree.
  18248. */
  18249. function send_tree(s, tree, max_code)
  18250. // deflate_state *s;
  18251. // ct_data *tree; /* the tree to be scanned */
  18252. // int max_code; /* and its largest code of non zero frequency */
  18253. {
  18254. var n; /* iterates over all tree elements */
  18255. var prevlen = -1; /* last emitted length */
  18256. var curlen; /* length of current code */
  18257. var nextlen = tree[0*2 + 1]/*.Len*/; /* length of next code */
  18258. var count = 0; /* repeat count of the current code */
  18259. var max_count = 7; /* max repeat count */
  18260. var min_count = 4; /* min repeat count */
  18261. /* tree[max_code+1].Len = -1; */ /* guard already set */
  18262. if (nextlen === 0) {
  18263. max_count = 138;
  18264. min_count = 3;
  18265. }
  18266. for (n = 0; n <= max_code; n++) {
  18267. curlen = nextlen;
  18268. nextlen = tree[(n+1)*2 + 1]/*.Len*/;
  18269. if (++count < max_count && curlen === nextlen) {
  18270. continue;
  18271. } else if (count < min_count) {
  18272. do { send_code(s, curlen, s.bl_tree); } while (--count !== 0);
  18273. } else if (curlen !== 0) {
  18274. if (curlen !== prevlen) {
  18275. send_code(s, curlen, s.bl_tree);
  18276. count--;
  18277. }
  18278. //Assert(count >= 3 && count <= 6, " 3_6?");
  18279. send_code(s, REP_3_6, s.bl_tree);
  18280. send_bits(s, count-3, 2);
  18281. } else if (count <= 10) {
  18282. send_code(s, REPZ_3_10, s.bl_tree);
  18283. send_bits(s, count-3, 3);
  18284. } else {
  18285. send_code(s, REPZ_11_138, s.bl_tree);
  18286. send_bits(s, count-11, 7);
  18287. }
  18288. count = 0;
  18289. prevlen = curlen;
  18290. if (nextlen === 0) {
  18291. max_count = 138;
  18292. min_count = 3;
  18293. } else if (curlen === nextlen) {
  18294. max_count = 6;
  18295. min_count = 3;
  18296. } else {
  18297. max_count = 7;
  18298. min_count = 4;
  18299. }
  18300. }
  18301. }
  18302. /* ===========================================================================
  18303. * Construct the Huffman tree for the bit lengths and return the index in
  18304. * bl_order of the last bit length code to send.
  18305. */
  18306. function build_bl_tree(s) {
  18307. var max_blindex; /* index of last bit length code of non zero freq */
  18308. /* Determine the bit length frequencies for literal and distance trees */
  18309. scan_tree(s, s.dyn_ltree, s.l_desc.max_code);
  18310. scan_tree(s, s.dyn_dtree, s.d_desc.max_code);
  18311. /* Build the bit length tree: */
  18312. build_tree(s, s.bl_desc);
  18313. /* opt_len now includes the length of the tree representations, except
  18314. * the lengths of the bit lengths codes and the 5+5+4 bits for the counts.
  18315. */
  18316. /* Determine the number of bit length codes to send. The pkzip format
  18317. * requires that at least 4 bit length codes be sent. (appnote.txt says
  18318. * 3 but the actual value used is 4.)
  18319. */
  18320. for (max_blindex = BL_CODES-1; max_blindex >= 3; max_blindex--) {
  18321. if (s.bl_tree[bl_order[max_blindex]*2 + 1]/*.Len*/ !== 0) {
  18322. break;
  18323. }
  18324. }
  18325. /* Update opt_len to include the bit length tree and counts */
  18326. s.opt_len += 3*(max_blindex+1) + 5+5+4;
  18327. //Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld",
  18328. // s->opt_len, s->static_len));
  18329. return max_blindex;
  18330. }
  18331. /* ===========================================================================
  18332. * Send the header for a block using dynamic Huffman trees: the counts, the
  18333. * lengths of the bit length codes, the literal tree and the distance tree.
  18334. * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
  18335. */
  18336. function send_all_trees(s, lcodes, dcodes, blcodes)
  18337. // deflate_state *s;
  18338. // int lcodes, dcodes, blcodes; /* number of codes for each tree */
  18339. {
  18340. var rank; /* index in bl_order */
  18341. //Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes");
  18342. //Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,
  18343. // "too many codes");
  18344. //Tracev((stderr, "\nbl counts: "));
  18345. send_bits(s, lcodes-257, 5); /* not +255 as stated in appnote.txt */
  18346. send_bits(s, dcodes-1, 5);
  18347. send_bits(s, blcodes-4, 4); /* not -3 as stated in appnote.txt */
  18348. for (rank = 0; rank < blcodes; rank++) {
  18349. //Tracev((stderr, "\nbl code %2d ", bl_order[rank]));
  18350. send_bits(s, s.bl_tree[bl_order[rank]*2 + 1]/*.Len*/, 3);
  18351. }
  18352. //Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent));
  18353. send_tree(s, s.dyn_ltree, lcodes-1); /* literal tree */
  18354. //Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent));
  18355. send_tree(s, s.dyn_dtree, dcodes-1); /* distance tree */
  18356. //Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent));
  18357. }
  18358. /* ===========================================================================
  18359. * Check if the data type is TEXT or BINARY, using the following algorithm:
  18360. * - TEXT if the two conditions below are satisfied:
  18361. * a) There are no non-portable control characters belonging to the
  18362. * "black list" (0..6, 14..25, 28..31).
  18363. * b) There is at least one printable character belonging to the
  18364. * "white list" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255).
  18365. * - BINARY otherwise.
  18366. * - The following partially-portable control characters form a
  18367. * "gray list" that is ignored in this detection algorithm:
  18368. * (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}).
  18369. * IN assertion: the fields Freq of dyn_ltree are set.
  18370. */
  18371. function detect_data_type(s) {
  18372. /* black_mask is the bit mask of black-listed bytes
  18373. * set bits 0..6, 14..25, and 28..31
  18374. * 0xf3ffc07f = binary 11110011111111111100000001111111
  18375. */
  18376. var black_mask = 0xf3ffc07f;
  18377. var n;
  18378. /* Check for non-textual ("black-listed") bytes. */
  18379. for (n = 0; n <= 31; n++, black_mask >>>= 1) {
  18380. if ((black_mask & 1) && (s.dyn_ltree[n*2]/*.Freq*/ !== 0)) {
  18381. return Z_BINARY;
  18382. }
  18383. }
  18384. /* Check for textual ("white-listed") bytes. */
  18385. if (s.dyn_ltree[9 * 2]/*.Freq*/ !== 0 || s.dyn_ltree[10 * 2]/*.Freq*/ !== 0 ||
  18386. s.dyn_ltree[13 * 2]/*.Freq*/ !== 0) {
  18387. return Z_TEXT;
  18388. }
  18389. for (n = 32; n < LITERALS; n++) {
  18390. if (s.dyn_ltree[n * 2]/*.Freq*/ !== 0) {
  18391. return Z_TEXT;
  18392. }
  18393. }
  18394. /* There are no "black-listed" or "white-listed" bytes:
  18395. * this stream either is empty or has tolerated ("gray-listed") bytes only.
  18396. */
  18397. return Z_BINARY;
  18398. }
  18399. var static_init_done = false;
  18400. /* ===========================================================================
  18401. * Initialize the tree data structures for a new zlib stream.
  18402. */
  18403. function _tr_init(s)
  18404. {
  18405. if (!static_init_done) {
  18406. tr_static_init();
  18407. static_init_done = true;
  18408. }
  18409. s.l_desc = new TreeDesc(s.dyn_ltree, static_l_desc);
  18410. s.d_desc = new TreeDesc(s.dyn_dtree, static_d_desc);
  18411. s.bl_desc = new TreeDesc(s.bl_tree, static_bl_desc);
  18412. s.bi_buf = 0;
  18413. s.bi_valid = 0;
  18414. /* Initialize the first block of the first file: */
  18415. init_block(s);
  18416. }
  18417. /* ===========================================================================
  18418. * Send a stored block
  18419. */
  18420. function _tr_stored_block(s, buf, stored_len, last)
  18421. //DeflateState *s;
  18422. //charf *buf; /* input block */
  18423. //ulg stored_len; /* length of input block */
  18424. //int last; /* one if this is the last block for a file */
  18425. {
  18426. send_bits(s, (STORED_BLOCK<<1)+(last ? 1 : 0), 3); /* send block type */
  18427. copy_block(s, buf, stored_len, true); /* with header */
  18428. }
  18429. /* ===========================================================================
  18430. * Send one empty static block to give enough lookahead for inflate.
  18431. * This takes 10 bits, of which 7 may remain in the bit buffer.
  18432. */
  18433. function _tr_align(s) {
  18434. send_bits(s, STATIC_TREES<<1, 3);
  18435. send_code(s, END_BLOCK, static_ltree);
  18436. bi_flush(s);
  18437. }
  18438. /* ===========================================================================
  18439. * Determine the best encoding for the current block: dynamic trees, static
  18440. * trees or store, and output the encoded block to the zip file.
  18441. */
  18442. function _tr_flush_block(s, buf, stored_len, last)
  18443. //DeflateState *s;
  18444. //charf *buf; /* input block, or NULL if too old */
  18445. //ulg stored_len; /* length of input block */
  18446. //int last; /* one if this is the last block for a file */
  18447. {
  18448. var opt_lenb, static_lenb; /* opt_len and static_len in bytes */
  18449. var max_blindex = 0; /* index of last bit length code of non zero freq */
  18450. /* Build the Huffman trees unless a stored block is forced */
  18451. if (s.level > 0) {
  18452. /* Check if the file is binary or text */
  18453. if (s.strm.data_type === Z_UNKNOWN) {
  18454. s.strm.data_type = detect_data_type(s);
  18455. }
  18456. /* Construct the literal and distance trees */
  18457. build_tree(s, s.l_desc);
  18458. // Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len,
  18459. // s->static_len));
  18460. build_tree(s, s.d_desc);
  18461. // Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len,
  18462. // s->static_len));
  18463. /* At this point, opt_len and static_len are the total bit lengths of
  18464. * the compressed block data, excluding the tree representations.
  18465. */
  18466. /* Build the bit length tree for the above two trees, and get the index
  18467. * in bl_order of the last bit length code to send.
  18468. */
  18469. max_blindex = build_bl_tree(s);
  18470. /* Determine the best encoding. Compute the block lengths in bytes. */
  18471. opt_lenb = (s.opt_len+3+7) >>> 3;
  18472. static_lenb = (s.static_len+3+7) >>> 3;
  18473. // Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ",
  18474. // opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,
  18475. // s->last_lit));
  18476. if (static_lenb <= opt_lenb) { opt_lenb = static_lenb; }
  18477. } else {
  18478. // Assert(buf != (char*)0, "lost buf");
  18479. opt_lenb = static_lenb = stored_len + 5; /* force a stored block */
  18480. }
  18481. if ((stored_len+4 <= opt_lenb) && (buf !== -1)) {
  18482. /* 4: two words for the lengths */
  18483. /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
  18484. * Otherwise we can't have processed more than WSIZE input bytes since
  18485. * the last block flush, because compression would have been
  18486. * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
  18487. * transform a block into a stored block.
  18488. */
  18489. _tr_stored_block(s, buf, stored_len, last);
  18490. } else if (s.strategy === Z_FIXED || static_lenb === opt_lenb) {
  18491. send_bits(s, (STATIC_TREES<<1) + (last ? 1 : 0), 3);
  18492. compress_block(s, static_ltree, static_dtree);
  18493. } else {
  18494. send_bits(s, (DYN_TREES<<1) + (last ? 1 : 0), 3);
  18495. send_all_trees(s, s.l_desc.max_code+1, s.d_desc.max_code+1, max_blindex+1);
  18496. compress_block(s, s.dyn_ltree, s.dyn_dtree);
  18497. }
  18498. // Assert (s->compressed_len == s->bits_sent, "bad compressed size");
  18499. /* The above check is made mod 2^32, for files larger than 512 MB
  18500. * and uLong implemented on 32 bits.
  18501. */
  18502. init_block(s);
  18503. if (last) {
  18504. bi_windup(s);
  18505. }
  18506. // Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3,
  18507. // s->compressed_len-7*last));
  18508. }
  18509. /* ===========================================================================
  18510. * Save the match info and tally the frequency counts. Return true if
  18511. * the current block must be flushed.
  18512. */
  18513. function _tr_tally(s, dist, lc)
  18514. // deflate_state *s;
  18515. // unsigned dist; /* distance of matched string */
  18516. // unsigned lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */
  18517. {
  18518. //var out_length, in_length, dcode;
  18519. s.pending_buf[s.d_buf + s.last_lit * 2] = (dist >>> 8) & 0xff;
  18520. s.pending_buf[s.d_buf + s.last_lit * 2 + 1] = dist & 0xff;
  18521. s.pending_buf[s.l_buf + s.last_lit] = lc & 0xff;
  18522. s.last_lit++;
  18523. if (dist === 0) {
  18524. /* lc is the unmatched char */
  18525. s.dyn_ltree[lc*2]/*.Freq*/++;
  18526. } else {
  18527. s.matches++;
  18528. /* Here, lc is the match length - MIN_MATCH */
  18529. dist--; /* dist = match distance - 1 */
  18530. //Assert((ush)dist < (ush)MAX_DIST(s) &&
  18531. // (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&
  18532. // (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match");
  18533. s.dyn_ltree[(_length_code[lc]+LITERALS+1) * 2]/*.Freq*/++;
  18534. s.dyn_dtree[d_code(dist) * 2]/*.Freq*/++;
  18535. }
  18536. // (!) This block is disabled in zlib defailts,
  18537. // don't enable it for binary compatibility
  18538. //#ifdef TRUNCATE_BLOCK
  18539. // /* Try to guess if it is profitable to stop the current block here */
  18540. // if ((s.last_lit & 0x1fff) === 0 && s.level > 2) {
  18541. // /* Compute an upper bound for the compressed length */
  18542. // out_length = s.last_lit*8;
  18543. // in_length = s.strstart - s.block_start;
  18544. //
  18545. // for (dcode = 0; dcode < D_CODES; dcode++) {
  18546. // out_length += s.dyn_dtree[dcode*2]/*.Freq*/ * (5 + extra_dbits[dcode]);
  18547. // }
  18548. // out_length >>>= 3;
  18549. // //Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ",
  18550. // // s->last_lit, in_length, out_length,
  18551. // // 100L - out_length*100L/in_length));
  18552. // if (s.matches < (s.last_lit>>1)/*int /2*/ && out_length < (in_length>>1)/*int /2*/) {
  18553. // return true;
  18554. // }
  18555. // }
  18556. //#endif
  18557. return (s.last_lit === s.lit_bufsize-1);
  18558. /* We avoid equality with lit_bufsize because of wraparound at 64K
  18559. * on 16 bit machines and because stored blocks are restricted to
  18560. * 64K-1 bytes.
  18561. */
  18562. }
  18563. exports._tr_init = _tr_init;
  18564. exports._tr_stored_block = _tr_stored_block;
  18565. exports._tr_flush_block = _tr_flush_block;
  18566. exports._tr_tally = _tr_tally;
  18567. exports._tr_align = _tr_align;
  18568. },{"../utils/common":52}],64:[function(require,module,exports){
  18569. 'use strict';
  18570. function ZStream() {
  18571. /* next input byte */
  18572. this.input = null; // JS specific, because we have no pointers
  18573. this.next_in = 0;
  18574. /* number of bytes available at input */
  18575. this.avail_in = 0;
  18576. /* total number of input bytes read so far */
  18577. this.total_in = 0;
  18578. /* next output byte should be put there */
  18579. this.output = null; // JS specific, because we have no pointers
  18580. this.next_out = 0;
  18581. /* remaining free space at output */
  18582. this.avail_out = 0;
  18583. /* total number of bytes output so far */
  18584. this.total_out = 0;
  18585. /* last error message, NULL if no error */
  18586. this.msg = ''/*Z_NULL*/;
  18587. /* not visible by applications */
  18588. this.state = null;
  18589. /* best guess about the data type: binary or text */
  18590. this.data_type = 2/*Z_UNKNOWN*/;
  18591. /* adler32 value of the uncompressed data */
  18592. this.adler = 0;
  18593. }
  18594. module.exports = ZStream;
  18595. },{}],65:[function(require,module,exports){
  18596. /* Copyright @ 2015 Atlassian Pty Ltd
  18597. *
  18598. * Licensed under the Apache License, Version 2.0 (the "License");
  18599. * you may not use this file except in compliance with the License.
  18600. * You may obtain a copy of the License at
  18601. *
  18602. * http://www.apache.org/licenses/LICENSE-2.0
  18603. *
  18604. * Unless required by applicable law or agreed to in writing, software
  18605. * distributed under the License is distributed on an "AS IS" BASIS,
  18606. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  18607. * See the License for the specific language governing permissions and
  18608. * limitations under the License.
  18609. */
  18610. module.exports = function arrayEquals(array) {
  18611. // if the other array is a falsy value, return
  18612. if (!array)
  18613. return false;
  18614. // compare lengths - can save a lot of time
  18615. if (this.length != array.length)
  18616. return false;
  18617. for (var i = 0, l = this.length; i < l; i++) {
  18618. // Check if we have nested arrays
  18619. if (this[i] instanceof Array && array[i] instanceof Array) {
  18620. // recurse into the nested arrays
  18621. if (!arrayEquals.apply(this[i], [array[i]]))
  18622. return false;
  18623. } else if (this[i] != array[i]) {
  18624. // Warning - two different object instances will never be equal:
  18625. // {x:20} != {x:20}
  18626. return false;
  18627. }
  18628. }
  18629. return true;
  18630. };
  18631. },{}],66:[function(require,module,exports){
  18632. /* Copyright @ 2015 Atlassian Pty Ltd
  18633. *
  18634. * Licensed under the Apache License, Version 2.0 (the "License");
  18635. * you may not use this file except in compliance with the License.
  18636. * You may obtain a copy of the License at
  18637. *
  18638. * http://www.apache.org/licenses/LICENSE-2.0
  18639. *
  18640. * Unless required by applicable law or agreed to in writing, software
  18641. * distributed under the License is distributed on an "AS IS" BASIS,
  18642. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  18643. * See the License for the specific language governing permissions and
  18644. * limitations under the License.
  18645. */
  18646. exports.Interop = require('./interop');
  18647. },{"./interop":67}],67:[function(require,module,exports){
  18648. /* Copyright @ 2015 Atlassian Pty Ltd
  18649. *
  18650. * Licensed under the Apache License, Version 2.0 (the "License");
  18651. * you may not use this file except in compliance with the License.
  18652. * You may obtain a copy of the License at
  18653. *
  18654. * http://www.apache.org/licenses/LICENSE-2.0
  18655. *
  18656. * Unless required by applicable law or agreed to in writing, software
  18657. * distributed under the License is distributed on an "AS IS" BASIS,
  18658. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  18659. * See the License for the specific language governing permissions and
  18660. * limitations under the License.
  18661. */
  18662. /* global RTCSessionDescription */
  18663. /* jshint -W097 */
  18664. "use strict";
  18665. var transform = require('./transform');
  18666. var arrayEquals = require('./array-equals');
  18667. function Interop() {
  18668. /**
  18669. * This map holds the most recent Unified Plan offer/answer SDP that was
  18670. * converted to Plan B, with the SDP type ('offer' or 'answer') as keys and
  18671. * the SDP string as values.
  18672. *
  18673. * @type {{}}
  18674. */
  18675. this.cache = {};
  18676. }
  18677. module.exports = Interop;
  18678. /**
  18679. * Returns the index of the first m-line with the given media type and with a
  18680. * direction which allows sending, in the last Unified Plan description with
  18681. * type "answer" converted to Plan B. Returns {null} if there is no saved
  18682. * answer, or if none of its m-lines with the given type allow sending.
  18683. * @param type the media type ("audio" or "video").
  18684. * @returns {*}
  18685. */
  18686. Interop.prototype.getFirstSendingIndexFromAnswer = function(type) {
  18687. if (!this.cache.answer) {
  18688. return null;
  18689. }
  18690. var session = transform.parse(this.cache.answer);
  18691. if (session && session.media && Array.isArray(session.media)){
  18692. for (var i = 0; i < session.media.length; i++) {
  18693. if (session.media[i].type == type &&
  18694. (!session.media[i].direction /* default to sendrecv */ ||
  18695. session.media[i].direction === 'sendrecv' ||
  18696. session.media[i].direction === 'sendonly')){
  18697. return i;
  18698. }
  18699. }
  18700. }
  18701. return null;
  18702. };
  18703. /**
  18704. * This method transforms a Unified Plan SDP to an equivalent Plan B SDP. A
  18705. * PeerConnection wrapper transforms the SDP to Plan B before passing it to the
  18706. * application.
  18707. *
  18708. * @param desc
  18709. * @returns {*}
  18710. */
  18711. Interop.prototype.toPlanB = function(desc) {
  18712. var self = this;
  18713. //#region Preliminary input validation.
  18714. if (typeof desc !== 'object' || desc === null ||
  18715. typeof desc.sdp !== 'string') {
  18716. console.warn('An empty description was passed as an argument.');
  18717. return desc;
  18718. }
  18719. // Objectify the SDP for easier manipulation.
  18720. var session = transform.parse(desc.sdp);
  18721. // If the SDP contains no media, there's nothing to transform.
  18722. if (typeof session.media === 'undefined' ||
  18723. !Array.isArray(session.media) || session.media.length === 0) {
  18724. console.warn('The description has no media.');
  18725. return desc;
  18726. }
  18727. // Try some heuristics to "make sure" this is a Unified Plan SDP. Plan B
  18728. // SDP has a video, an audio and a data "channel" at most.
  18729. if (session.media.length <= 3 && session.media.every(function(m) {
  18730. return ['video', 'audio', 'data'].indexOf(m.mid) !== -1;
  18731. })) {
  18732. console.warn('This description does not look like Unified Plan.');
  18733. return desc;
  18734. }
  18735. //#endregion
  18736. // HACK https://bugzilla.mozilla.org/show_bug.cgi?id=1113443
  18737. var sdp = desc.sdp;
  18738. var rewrite = false;
  18739. for (var i = 0; i < session.media.length; i++) {
  18740. var uLine = session.media[i];
  18741. uLine.rtp.forEach(function(rtp) {
  18742. if (rtp.codec === 'NULL')
  18743. {
  18744. rewrite = true;
  18745. var offer = transform.parse(self.cache['offer']);
  18746. rtp.codec = offer.media[i].rtp[0].codec;
  18747. }
  18748. });
  18749. };
  18750. if (rewrite) {
  18751. sdp = transform.write(session);
  18752. }
  18753. // Unified Plan SDP is our "precious". Cache it for later use in the Plan B
  18754. // -> Unified Plan transformation.
  18755. this.cache[desc.type] = sdp;
  18756. //#region Convert from Unified Plan to Plan B.
  18757. // We rebuild the session.media array.
  18758. var media = session.media;
  18759. session.media = [];
  18760. // Associative array that maps channel types to channel objects for fast
  18761. // access to channel objects by their type, e.g. type2bl['audio']->channel
  18762. // obj.
  18763. var type2bl = {};
  18764. // Used to build the group:BUNDLE value after the channels construction
  18765. // loop.
  18766. var types = [];
  18767. // Implode the Unified Plan m-lines/tracks into Plan B channels.
  18768. media.forEach(function(uLine) {
  18769. // rtcp-mux is required in the Plan B SDP.
  18770. if ((typeof uLine.rtcpMux !== 'string' ||
  18771. uLine.rtcpMux !== 'rtcp-mux') &&
  18772. uLine.direction !== 'inactive') {
  18773. throw new Error('Cannot convert to Plan B because m-lines ' +
  18774. 'without the rtcp-mux attribute were found.');
  18775. }
  18776. if (uLine.type === 'application') {
  18777. session.media.push(uLine);
  18778. types.push(uLine.mid);
  18779. return;
  18780. }
  18781. // If we don't have a channel for this uLine.type, then use this
  18782. // uLine as the channel basis.
  18783. if (typeof type2bl[uLine.type] === 'undefined') {
  18784. type2bl[uLine.type] = uLine;
  18785. }
  18786. // Add sources to the channel and handle a=msid.
  18787. if (typeof uLine.sources === 'object') {
  18788. Object.keys(uLine.sources).forEach(function(ssrc) {
  18789. if (typeof type2bl[uLine.type].sources !== 'object')
  18790. type2bl[uLine.type].sources = {};
  18791. // Assign the sources to the channel.
  18792. type2bl[uLine.type].sources[ssrc] =
  18793. uLine.sources[ssrc];
  18794. if (typeof uLine.msid !== 'undefined') {
  18795. // In Plan B the msid is an SSRC attribute. Also, we don't
  18796. // care about the obsolete label and mslabel attributes.
  18797. //
  18798. // Note that it is not guaranteed that the uLine will
  18799. // have an msid. recvonly channels in particular don't have
  18800. // one.
  18801. type2bl[uLine.type].sources[ssrc].msid =
  18802. uLine.msid;
  18803. }
  18804. // NOTE ssrcs in ssrc groups will share msids, as
  18805. // draft-uberti-rtcweb-plan-00 mandates.
  18806. });
  18807. }
  18808. // Add ssrc groups to the channel.
  18809. if (typeof uLine.ssrcGroups !== 'undefined' &&
  18810. Array.isArray(uLine.ssrcGroups)) {
  18811. // Create the ssrcGroups array, if it's not defined.
  18812. if (typeof type2bl[uLine.type].ssrcGroups === 'undefined' ||
  18813. !Array.isArray(type2bl[uLine.type].ssrcGroups)) {
  18814. type2bl[uLine.type].ssrcGroups = [];
  18815. }
  18816. type2bl[uLine.type].ssrcGroups =
  18817. type2bl[uLine.type].ssrcGroups.concat(
  18818. uLine.ssrcGroups);
  18819. }
  18820. if (type2bl[uLine.type] === uLine) {
  18821. // Copy ICE related stuff from the principal media line.
  18822. uLine.candidates = media[0].candidates;
  18823. uLine.iceUfrag = media[0].iceUfrag;
  18824. uLine.icePwd = media[0].icePwd;
  18825. uLine.fingerprint = media[0].fingerprint;
  18826. // Plan B mids are in ['audio', 'video', 'data']
  18827. uLine.mid = uLine.type;
  18828. // Plan B doesn't support/need the bundle-only attribute.
  18829. delete uLine.bundleOnly;
  18830. // In Plan B the msid is an SSRC attribute.
  18831. delete uLine.msid;
  18832. // Used to build the group:BUNDLE value after this loop.
  18833. types.push(uLine.type);
  18834. // Add the channel to the new media array.
  18835. session.media.push(uLine);
  18836. }
  18837. });
  18838. // We regenerate the BUNDLE group with the new mids.
  18839. session.groups.some(function(group) {
  18840. if (group.type === 'BUNDLE') {
  18841. group.mids = types.join(' ');
  18842. return true;
  18843. }
  18844. });
  18845. // msid semantic
  18846. session.msidSemantic = {
  18847. semantic: 'WMS',
  18848. token: '*'
  18849. };
  18850. var resStr = transform.write(session);
  18851. return new RTCSessionDescription({
  18852. type: desc.type,
  18853. sdp: resStr
  18854. });
  18855. //#endregion
  18856. };
  18857. /**
  18858. * This method transforms a Plan B SDP to an equivalent Unified Plan SDP. A
  18859. * PeerConnection wrapper transforms the SDP to Unified Plan before passing it
  18860. * to FF.
  18861. *
  18862. * @param desc
  18863. * @returns {*}
  18864. */
  18865. Interop.prototype.toUnifiedPlan = function(desc) {
  18866. var self = this;
  18867. //#region Preliminary input validation.
  18868. if (typeof desc !== 'object' || desc === null ||
  18869. typeof desc.sdp !== 'string') {
  18870. console.warn('An empty description was passed as an argument.');
  18871. return desc;
  18872. }
  18873. var session = transform.parse(desc.sdp);
  18874. // If the SDP contains no media, there's nothing to transform.
  18875. if (typeof session.media === 'undefined' ||
  18876. !Array.isArray(session.media) || session.media.length === 0) {
  18877. console.warn('The description has no media.');
  18878. return desc;
  18879. }
  18880. // Try some heuristics to "make sure" this is a Plan B SDP. Plan B SDP has
  18881. // a video, an audio and a data "channel" at most.
  18882. if (session.media.length > 3 || !session.media.every(function(m) {
  18883. return ['video', 'audio', 'data'].indexOf(m.mid) !== -1;
  18884. })) {
  18885. console.warn('This description does not look like Plan B.');
  18886. return desc;
  18887. }
  18888. // Make sure this Plan B SDP can be converted to a Unified Plan SDP.
  18889. var mids = [];
  18890. session.media.forEach(function(m) {
  18891. mids.push(m.mid);
  18892. });
  18893. var hasBundle = false;
  18894. if (typeof session.groups !== 'undefined' &&
  18895. Array.isArray(session.groups)) {
  18896. hasBundle = session.groups.every(function(g) {
  18897. return g.type !== 'BUNDLE' ||
  18898. arrayEquals.apply(g.mids.sort(), [mids.sort()]);
  18899. });
  18900. }
  18901. if (!hasBundle) {
  18902. throw new Error("Cannot convert to Unified Plan because m-lines that" +
  18903. " are not bundled were found.");
  18904. }
  18905. //#endregion
  18906. //#region Convert from Plan B to Unified Plan.
  18907. // Unfortunately, a Plan B offer/answer doesn't have enough information to
  18908. // rebuild an equivalent Unified Plan offer/answer.
  18909. //
  18910. // For example, if this is a local answer (in Unified Plan style) that we
  18911. // convert to Plan B prior to handing it over to the application (the
  18912. // PeerConnection wrapper called us, for instance, after a successful
  18913. // createAnswer), we want to remember the m-line at which we've seen the
  18914. // (local) SSRC. That's because when the application wants to do call the
  18915. // SLD method, forcing us to do the inverse transformation (from Plan B to
  18916. // Unified Plan), we need to know to which m-line to assign the (local)
  18917. // SSRC. We also need to know all the other m-lines that the original
  18918. // answer had and include them in the transformed answer as well.
  18919. //
  18920. // Another example is if this is a remote offer that we convert to Plan B
  18921. // prior to giving it to the application, we want to remember the mid at
  18922. // which we've seen the (remote) SSRC.
  18923. //
  18924. // In the iteration that follows, we use the cached Unified Plan (if it
  18925. // exists) to assign mids to ssrcs.
  18926. var cached;
  18927. if (typeof this.cache[desc.type] !== 'undefined') {
  18928. cached = transform.parse(this.cache[desc.type]);
  18929. }
  18930. var recvonlySsrcs = {
  18931. audio: {},
  18932. video: {}
  18933. };
  18934. // A helper map that sends mids to m-line objects. We use it later to
  18935. // rebuild the Unified Plan style session.media array.
  18936. var mid2ul = {};
  18937. session.media.forEach(function(bLine) {
  18938. if ((typeof bLine.rtcpMux !== 'string' ||
  18939. bLine.rtcpMux !== 'rtcp-mux') &&
  18940. bLine.direction !== 'inactive') {
  18941. throw new Error("Cannot convert to Unified Plan because m-lines " +
  18942. "without the rtcp-mux attribute were found.");
  18943. }
  18944. if (bLine.type === 'application') {
  18945. mid2ul[bLine.mid] = bLine;
  18946. return;
  18947. }
  18948. // With rtcp-mux and bundle all the channels should have the same ICE
  18949. // stuff.
  18950. var sources = bLine.sources;
  18951. var ssrcGroups = bLine.ssrcGroups;
  18952. var candidates = bLine.candidates;
  18953. var iceUfrag = bLine.iceUfrag;
  18954. var icePwd = bLine.icePwd;
  18955. var fingerprint = bLine.fingerprint;
  18956. var port = bLine.port;
  18957. // We'll use the "bLine" object as a prototype for each new "mLine"
  18958. // that we create, but first we need to clean it up a bit.
  18959. delete bLine.sources;
  18960. delete bLine.ssrcGroups;
  18961. delete bLine.candidates;
  18962. delete bLine.iceUfrag;
  18963. delete bLine.icePwd;
  18964. delete bLine.fingerprint;
  18965. delete bLine.port;
  18966. delete bLine.mid;
  18967. // inverted ssrc group map
  18968. var ssrc2group = {};
  18969. if (typeof ssrcGroups !== 'undefined' && Array.isArray(ssrcGroups)) {
  18970. ssrcGroups.forEach(function (ssrcGroup) {
  18971. // TODO(gp) find out how to receive simulcast with FF. For the
  18972. // time being, hide it.
  18973. if (ssrcGroup.semantics === 'SIM') {
  18974. return;
  18975. }
  18976. // XXX This might brake if an SSRC is in more than one group
  18977. // for some reason.
  18978. if (typeof ssrcGroup.ssrcs !== 'undefined' &&
  18979. Array.isArray(ssrcGroup.ssrcs)) {
  18980. ssrcGroup.ssrcs.forEach(function (ssrc) {
  18981. if (typeof ssrc2group[ssrc] === 'undefined') {
  18982. ssrc2group[ssrc] = [];
  18983. }
  18984. ssrc2group[ssrc].push(ssrcGroup);
  18985. });
  18986. }
  18987. });
  18988. }
  18989. // ssrc to m-line index.
  18990. var ssrc2ml = {};
  18991. if (typeof sources === 'object') {
  18992. // Explode the Plan B channel sources with one m-line per source.
  18993. Object.keys(sources).forEach(function(ssrc) {
  18994. // The (unified) m-line for this SSRC. We either create it from
  18995. // scratch or, if it's a grouped SSRC, we re-use a related
  18996. // mline. In other words, if the source is grouped with another
  18997. // source, put the two together in the same m-line.
  18998. var uLine;
  18999. // We assume here that we are the answerer in the O/A, so any
  19000. // offers which we translate come from the remote side, while
  19001. // answers are local. So the check below is to make that we
  19002. // handle receive-only SSRCs in a special way only if they come
  19003. // from the remote side.
  19004. if (desc.type==='offer') {
  19005. // We want to detect SSRCs which are used by a remote peer
  19006. // in an m-line with direction=recvonly (i.e. they are
  19007. // being used for RTCP only).
  19008. // This information would have gotten lost if the remote
  19009. // peer used Unified Plan and their local description was
  19010. // translated to Plan B. So we use the lack of an MSID
  19011. // attribute to deduce a "receive only" SSRC.
  19012. if (!sources[ssrc].msid) {
  19013. recvonlySsrcs[bLine.type][ssrc] = sources[ssrc];
  19014. // Receive-only SSRCs must not create new m-lines. We
  19015. // will assign them to an existing m-line later.
  19016. return;
  19017. }
  19018. }
  19019. if (typeof ssrc2group[ssrc] !== 'undefined' &&
  19020. Array.isArray(ssrc2group[ssrc])) {
  19021. ssrc2group[ssrc].some(function (ssrcGroup) {
  19022. // ssrcGroup.ssrcs *is* an Array, no need to check
  19023. // again here.
  19024. return ssrcGroup.ssrcs.some(function (related) {
  19025. if (typeof ssrc2ml[related] === 'object') {
  19026. uLine = ssrc2ml[related];
  19027. return true;
  19028. }
  19029. });
  19030. });
  19031. }
  19032. if (typeof uLine === 'object') {
  19033. // the m-line already exists. Just add the source.
  19034. uLine.sources[ssrc] = sources[ssrc];
  19035. delete sources[ssrc].msid;
  19036. } else {
  19037. // Use the "bLine" as a prototype for the "uLine".
  19038. uLine = Object.create(bLine);
  19039. ssrc2ml[ssrc] = uLine;
  19040. if (typeof sources[ssrc].msid !== 'undefined') {
  19041. // Assign the msid of the source to the m-line. Note
  19042. // that it is not guaranteed that the source will have
  19043. // msid. In particular "recvonly" sources don't have an
  19044. // msid. Note that "recvonly" is a term only defined
  19045. // for m-lines.
  19046. uLine.msid = sources[ssrc].msid;
  19047. uLine.direction = 'sendrecv';
  19048. delete sources[ssrc].msid;
  19049. }
  19050. // We assign one SSRC per media line.
  19051. uLine.sources = {};
  19052. uLine.sources[ssrc] = sources[ssrc];
  19053. uLine.ssrcGroups = ssrc2group[ssrc];
  19054. // Use the cached Unified Plan SDP (if it exists) to assign
  19055. // SSRCs to mids.
  19056. if (typeof cached !== 'undefined' &&
  19057. typeof cached.media !== 'undefined' &&
  19058. Array.isArray(cached.media)) {
  19059. cached.media.forEach(function (m) {
  19060. if (typeof m.sources === 'object') {
  19061. Object.keys(m.sources).forEach(function (s) {
  19062. if (s === ssrc) {
  19063. uLine.mid = m.mid;
  19064. }
  19065. });
  19066. }
  19067. });
  19068. }
  19069. if (typeof uLine.mid === 'undefined') {
  19070. // If this is an SSRC that we see for the first time
  19071. // assign it a new mid. This is typically the case when
  19072. // this method is called to transform a remote
  19073. // description for the first time or when there is a
  19074. // new SSRC in the remote description because a new
  19075. // peer has joined the conference. Local SSRCs should
  19076. // have already been added to the map in the toPlanB
  19077. // method.
  19078. //
  19079. // Because FF generates answers in Unified Plan style,
  19080. // we MUST already have a cached answer with all the
  19081. // local SSRCs mapped to some m-line/mid.
  19082. if (desc.type === 'answer') {
  19083. throw new Error("An unmapped SSRC was found.");
  19084. }
  19085. uLine.mid = [bLine.type, '-', ssrc].join('');
  19086. }
  19087. // Include the candidates in the 1st media line.
  19088. uLine.candidates = candidates;
  19089. uLine.iceUfrag = iceUfrag;
  19090. uLine.icePwd = icePwd;
  19091. uLine.fingerprint = fingerprint;
  19092. uLine.port = port;
  19093. mid2ul[uLine.mid] = uLine;
  19094. }
  19095. });
  19096. }
  19097. });
  19098. // Rebuild the media array in the right order and add the missing mLines
  19099. // (missing from the Plan B SDP).
  19100. session.media = [];
  19101. mids = []; // reuse
  19102. if (desc.type === 'answer') {
  19103. // The media lines in the answer must match the media lines in the
  19104. // offer. The order is important too. Here we assume that Firefox is
  19105. // the answerer, so we merely have to use the reconstructed (unified)
  19106. // answer to update the cached (unified) answer accordingly.
  19107. //
  19108. // In the general case, one would have to use the cached (unified)
  19109. // offer to find the m-lines that are missing from the reconstructed
  19110. // answer, potentially grabbing them from the cached (unified) answer.
  19111. // One has to be careful with this approach because inactive m-lines do
  19112. // not always have an mid, making it tricky (impossible?) to find where
  19113. // exactly and which m-lines are missing from the reconstructed answer.
  19114. for (var i = 0; i < cached.media.length; i++) {
  19115. var uLine = cached.media[i];
  19116. if (typeof mid2ul[uLine.mid] === 'undefined') {
  19117. // The mid isn't in the reconstructed (unified) answer.
  19118. // This is either a (unified) m-line containing a remote
  19119. // track only, or a (unified) m-line containing a remote
  19120. // track and a local track that has been removed.
  19121. // In either case, it MUST exist in the cached
  19122. // (unified) answer.
  19123. //
  19124. // In case this is a removed local track, clean-up
  19125. // the (unified) m-line and make sure it's 'recvonly' or
  19126. // 'inactive'.
  19127. delete uLine.msid;
  19128. delete uLine.sources;
  19129. delete uLine.ssrcGroups;
  19130. if (!uLine.direction
  19131. || uLine.direction === 'sendrecv')
  19132. uLine.direction = 'recvonly';
  19133. else if (uLine.direction === 'sendonly')
  19134. uLine.direction = 'inactive';
  19135. } else {
  19136. // This is an (unified) m-line/channel that contains a local
  19137. // track (sendrecv or sendonly channel) or it's a unified
  19138. // recvonly m-line/channel. In either case, since we're
  19139. // going from PlanB -> Unified Plan this m-line MUST
  19140. // exist in the cached answer.
  19141. }
  19142. session.media.push(uLine);
  19143. if (typeof uLine.mid === 'string') {
  19144. // inactive lines don't/may not have an mid.
  19145. mids.push(uLine.mid);
  19146. }
  19147. }
  19148. } else {
  19149. // SDP offer/answer (and the JSEP spec) forbids removing an m-section
  19150. // under any circumstances. If we are no longer interested in sending a
  19151. // track, we just remove the msid and ssrc attributes and set it to
  19152. // either a=recvonly (as the reofferer, we must use recvonly if the
  19153. // other side was previously sending on the m-section, but we can also
  19154. // leave the possibility open if it wasn't previously in use), or
  19155. // a=inactive.
  19156. if (typeof cached !== 'undefined' &&
  19157. typeof cached.media !== 'undefined' &&
  19158. Array.isArray(cached.media)) {
  19159. cached.media.forEach(function(uLine) {
  19160. mids.push(uLine.mid);
  19161. if (typeof mid2ul[uLine.mid] !== 'undefined') {
  19162. session.media.push(mid2ul[uLine.mid]);
  19163. } else {
  19164. delete uLine.msid;
  19165. delete uLine.sources;
  19166. delete uLine.ssrcGroups;
  19167. if (!uLine.direction
  19168. || uLine.direction === 'sendrecv')
  19169. uLine.direction = 'recvonly';
  19170. if (!uLine.direction
  19171. || uLine.direction === 'sendonly')
  19172. uLine.direction = 'inactive';
  19173. session.media.push(uLine);
  19174. }
  19175. });
  19176. }
  19177. // Add all the remaining (new) m-lines of the transformed SDP.
  19178. Object.keys(mid2ul).forEach(function(mid) {
  19179. if (mids.indexOf(mid) === -1) {
  19180. mids.push(mid);
  19181. if (mid2ul[mid].direction === 'recvonly') {
  19182. // This is a remote recvonly channel. Add its SSRC to the
  19183. // appropriate sendrecv or sendonly channel.
  19184. // TODO(gp) what if we don't have sendrecv/sendonly
  19185. // channel?
  19186. session.media.some(function (uLine) {
  19187. if ((uLine.direction === 'sendrecv' ||
  19188. uLine.direction === 'sendonly') &&
  19189. uLine.type === mid2ul[mid].type) {
  19190. // mid2ul[mid] shouldn't have any ssrc-groups
  19191. Object.keys(mid2ul[mid].sources).forEach(
  19192. function (ssrc) {
  19193. uLine.sources[ssrc] =
  19194. mid2ul[mid].sources[ssrc];
  19195. });
  19196. return true;
  19197. }
  19198. });
  19199. } else {
  19200. session.media.push(mid2ul[mid]);
  19201. }
  19202. }
  19203. });
  19204. }
  19205. // After we have constructed the Plan Unified m-lines we can figure out
  19206. // where (in which m-line) to place the 'recvonly SSRCs'.
  19207. // Note: we assume here that we are the answerer in the O/A, so any offers
  19208. // which we translate come from the remote side, while answers are local
  19209. // (and so our last local description is cached as an 'answer').
  19210. ["audio", "video"].forEach(function (type) {
  19211. if (!session || !session.media || !Array.isArray(session.media))
  19212. return;
  19213. var idx = null;
  19214. if (Object.keys(recvonlySsrcs[type]).length > 0) {
  19215. idx = self.getFirstSendingIndexFromAnswer(type);
  19216. if (idx === null){
  19217. // If this is the first offer we receive, we don't have a
  19218. // cached answer. Assume that we will be sending media using
  19219. // the first m-line for each media type.
  19220. for (var i = 0; i < session.media.length; i++) {
  19221. if (session.media[i].type === type) {
  19222. idx = i;
  19223. break;
  19224. }
  19225. }
  19226. }
  19227. }
  19228. if (idx && session.media.length > idx) {
  19229. var mLine = session.media[idx];
  19230. Object.keys(recvonlySsrcs[type]).forEach(function(ssrc) {
  19231. if (mLine.sources && mLine.sources[ssrc]) {
  19232. console.warn("Replacing an existing SSRC.");
  19233. }
  19234. if (!mLine.sources) {
  19235. mLine.sources = {};
  19236. }
  19237. mLine.sources[ssrc] = recvonlySsrcs[type][ssrc];
  19238. });
  19239. }
  19240. });
  19241. // We regenerate the BUNDLE group (since we regenerated the mids)
  19242. session.groups.some(function(group) {
  19243. if (group.type === 'BUNDLE') {
  19244. group.mids = mids.join(' ');
  19245. return true;
  19246. }
  19247. });
  19248. // msid semantic
  19249. session.msidSemantic = {
  19250. semantic: 'WMS',
  19251. token: '*'
  19252. };
  19253. var resStr = transform.write(session);
  19254. // Cache the transformed SDP (Unified Plan) for later re-use in this
  19255. // function.
  19256. this.cache[desc.type] = resStr;
  19257. return new RTCSessionDescription({
  19258. type: desc.type,
  19259. sdp: resStr
  19260. });
  19261. //#endregion
  19262. };
  19263. },{"./array-equals":65,"./transform":68}],68:[function(require,module,exports){
  19264. /* Copyright @ 2015 Atlassian Pty Ltd
  19265. *
  19266. * Licensed under the Apache License, Version 2.0 (the "License");
  19267. * you may not use this file except in compliance with the License.
  19268. * You may obtain a copy of the License at
  19269. *
  19270. * http://www.apache.org/licenses/LICENSE-2.0
  19271. *
  19272. * Unless required by applicable law or agreed to in writing, software
  19273. * distributed under the License is distributed on an "AS IS" BASIS,
  19274. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  19275. * See the License for the specific language governing permissions and
  19276. * limitations under the License.
  19277. */
  19278. var transform = require('sdp-transform');
  19279. exports.write = function(session, opts) {
  19280. if (typeof session !== 'undefined' &&
  19281. typeof session.media !== 'undefined' &&
  19282. Array.isArray(session.media)) {
  19283. session.media.forEach(function (mLine) {
  19284. // expand sources to ssrcs
  19285. if (typeof mLine.sources !== 'undefined' &&
  19286. Object.keys(mLine.sources).length !== 0) {
  19287. mLine.ssrcs = [];
  19288. Object.keys(mLine.sources).forEach(function (ssrc) {
  19289. var source = mLine.sources[ssrc];
  19290. Object.keys(source).forEach(function (attribute) {
  19291. mLine.ssrcs.push({
  19292. id: ssrc,
  19293. attribute: attribute,
  19294. value: source[attribute]
  19295. });
  19296. });
  19297. });
  19298. delete mLine.sources;
  19299. }
  19300. // join ssrcs in ssrc groups
  19301. if (typeof mLine.ssrcGroups !== 'undefined' &&
  19302. Array.isArray(mLine.ssrcGroups)) {
  19303. mLine.ssrcGroups.forEach(function (ssrcGroup) {
  19304. if (typeof ssrcGroup.ssrcs !== 'undefined' &&
  19305. Array.isArray(ssrcGroup.ssrcs)) {
  19306. ssrcGroup.ssrcs = ssrcGroup.ssrcs.join(' ');
  19307. }
  19308. });
  19309. }
  19310. });
  19311. }
  19312. // join group mids
  19313. if (typeof session !== 'undefined' &&
  19314. typeof session.groups !== 'undefined' && Array.isArray(session.groups)) {
  19315. session.groups.forEach(function (g) {
  19316. if (typeof g.mids !== 'undefined' && Array.isArray(g.mids)) {
  19317. g.mids = g.mids.join(' ');
  19318. }
  19319. });
  19320. }
  19321. return transform.write(session, opts);
  19322. };
  19323. exports.parse = function(sdp) {
  19324. var session = transform.parse(sdp);
  19325. if (typeof session !== 'undefined' && typeof session.media !== 'undefined' &&
  19326. Array.isArray(session.media)) {
  19327. session.media.forEach(function (mLine) {
  19328. // group sources attributes by ssrc
  19329. if (typeof mLine.ssrcs !== 'undefined' && Array.isArray(mLine.ssrcs)) {
  19330. mLine.sources = {};
  19331. mLine.ssrcs.forEach(function (ssrc) {
  19332. if (!mLine.sources[ssrc.id])
  19333. mLine.sources[ssrc.id] = {};
  19334. mLine.sources[ssrc.id][ssrc.attribute] = ssrc.value;
  19335. });
  19336. delete mLine.ssrcs;
  19337. }
  19338. // split ssrcs in ssrc groups
  19339. if (typeof mLine.ssrcGroups !== 'undefined' &&
  19340. Array.isArray(mLine.ssrcGroups)) {
  19341. mLine.ssrcGroups.forEach(function (ssrcGroup) {
  19342. if (typeof ssrcGroup.ssrcs === 'string') {
  19343. ssrcGroup.ssrcs = ssrcGroup.ssrcs.split(' ');
  19344. }
  19345. });
  19346. }
  19347. });
  19348. }
  19349. // split group mids
  19350. if (typeof session !== 'undefined' &&
  19351. typeof session.groups !== 'undefined' && Array.isArray(session.groups)) {
  19352. session.groups.forEach(function (g) {
  19353. if (typeof g.mids === 'string') {
  19354. g.mids = g.mids.split(' ');
  19355. }
  19356. });
  19357. }
  19358. return session;
  19359. };
  19360. },{"sdp-transform":70}],69:[function(require,module,exports){
  19361. var grammar = module.exports = {
  19362. v: [{
  19363. name: 'version',
  19364. reg: /^(\d*)$/
  19365. }],
  19366. o: [{ //o=- 20518 0 IN IP4 203.0.113.1
  19367. // NB: sessionId will be a String in most cases because it is huge
  19368. name: 'origin',
  19369. reg: /^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/,
  19370. names: ['username', 'sessionId', 'sessionVersion', 'netType', 'ipVer', 'address'],
  19371. format: "%s %s %d %s IP%d %s"
  19372. }],
  19373. // default parsing of these only (though some of these feel outdated)
  19374. s: [{ name: 'name' }],
  19375. i: [{ name: 'description' }],
  19376. u: [{ name: 'uri' }],
  19377. e: [{ name: 'email' }],
  19378. p: [{ name: 'phone' }],
  19379. z: [{ name: 'timezones' }], // TODO: this one can actually be parsed properly..
  19380. r: [{ name: 'repeats' }], // TODO: this one can also be parsed properly
  19381. //k: [{}], // outdated thing ignored
  19382. t: [{ //t=0 0
  19383. name: 'timing',
  19384. reg: /^(\d*) (\d*)/,
  19385. names: ['start', 'stop'],
  19386. format: "%d %d"
  19387. }],
  19388. c: [{ //c=IN IP4 10.47.197.26
  19389. name: 'connection',
  19390. reg: /^IN IP(\d) (\S*)/,
  19391. names: ['version', 'ip'],
  19392. format: "IN IP%d %s"
  19393. }],
  19394. b: [{ //b=AS:4000
  19395. push: 'bandwidth',
  19396. reg: /^(TIAS|AS|CT|RR|RS):(\d*)/,
  19397. names: ['type', 'limit'],
  19398. format: "%s:%s"
  19399. }],
  19400. m: [{ //m=video 51744 RTP/AVP 126 97 98 34 31
  19401. // NB: special - pushes to session
  19402. // TODO: rtp/fmtp should be filtered by the payloads found here?
  19403. reg: /^(\w*) (\d*) ([\w\/]*)(?: (.*))?/,
  19404. names: ['type', 'port', 'protocol', 'payloads'],
  19405. format: "%s %d %s %s"
  19406. }],
  19407. a: [
  19408. { //a=rtpmap:110 opus/48000/2
  19409. push: 'rtp',
  19410. reg: /^rtpmap:(\d*) ([\w\-]*)(?:\s*\/(\d*)(?:\s*\/(\S*))?)?/,
  19411. names: ['payload', 'codec', 'rate', 'encoding'],
  19412. format: function (o) {
  19413. return (o.encoding) ?
  19414. "rtpmap:%d %s/%s/%s":
  19415. o.rate ?
  19416. "rtpmap:%d %s/%s":
  19417. "rtpmap:%d %s";
  19418. }
  19419. },
  19420. {
  19421. //a=fmtp:108 profile-level-id=24;object=23;bitrate=64000
  19422. //a=fmtp:111 minptime=10; useinbandfec=1
  19423. push: 'fmtp',
  19424. reg: /^fmtp:(\d*) ([\S| ]*)/,
  19425. names: ['payload', 'config'],
  19426. format: "fmtp:%d %s"
  19427. },
  19428. { //a=control:streamid=0
  19429. name: 'control',
  19430. reg: /^control:(.*)/,
  19431. format: "control:%s"
  19432. },
  19433. { //a=rtcp:65179 IN IP4 193.84.77.194
  19434. name: 'rtcp',
  19435. reg: /^rtcp:(\d*)(?: (\S*) IP(\d) (\S*))?/,
  19436. names: ['port', 'netType', 'ipVer', 'address'],
  19437. format: function (o) {
  19438. return (o.address != null) ?
  19439. "rtcp:%d %s IP%d %s":
  19440. "rtcp:%d";
  19441. }
  19442. },
  19443. { //a=rtcp-fb:98 trr-int 100
  19444. push: 'rtcpFbTrrInt',
  19445. reg: /^rtcp-fb:(\*|\d*) trr-int (\d*)/,
  19446. names: ['payload', 'value'],
  19447. format: "rtcp-fb:%d trr-int %d"
  19448. },
  19449. { //a=rtcp-fb:98 nack rpsi
  19450. push: 'rtcpFb',
  19451. reg: /^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,
  19452. names: ['payload', 'type', 'subtype'],
  19453. format: function (o) {
  19454. return (o.subtype != null) ?
  19455. "rtcp-fb:%s %s %s":
  19456. "rtcp-fb:%s %s";
  19457. }
  19458. },
  19459. { //a=extmap:2 urn:ietf:params:rtp-hdrext:toffset
  19460. //a=extmap:1/recvonly URI-gps-string
  19461. push: 'ext',
  19462. reg: /^extmap:([\w_\/]*) (\S*)(?: (\S*))?/,
  19463. names: ['value', 'uri', 'config'], // value may include "/direction" suffix
  19464. format: function (o) {
  19465. return (o.config != null) ?
  19466. "extmap:%s %s %s":
  19467. "extmap:%s %s";
  19468. }
  19469. },
  19470. {
  19471. //a=crypto:1 AES_CM_128_HMAC_SHA1_80 inline:PS1uQCVeeCFCanVmcjkpPywjNWhcYD0mXXtxaVBR|2^20|1:32
  19472. push: 'crypto',
  19473. reg: /^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,
  19474. names: ['id', 'suite', 'config', 'sessionConfig'],
  19475. format: function (o) {
  19476. return (o.sessionConfig != null) ?
  19477. "crypto:%d %s %s %s":
  19478. "crypto:%d %s %s";
  19479. }
  19480. },
  19481. { //a=setup:actpass
  19482. name: 'setup',
  19483. reg: /^setup:(\w*)/,
  19484. format: "setup:%s"
  19485. },
  19486. { //a=mid:1
  19487. name: 'mid',
  19488. reg: /^mid:([^\s]*)/,
  19489. format: "mid:%s"
  19490. },
  19491. { //a=msid:0c8b064d-d807-43b4-b434-f92a889d8587 98178685-d409-46e0-8e16-7ef0db0db64a
  19492. name: 'msid',
  19493. reg: /^msid:(.*)/,
  19494. format: "msid:%s"
  19495. },
  19496. { //a=ptime:20
  19497. name: 'ptime',
  19498. reg: /^ptime:(\d*)/,
  19499. format: "ptime:%d"
  19500. },
  19501. { //a=maxptime:60
  19502. name: 'maxptime',
  19503. reg: /^maxptime:(\d*)/,
  19504. format: "maxptime:%d"
  19505. },
  19506. { //a=sendrecv
  19507. name: 'direction',
  19508. reg: /^(sendrecv|recvonly|sendonly|inactive)/
  19509. },
  19510. { //a=ice-lite
  19511. name: 'icelite',
  19512. reg: /^(ice-lite)/
  19513. },
  19514. { //a=ice-ufrag:F7gI
  19515. name: 'iceUfrag',
  19516. reg: /^ice-ufrag:(\S*)/,
  19517. format: "ice-ufrag:%s"
  19518. },
  19519. { //a=ice-pwd:x9cml/YzichV2+XlhiMu8g
  19520. name: 'icePwd',
  19521. reg: /^ice-pwd:(\S*)/,
  19522. format: "ice-pwd:%s"
  19523. },
  19524. { //a=fingerprint:SHA-1 00:11:22:33:44:55:66:77:88:99:AA:BB:CC:DD:EE:FF:00:11:22:33
  19525. name: 'fingerprint',
  19526. reg: /^fingerprint:(\S*) (\S*)/,
  19527. names: ['type', 'hash'],
  19528. format: "fingerprint:%s %s"
  19529. },
  19530. {
  19531. //a=candidate:0 1 UDP 2113667327 203.0.113.1 54400 typ host
  19532. //a=candidate:1162875081 1 udp 2113937151 192.168.34.75 60017 typ host generation 0
  19533. //a=candidate:3289912957 2 udp 1845501695 193.84.77.194 60017 typ srflx raddr 192.168.34.75 rport 60017 generation 0
  19534. //a=candidate:229815620 1 tcp 1518280447 192.168.150.19 60017 typ host tcptype active generation 0
  19535. //a=candidate:3289912957 2 tcp 1845501695 193.84.77.194 60017 typ srflx raddr 192.168.34.75 rport 60017 tcptype passive generation 0
  19536. push:'candidates',
  19537. reg: /^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: tcptype (\S*))?(?: generation (\d*))?/,
  19538. names: ['foundation', 'component', 'transport', 'priority', 'ip', 'port', 'type', 'raddr', 'rport', 'tcptype', 'generation'],
  19539. format: function (o) {
  19540. var str = "candidate:%s %d %s %d %s %d typ %s";
  19541. str += (o.raddr != null) ? " raddr %s rport %d" : "%v%v";
  19542. // NB: candidate has three optional chunks, so %void middles one if it's missing
  19543. str += (o.tcptype != null) ? " tcptype %s" : "%v";
  19544. if (o.generation != null) {
  19545. str += " generation %d";
  19546. }
  19547. return str;
  19548. }
  19549. },
  19550. { //a=end-of-candidates (keep after the candidates line for readability)
  19551. name: 'endOfCandidates',
  19552. reg: /^(end-of-candidates)/
  19553. },
  19554. { //a=remote-candidates:1 203.0.113.1 54400 2 203.0.113.1 54401 ...
  19555. name: 'remoteCandidates',
  19556. reg: /^remote-candidates:(.*)/,
  19557. format: "remote-candidates:%s"
  19558. },
  19559. { //a=ice-options:google-ice
  19560. name: 'iceOptions',
  19561. reg: /^ice-options:(\S*)/,
  19562. format: "ice-options:%s"
  19563. },
  19564. { //a=ssrc:2566107569 cname:t9YU8M1UxTF8Y1A1
  19565. push: "ssrcs",
  19566. reg: /^ssrc:(\d*) ([\w_]*):(.*)/,
  19567. names: ['id', 'attribute', 'value'],
  19568. format: "ssrc:%d %s:%s"
  19569. },
  19570. { //a=ssrc-group:FEC 1 2
  19571. push: "ssrcGroups",
  19572. reg: /^ssrc-group:(\w*) (.*)/,
  19573. names: ['semantics', 'ssrcs'],
  19574. format: "ssrc-group:%s %s"
  19575. },
  19576. { //a=msid-semantic: WMS Jvlam5X3SX1OP6pn20zWogvaKJz5Hjf9OnlV
  19577. name: "msidSemantic",
  19578. reg: /^msid-semantic:\s?(\w*) (\S*)/,
  19579. names: ['semantic', 'token'],
  19580. format: "msid-semantic: %s %s" // space after ":" is not accidental
  19581. },
  19582. { //a=group:BUNDLE audio video
  19583. push: 'groups',
  19584. reg: /^group:(\w*) (.*)/,
  19585. names: ['type', 'mids'],
  19586. format: "group:%s %s"
  19587. },
  19588. { //a=rtcp-mux
  19589. name: 'rtcpMux',
  19590. reg: /^(rtcp-mux)/
  19591. },
  19592. { //a=rtcp-rsize
  19593. name: 'rtcpRsize',
  19594. reg: /^(rtcp-rsize)/
  19595. },
  19596. { // any a= that we don't understand is kepts verbatim on media.invalid
  19597. push: 'invalid',
  19598. names: ["value"]
  19599. }
  19600. ]
  19601. };
  19602. // set sensible defaults to avoid polluting the grammar with boring details
  19603. Object.keys(grammar).forEach(function (key) {
  19604. var objs = grammar[key];
  19605. objs.forEach(function (obj) {
  19606. if (!obj.reg) {
  19607. obj.reg = /(.*)/;
  19608. }
  19609. if (!obj.format) {
  19610. obj.format = "%s";
  19611. }
  19612. });
  19613. });
  19614. },{}],70:[function(require,module,exports){
  19615. var parser = require('./parser');
  19616. var writer = require('./writer');
  19617. exports.write = writer;
  19618. exports.parse = parser.parse;
  19619. exports.parseFmtpConfig = parser.parseFmtpConfig;
  19620. exports.parsePayloads = parser.parsePayloads;
  19621. exports.parseRemoteCandidates = parser.parseRemoteCandidates;
  19622. },{"./parser":71,"./writer":72}],71:[function(require,module,exports){
  19623. var toIntIfInt = function (v) {
  19624. return String(Number(v)) === v ? Number(v) : v;
  19625. };
  19626. var attachProperties = function (match, location, names, rawName) {
  19627. if (rawName && !names) {
  19628. location[rawName] = toIntIfInt(match[1]);
  19629. }
  19630. else {
  19631. for (var i = 0; i < names.length; i += 1) {
  19632. if (match[i+1] != null) {
  19633. location[names[i]] = toIntIfInt(match[i+1]);
  19634. }
  19635. }
  19636. }
  19637. };
  19638. var parseReg = function (obj, location, content) {
  19639. var needsBlank = obj.name && obj.names;
  19640. if (obj.push && !location[obj.push]) {
  19641. location[obj.push] = [];
  19642. }
  19643. else if (needsBlank && !location[obj.name]) {
  19644. location[obj.name] = {};
  19645. }
  19646. var keyLocation = obj.push ?
  19647. {} : // blank object that will be pushed
  19648. needsBlank ? location[obj.name] : location; // otherwise, named location or root
  19649. attachProperties(content.match(obj.reg), keyLocation, obj.names, obj.name);
  19650. if (obj.push) {
  19651. location[obj.push].push(keyLocation);
  19652. }
  19653. };
  19654. var grammar = require('./grammar');
  19655. var validLine = RegExp.prototype.test.bind(/^([a-z])=(.*)/);
  19656. exports.parse = function (sdp) {
  19657. var session = {}
  19658. , media = []
  19659. , location = session; // points at where properties go under (one of the above)
  19660. // parse lines we understand
  19661. sdp.split(/(\r\n|\r|\n)/).filter(validLine).forEach(function (l) {
  19662. var type = l[0];
  19663. var content = l.slice(2);
  19664. if (type === 'm') {
  19665. media.push({rtp: [], fmtp: []});
  19666. location = media[media.length-1]; // point at latest media line
  19667. }
  19668. for (var j = 0; j < (grammar[type] || []).length; j += 1) {
  19669. var obj = grammar[type][j];
  19670. if (obj.reg.test(content)) {
  19671. return parseReg(obj, location, content);
  19672. }
  19673. }
  19674. });
  19675. session.media = media; // link it up
  19676. return session;
  19677. };
  19678. var fmtpReducer = function (acc, expr) {
  19679. var s = expr.split('=');
  19680. if (s.length === 2) {
  19681. acc[s[0]] = toIntIfInt(s[1]);
  19682. }
  19683. return acc;
  19684. };
  19685. exports.parseFmtpConfig = function (str) {
  19686. return str.split(/\;\s?/).reduce(fmtpReducer, {});
  19687. };
  19688. exports.parsePayloads = function (str) {
  19689. return str.split(' ').map(Number);
  19690. };
  19691. exports.parseRemoteCandidates = function (str) {
  19692. var candidates = [];
  19693. var parts = str.split(' ').map(toIntIfInt);
  19694. for (var i = 0; i < parts.length; i += 3) {
  19695. candidates.push({
  19696. component: parts[i],
  19697. ip: parts[i + 1],
  19698. port: parts[i + 2]
  19699. });
  19700. }
  19701. return candidates;
  19702. };
  19703. },{"./grammar":69}],72:[function(require,module,exports){
  19704. var grammar = require('./grammar');
  19705. // customized util.format - discards excess arguments and can void middle ones
  19706. var formatRegExp = /%[sdv%]/g;
  19707. var format = function (formatStr) {
  19708. var i = 1;
  19709. var args = arguments;
  19710. var len = args.length;
  19711. return formatStr.replace(formatRegExp, function (x) {
  19712. if (i >= len) {
  19713. return x; // missing argument
  19714. }
  19715. var arg = args[i];
  19716. i += 1;
  19717. switch (x) {
  19718. case '%%':
  19719. return '%';
  19720. case '%s':
  19721. return String(arg);
  19722. case '%d':
  19723. return Number(arg);
  19724. case '%v':
  19725. return '';
  19726. }
  19727. });
  19728. // NB: we discard excess arguments - they are typically undefined from makeLine
  19729. };
  19730. var makeLine = function (type, obj, location) {
  19731. var str = obj.format instanceof Function ?
  19732. (obj.format(obj.push ? location : location[obj.name])) :
  19733. obj.format;
  19734. var args = [type + '=' + str];
  19735. if (obj.names) {
  19736. for (var i = 0; i < obj.names.length; i += 1) {
  19737. var n = obj.names[i];
  19738. if (obj.name) {
  19739. args.push(location[obj.name][n]);
  19740. }
  19741. else { // for mLine and push attributes
  19742. args.push(location[obj.names[i]]);
  19743. }
  19744. }
  19745. }
  19746. else {
  19747. args.push(location[obj.name]);
  19748. }
  19749. return format.apply(null, args);
  19750. };
  19751. // RFC specified order
  19752. // TODO: extend this with all the rest
  19753. var defaultOuterOrder = [
  19754. 'v', 'o', 's', 'i',
  19755. 'u', 'e', 'p', 'c',
  19756. 'b', 't', 'r', 'z', 'a'
  19757. ];
  19758. var defaultInnerOrder = ['i', 'c', 'b', 'a'];
  19759. module.exports = function (session, opts) {
  19760. opts = opts || {};
  19761. // ensure certain properties exist
  19762. if (session.version == null) {
  19763. session.version = 0; // "v=0" must be there (only defined version atm)
  19764. }
  19765. if (session.name == null) {
  19766. session.name = " "; // "s= " must be there if no meaningful name set
  19767. }
  19768. session.media.forEach(function (mLine) {
  19769. if (mLine.payloads == null) {
  19770. mLine.payloads = "";
  19771. }
  19772. });
  19773. var outerOrder = opts.outerOrder || defaultOuterOrder;
  19774. var innerOrder = opts.innerOrder || defaultInnerOrder;
  19775. var sdp = [];
  19776. // loop through outerOrder for matching properties on session
  19777. outerOrder.forEach(function (type) {
  19778. grammar[type].forEach(function (obj) {
  19779. if (obj.name in session && session[obj.name] != null) {
  19780. sdp.push(makeLine(type, obj, session));
  19781. }
  19782. else if (obj.push in session && session[obj.push] != null) {
  19783. session[obj.push].forEach(function (el) {
  19784. sdp.push(makeLine(type, obj, el));
  19785. });
  19786. }
  19787. });
  19788. });
  19789. // then for each media line, follow the innerOrder
  19790. session.media.forEach(function (mLine) {
  19791. sdp.push(makeLine('m', grammar.m[0], mLine));
  19792. innerOrder.forEach(function (type) {
  19793. grammar[type].forEach(function (obj) {
  19794. if (obj.name in mLine && mLine[obj.name] != null) {
  19795. sdp.push(makeLine(type, obj, mLine));
  19796. }
  19797. else if (obj.push in mLine && mLine[obj.push] != null) {
  19798. mLine[obj.push].forEach(function (el) {
  19799. sdp.push(makeLine(type, obj, el));
  19800. });
  19801. }
  19802. });
  19803. });
  19804. });
  19805. return sdp.join('\r\n') + '\r\n';
  19806. };
  19807. },{"./grammar":69}],73:[function(require,module,exports){
  19808. /* Copyright @ 2015 Atlassian Pty Ltd
  19809. *
  19810. * Licensed under the Apache License, Version 2.0 (the "License");
  19811. * you may not use this file except in compliance with the License.
  19812. * You may obtain a copy of the License at
  19813. *
  19814. * http://www.apache.org/licenses/LICENSE-2.0
  19815. *
  19816. * Unless required by applicable law or agreed to in writing, software
  19817. * distributed under the License is distributed on an "AS IS" BASIS,
  19818. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  19819. * See the License for the specific language governing permissions and
  19820. * limitations under the License.
  19821. */
  19822. var transform = require('sdp-transform');
  19823. var transformUtils = require('./transform-utils');
  19824. var parseSsrcs = transformUtils.parseSsrcs;
  19825. var writeSsrcs = transformUtils.writeSsrcs;
  19826. //region Constants
  19827. var DEFAULT_NUM_OF_LAYERS = 3;
  19828. //endregion
  19829. //region Ctor
  19830. function Simulcast(options) {
  19831. this.options = options ? options : {};
  19832. if (!this.options.numOfLayers) {
  19833. this.options.numOfLayers = DEFAULT_NUM_OF_LAYERS;
  19834. }
  19835. this.layers = [];
  19836. }
  19837. //endregion
  19838. //region Stateless private utility functions
  19839. /**
  19840. * Returns a random integer between min (included) and max (excluded)
  19841. * Using Math.round() gives a non-uniform distribution!
  19842. * @returns {number}
  19843. */
  19844. function generateSSRC() {
  19845. var min = 0, max = 0xffffffff;
  19846. return Math.floor(Math.random() * (max - min)) + min;
  19847. };
  19848. function processVideo(session, action) {
  19849. if (session == null || !Array.isArray(session.media)) {
  19850. return;
  19851. }
  19852. session.media.forEach(function (mLine) {
  19853. if (mLine.type === 'video') {
  19854. action(mLine);
  19855. }
  19856. });
  19857. }
  19858. function validateDescription(desc)
  19859. {
  19860. return desc && desc != null
  19861. && desc.type && desc.type != ''
  19862. && desc.sdp && desc.sdp != '';
  19863. }
  19864. function explodeRemoteSimulcast(mLine) {
  19865. if (!mLine || !Array.isArray(mLine.ssrcGroups)) {
  19866. return;
  19867. }
  19868. var sources = parseSsrcs(mLine);
  19869. var order = [];
  19870. // Find the SIM group and explode its sources.
  19871. var j = mLine.ssrcGroups.length;
  19872. while (j--) {
  19873. if (mLine.ssrcGroups[j].semantics !== 'SIM') {
  19874. continue;
  19875. }
  19876. var simulcastSsrcs = mLine.ssrcGroups[j].ssrcs.split(' ');
  19877. for (var i = 0; i < simulcastSsrcs.length; i++) {
  19878. var ssrc = simulcastSsrcs[i];
  19879. order.push(ssrc);
  19880. var parts = sources[ssrc].msid.split(' ');
  19881. sources[ssrc].msid = [parts[0], '/', i, ' ', parts[1], '/', i].join('');
  19882. sources[ssrc].cname = [sources[ssrc].cname, '/', i].join('');
  19883. // Remove all the groups that this SSRC participates in.
  19884. mLine.ssrcGroups.forEach(function (relatedGroup) {
  19885. if (relatedGroup.semantics === 'SIM') {
  19886. return;
  19887. }
  19888. var relatedSsrcs = relatedGroup.ssrcs.split(' ');
  19889. if (relatedSsrcs.indexOf(ssrc) === -1) {
  19890. return;
  19891. }
  19892. // Nuke all the related SSRCs.
  19893. relatedSsrcs.forEach(function (relatedSSRC) {
  19894. sources[relatedSSRC].msid = sources[ssrc].msid;
  19895. sources[relatedSSRC].cname = sources[ssrc].cname;
  19896. if (relatedSSRC !== ssrc) {
  19897. order.push(relatedSSRC);
  19898. }
  19899. });
  19900. // Schedule the related group for nuking.
  19901. })
  19902. }
  19903. mLine.ssrcs = writeSsrcs(sources, order);
  19904. mLine.ssrcGroups.splice(j, 1);
  19905. };
  19906. }
  19907. function implodeRemoteSimulcast(mLine) {
  19908. if (!mLine || !Array.isArray(mLine.ssrcGroups)) {
  19909. console.debug('Halt: There are no SSRC groups in the remote ' +
  19910. 'description.');
  19911. return;
  19912. }
  19913. var sources = parseSsrcs(mLine);
  19914. // Find the SIM group and nuke it.
  19915. mLine.ssrcGroups.forEach(function (simulcastGroup) {
  19916. if (simulcastGroup.semantics !== 'SIM') {
  19917. return;
  19918. }
  19919. console.debug("Imploding SIM group: " + simulcastGroup.ssrcs);
  19920. // Schedule the SIM group for nuking.
  19921. simulcastGroup.nuke = true;
  19922. var simulcastSsrcs = simulcastGroup.ssrcs.split(' ');
  19923. // Nuke all the higher layer SSRCs.
  19924. for (var i = 1; i < simulcastSsrcs.length; i++) {
  19925. var ssrc = simulcastSsrcs[i];
  19926. delete sources[ssrc];
  19927. // Remove all the groups that this SSRC participates in.
  19928. mLine.ssrcGroups.forEach(function (relatedGroup) {
  19929. if (relatedGroup.semantics === 'SIM') {
  19930. return;
  19931. }
  19932. var relatedSsrcs = relatedGroup.ssrcs.split(' ');
  19933. if (relatedSsrcs.indexOf(ssrc) === -1) {
  19934. return;
  19935. }
  19936. // Nuke all the related SSRCs.
  19937. relatedSsrcs.forEach(function (relatedSSRC) {
  19938. delete sources[relatedSSRC];
  19939. });
  19940. // Schedule the related group for nuking.
  19941. relatedGroup.nuke = true;
  19942. })
  19943. }
  19944. return;
  19945. });
  19946. mLine.ssrcs = writeSsrcs(sources);
  19947. // Nuke all the scheduled groups.
  19948. var i = mLine.ssrcGroups.length;
  19949. while (i--) {
  19950. if (mLine.ssrcGroups[i].nuke) {
  19951. mLine.ssrcGroups.splice(i, 1);
  19952. }
  19953. }
  19954. }
  19955. function removeGoogConference(mLine) {
  19956. if (!mLine || !Array.isArray(mLine.invalid)) {
  19957. return;
  19958. }
  19959. var i = mLine.invalid.length;
  19960. while (i--) {
  19961. if (mLine.invalid[i].value == 'x-google-flag:conference') {
  19962. mLine.invalid.splice(i, 1);
  19963. }
  19964. }
  19965. }
  19966. function assertGoogConference(mLine) {
  19967. if (!mLine) {
  19968. return;
  19969. }
  19970. if (!Array.isArray(mLine.invalid)) {
  19971. mLine.invalid = [];
  19972. }
  19973. if (!mLine.invalid.some(
  19974. function (i) { return i.value === 'x-google-flag:conference' })) {
  19975. mLine.invalid.push({'value': 'x-google-flag:conference'});
  19976. }
  19977. }
  19978. //endregion
  19979. //region "Private" functions
  19980. /**
  19981. *
  19982. * @param mLine
  19983. * @private
  19984. */
  19985. Simulcast.prototype._maybeInitializeLayers = function(mLine) {
  19986. if (!mLine || mLine.type !== 'video') {
  19987. return;
  19988. }
  19989. var sources = parseSsrcs(mLine);
  19990. if (Object.keys(sources).length === 0) {
  19991. // no sources, disable simulcast.
  19992. if (this.layers.length !== 0) {
  19993. this.layers = [];
  19994. }
  19995. return;
  19996. }
  19997. // find the base layer (we'll reuse its msid and cname).
  19998. var baseLayerSSRC = Object.keys(sources)[0];
  19999. var baseLayer = sources[baseLayerSSRC];
  20000. // todo(gp) handle screen sharing.
  20001. // check if base CNAME has changed and reinitialise layers.
  20002. if (this.layers.length > 0
  20003. && sources[baseLayerSSRC].cname !== this.layers[0].cname) {
  20004. this.layers = [];
  20005. }
  20006. // (re)initialise layers
  20007. if (this.layers.length < 1) {
  20008. // first push the base layer.
  20009. this.layers.push({
  20010. ssrc: baseLayerSSRC,
  20011. msid: baseLayer.msid,
  20012. cname: baseLayer.cname
  20013. });
  20014. var rtx = false; // RFC 4588
  20015. if (Array.isArray(mLine.rtp)) {
  20016. rtx = mLine.rtp.some(
  20017. function (rtpmap) { return rtpmap.codec === 'rtx'; });
  20018. }
  20019. if (rtx) {
  20020. this.layers[0].rtx = generateSSRC();
  20021. }
  20022. // now push additional layers.
  20023. for (var i = 1; i < Math.max(1, this.options.numOfLayers); i++) {
  20024. var layer = { ssrc: generateSSRC() };
  20025. if (rtx) {
  20026. layer.rtx = generateSSRC();
  20027. }
  20028. this.layers.push(layer);
  20029. }
  20030. }
  20031. };
  20032. /**
  20033. *
  20034. * @param mLine
  20035. * @private
  20036. */
  20037. Simulcast.prototype._restoreSimulcastView = function(mLine) {
  20038. if (mLine && mLine.type === 'video' && this.layers.length !== 0) {
  20039. var sources = {};
  20040. var msid = this.layers[0].msid;
  20041. var cname = this.layers[0].cname;
  20042. var simulcastSsrcs = [];
  20043. var ssrcGroups = [];
  20044. for (var i = 0; i < this.layers.length; i++) {
  20045. var layer = this.layers[i];
  20046. sources[layer.ssrc] = { msid: msid, cname: cname };
  20047. simulcastSsrcs.push(layer.ssrc);
  20048. if (layer.rtx) {
  20049. sources[layer.rtx] = {
  20050. msid: msid,
  20051. cname: cname
  20052. }
  20053. ssrcGroups.push({
  20054. semantics: 'FID',
  20055. ssrcs: [layer.ssrc, layer.rtx].join(' ')
  20056. });
  20057. }
  20058. }
  20059. ssrcGroups.push({
  20060. semantics: 'SIM',
  20061. ssrcs: simulcastSsrcs.join(' ')
  20062. });
  20063. mLine.ssrcGroups = ssrcGroups;
  20064. mLine.ssrcs = writeSsrcs(sources);
  20065. }
  20066. }
  20067. //endregion
  20068. //region "Public" functions
  20069. Simulcast.prototype.isSupported = function () {
  20070. return window.chrome;
  20071. // TODO this needs improvements. For example I doubt that Chrome in Android
  20072. // has simulcast support. Also, only recent versions of Chromium have native
  20073. // simulcast support.
  20074. }
  20075. /**
  20076. *
  20077. * @param desc
  20078. * @returns {RTCSessionDescription}
  20079. */
  20080. Simulcast.prototype.mungeRemoteDescription = function (desc) {
  20081. if (!validateDescription(desc)) {
  20082. return desc;
  20083. }
  20084. var session = transform.parse(desc.sdp);
  20085. var self = this;
  20086. processVideo(session, function (mLine) {
  20087. // Handle simulcast reception.
  20088. if (self.options.explodeRemoteSimulcast) {
  20089. explodeRemoteSimulcast(mLine);
  20090. } else {
  20091. implodeRemoteSimulcast(mLine);
  20092. }
  20093. // If native simulcast is enabled, we must append the x-goog-conference
  20094. // attribute to the SDP.
  20095. if (self.layers.length < 1) {
  20096. removeGoogConference(mLine);
  20097. } else {
  20098. assertGoogConference(mLine);
  20099. }
  20100. });
  20101. return new RTCSessionDescription({
  20102. type: desc.type,
  20103. sdp: transform.write(session)
  20104. });
  20105. };
  20106. /**
  20107. *
  20108. * @param desc
  20109. * @returns {RTCSessionDescription}
  20110. */
  20111. Simulcast.prototype.mungeLocalDescription = function (desc) {
  20112. if (!validateDescription(desc) || !this.isSupported()) {
  20113. return desc;
  20114. }
  20115. var session = transform.parse(desc.sdp);
  20116. var self = this;
  20117. processVideo(session, function (mLine) {
  20118. // Initialize native simulcast layers, if not already done.
  20119. self._maybeInitializeLayers(mLine);
  20120. // Update the SDP with the simulcast layers.
  20121. self._restoreSimulcastView(mLine);
  20122. });
  20123. return new RTCSessionDescription({
  20124. type: desc.type,
  20125. sdp: transform.write(session)
  20126. });
  20127. };
  20128. //endregion
  20129. module.exports = Simulcast;
  20130. },{"./transform-utils":74,"sdp-transform":76}],74:[function(require,module,exports){
  20131. /* Copyright @ 2015 Atlassian Pty Ltd
  20132. *
  20133. * Licensed under the Apache License, Version 2.0 (the "License");
  20134. * you may not use this file except in compliance with the License.
  20135. * You may obtain a copy of the License at
  20136. *
  20137. * http://www.apache.org/licenses/LICENSE-2.0
  20138. *
  20139. * Unless required by applicable law or agreed to in writing, software
  20140. * distributed under the License is distributed on an "AS IS" BASIS,
  20141. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  20142. * See the License for the specific language governing permissions and
  20143. * limitations under the License.
  20144. */
  20145. exports.writeSsrcs = function(sources, order) {
  20146. var ssrcs = [];
  20147. // expand sources to ssrcs
  20148. if (typeof sources !== 'undefined' &&
  20149. Object.keys(sources).length !== 0) {
  20150. if (Array.isArray(order)) {
  20151. for (var i = 0; i < order.length; i++) {
  20152. var ssrc = order[i];
  20153. var source = sources[ssrc];
  20154. Object.keys(source).forEach(function (attribute) {
  20155. ssrcs.push({
  20156. id: ssrc,
  20157. attribute: attribute,
  20158. value: source[attribute]
  20159. });
  20160. });
  20161. }
  20162. } else {
  20163. Object.keys(sources).forEach(function (ssrc) {
  20164. var source = sources[ssrc];
  20165. Object.keys(source).forEach(function (attribute) {
  20166. ssrcs.push({
  20167. id: ssrc,
  20168. attribute: attribute,
  20169. value: source[attribute]
  20170. });
  20171. });
  20172. });
  20173. }
  20174. }
  20175. return ssrcs;
  20176. };
  20177. exports.parseSsrcs = function (mLine) {
  20178. var sources = {};
  20179. // group sources attributes by ssrc.
  20180. if (typeof mLine.ssrcs !== 'undefined' && Array.isArray(mLine.ssrcs)) {
  20181. mLine.ssrcs.forEach(function (ssrc) {
  20182. if (!sources[ssrc.id])
  20183. sources[ssrc.id] = {};
  20184. sources[ssrc.id][ssrc.attribute] = ssrc.value;
  20185. });
  20186. }
  20187. return sources;
  20188. };
  20189. },{}],75:[function(require,module,exports){
  20190. arguments[4][69][0].apply(exports,arguments)
  20191. },{"dup":69}],76:[function(require,module,exports){
  20192. arguments[4][70][0].apply(exports,arguments)
  20193. },{"./parser":77,"./writer":78,"dup":70}],77:[function(require,module,exports){
  20194. arguments[4][71][0].apply(exports,arguments)
  20195. },{"./grammar":75,"dup":71}],78:[function(require,module,exports){
  20196. arguments[4][72][0].apply(exports,arguments)
  20197. },{"./grammar":75,"dup":72}],79:[function(require,module,exports){
  20198. arguments[4][69][0].apply(exports,arguments)
  20199. },{"dup":69}],80:[function(require,module,exports){
  20200. arguments[4][70][0].apply(exports,arguments)
  20201. },{"./parser":81,"./writer":82,"dup":70}],81:[function(require,module,exports){
  20202. arguments[4][71][0].apply(exports,arguments)
  20203. },{"./grammar":79,"dup":71}],82:[function(require,module,exports){
  20204. arguments[4][72][0].apply(exports,arguments)
  20205. },{"./grammar":79,"dup":72}],83:[function(require,module,exports){
  20206. var MediaStreamType = {
  20207. VIDEO_TYPE: "Video",
  20208. AUDIO_TYPE: "Audio"
  20209. };
  20210. module.exports = MediaStreamType;
  20211. },{}],84:[function(require,module,exports){
  20212. var RTCEvents = {
  20213. RTC_READY: "rtc.ready",
  20214. DATA_CHANNEL_OPEN: "rtc.data_channel_open",
  20215. LASTN_CHANGED: "rtc.lastn_changed",
  20216. DOMINANTSPEAKER_CHANGED: "rtc.dominantspeaker_changed",
  20217. LASTN_ENDPOINT_CHANGED: "rtc.lastn_endpoint_changed",
  20218. AVAILABLE_DEVICES_CHANGED: "rtc.available_devices_changed"
  20219. };
  20220. module.exports = RTCEvents;
  20221. },{}],85:[function(require,module,exports){
  20222. var Resolutions = {
  20223. "1080": {
  20224. width: 1920,
  20225. height: 1080,
  20226. order: 7
  20227. },
  20228. "fullhd": {
  20229. width: 1920,
  20230. height: 1080,
  20231. order: 7
  20232. },
  20233. "720": {
  20234. width: 1280,
  20235. height: 720,
  20236. order: 6
  20237. },
  20238. "hd": {
  20239. width: 1280,
  20240. height: 720,
  20241. order: 6
  20242. },
  20243. "960": {
  20244. width: 960,
  20245. height: 720,
  20246. order: 5
  20247. },
  20248. "640": {
  20249. width: 640,
  20250. height: 480,
  20251. order: 4
  20252. },
  20253. "vga": {
  20254. width: 640,
  20255. height: 480,
  20256. order: 4
  20257. },
  20258. "360": {
  20259. width: 640,
  20260. height: 360,
  20261. order: 3
  20262. },
  20263. "320": {
  20264. width: 320,
  20265. height: 240,
  20266. order: 2
  20267. },
  20268. "180": {
  20269. width: 320,
  20270. height: 180,
  20271. order: 1
  20272. }
  20273. };
  20274. module.exports = Resolutions;
  20275. },{}],86:[function(require,module,exports){
  20276. var XMPPEvents = {
  20277. // Designates an event indicating that the connection to the XMPP server
  20278. // failed.
  20279. CONNECTION_FAILED: "xmpp.connection.failed",
  20280. // Designates an event indicating that the media (ICE) connection was
  20281. // interrupted. This should go to the RTC module.
  20282. CONNECTION_INTERRUPTED: "xmpp.connection.interrupted",
  20283. // Designates an event indicating that the media (ICE) connection was
  20284. // restored. This should go to the RTC module.
  20285. CONNECTION_RESTORED: "xmpp.connection.restored",
  20286. // Designates an event indicating that an offer (e.g. Jingle
  20287. // session-initiate) was received.
  20288. CALL_INCOMING: "xmpp.callincoming.jingle",
  20289. // Designates an event indicating that we were kicked from the XMPP MUC.
  20290. KICKED: "xmpp.kicked",
  20291. // Designates an event indicating that the userID for a specific JID has
  20292. // changed.
  20293. // Note: currently this event fires every time we receive presence from
  20294. // someone (regardless of whether or not the "userID" changed).
  20295. USER_ID_CHANGED: "xmpp.user_id_changed",
  20296. // Designates an event indicating that we have joined the XMPP MUC.
  20297. MUC_JOINED: "xmpp.muc_joined",
  20298. // Designates an event indicating that a participant joined the XMPP MUC.
  20299. MUC_MEMBER_JOINED: "xmpp.muc_member_joined",
  20300. // Designates an event indicating that a participant left the XMPP MUC.
  20301. MUC_MEMBER_LEFT: "xmpp.muc_member_left",
  20302. // Designates an event indicating that the MUC role of a participant has
  20303. // changed.
  20304. MUC_ROLE_CHANGED: "xmpp.muc_role_changed",
  20305. // Designates an event indicating that the XMPP MUC was destroyed.
  20306. MUC_DESTROYED: "xmpp.muc_destroyed",
  20307. // Designates an event indicating that the display name of a participant
  20308. // has changed.
  20309. DISPLAY_NAME_CHANGED: "xmpp.display_name_changed",
  20310. // Designates an event indicating that we received statistics from a
  20311. // participant in the MUC.
  20312. REMOTE_STATS: "xmpp.remote_stats",
  20313. // Designates an event indicating that our role in the XMPP MUC has changed.
  20314. LOCAL_ROLE_CHANGED: "xmpp.localrole_changed",
  20315. // Designates an event indicating that the subject of the XMPP MUC has
  20316. // changed.
  20317. SUBJECT_CHANGED: "xmpp.subject_changed",
  20318. // Designates an event indicating that an XMPP message in the MUC was
  20319. // received.
  20320. MESSAGE_RECEIVED: "xmpp.message_received",
  20321. // Designates an event indicating that we sent an XMPP message to the MUC.
  20322. SENDING_CHAT_MESSAGE: "xmpp.sending_chat_message",
  20323. // Designates an event indicating that the video type (e.g. 'camera' or
  20324. // 'screen') for a participant has changed.
  20325. // Note: currently this event fires every time we receive presence from
  20326. // someone (regardless of whether or not the "video type" changed).
  20327. PARTICIPANT_VIDEO_TYPE_CHANGED: "xmpp.video_type",
  20328. // Designates an event indicating that a participant in the XMPP MUC has
  20329. // advertised that they have audio muted (or unmuted).
  20330. PARTICIPANT_AUDIO_MUTED: "xmpp.audio_muted",
  20331. // Designates an event indicating that a participant in the XMPP MUC has
  20332. // advertised that they have video muted (or unmuted).
  20333. PARTICIPANT_VIDEO_MUTED: "xmpp.video_muted",
  20334. // Designates an event indicating that the focus has asked us to mute our
  20335. // audio.
  20336. AUDIO_MUTED_BY_FOCUS: "xmpp.audio_muted_by_focus",
  20337. // Designates an event indicating that a moderator in the room changed the
  20338. // "start muted" settings for the conference.
  20339. START_MUTED_SETTING_CHANGED: "xmpp.start_muted_setting_changed",
  20340. // Designates an event indicating that we should join the conference with
  20341. // audio and/or video muted.
  20342. START_MUTED_FROM_FOCUS: "xmpp.start_muted_from_focus",
  20343. // Designates an event indicating that a remote participant's available
  20344. // devices (whether he supports a audio and/or video) changed.
  20345. // Note: currently this event fires every time we receive presence from
  20346. // someone (regardless of whether or not the devices changed).
  20347. DEVICE_AVAILABLE: "xmpp.device_available",
  20348. PEERCONNECTION_READY: "xmpp.peerconnection_ready",
  20349. CONFERENCE_SETUP_FAILED: "xmpp.conference_setup_failed",
  20350. PASSWORD_REQUIRED: "xmpp.password_required",
  20351. AUTHENTICATION_REQUIRED: "xmpp.authentication_required",
  20352. CHAT_ERROR_RECEIVED: "xmpp.chat_error_received",
  20353. ETHERPAD: "xmpp.etherpad",
  20354. BRIDGE_DOWN: "xmpp.bridge_down",
  20355. PRESENCE_STATUS: "xmpp.presence_status",
  20356. RESERVATION_ERROR: "xmpp.room_reservation_error",
  20357. DISPOSE_CONFERENCE: "xmpp.dispose_conference",
  20358. GRACEFUL_SHUTDOWN: "xmpp.graceful_shutdown",
  20359. // TODO: only used in a hack, should probably be removed.
  20360. SET_LOCAL_DESCRIPTION_ERROR: 'xmpp.set_local_description_error',
  20361. // TODO: only used in a hack, should probably be removed.
  20362. SET_REMOTE_DESCRIPTION_ERROR: 'xmpp.set_remote_description_error',
  20363. // TODO: only used in a hack, should probably be removed.
  20364. CREATE_ANSWER_ERROR: 'xmpp.create_answer_error',
  20365. JINGLE_FATAL_ERROR: 'xmpp.jingle_fatal_error',
  20366. PROMPT_FOR_LOGIN: 'xmpp.prompt_for_login',
  20367. FOCUS_DISCONNECTED: 'xmpp.focus_disconnected',
  20368. ROOM_JOIN_ERROR: 'xmpp.room_join_error',
  20369. ROOM_CONNECT_ERROR: 'xmpp.room_connect_error',
  20370. // xmpp is connected and obtained user media
  20371. READY_TO_JOIN: 'xmpp.ready_to_join',
  20372. FOCUS_LEFT: "xmpp.focus_left",
  20373. REMOTE_STREAM_RECEIVED: "xmpp.remote_stream_received",
  20374. /**
  20375. * Indicates that recording state changed.
  20376. */
  20377. RECORDING_STATE_CHANGED: "xmpp.recordingStateChanged",
  20378. /**
  20379. * Indicates that phone number changed.
  20380. */
  20381. PHONE_NUMBER_CHANGED: "conference.phoneNumberChanged"
  20382. };
  20383. module.exports = XMPPEvents;
  20384. },{}],87:[function(require,module,exports){
  20385. var AuthenticationEvents = {
  20386. /**
  20387. * Event callback arguments:
  20388. * function(authenticationEnabled, userIdentity)
  20389. * authenticationEnabled - indicates whether authentication has been enabled
  20390. * in this session
  20391. * userIdentity - if user has been logged in then it contains user name. If
  20392. * contains 'null' or 'undefined' then user is not logged in.
  20393. */
  20394. IDENTITY_UPDATED: "authentication.identity_updated"
  20395. };
  20396. module.exports = AuthenticationEvents;
  20397. },{}],88:[function(require,module,exports){
  20398. var DesktopSharingEventTypes = {
  20399. INIT: "ds.init",
  20400. SWITCHING_DONE: "ds.switching_done",
  20401. NEW_STREAM_CREATED: "ds.new_stream_created",
  20402. /**
  20403. * An event which indicates that the jidesha extension for Firefox is
  20404. * needed to proceed with screen sharing, and that it is not installed.
  20405. */
  20406. FIREFOX_EXTENSION_NEEDED: "ds.firefox_extension_needed"
  20407. };
  20408. module.exports = DesktopSharingEventTypes;
  20409. },{}],89:[function(require,module,exports){
  20410. module.exports = {
  20411. /**
  20412. * An event carrying connection statistics.
  20413. */
  20414. CONNECTION_STATS: "statistics.connectionstats",
  20415. /**
  20416. * FIXME: needs documentation.
  20417. */
  20418. AUDIO_LEVEL: "statistics.audioLevel",
  20419. /**
  20420. * FIXME: needs documentation.
  20421. */
  20422. STOP: "statistics.stop"
  20423. };
  20424. },{}],90:[function(require,module,exports){
  20425. var Constants = {
  20426. LOCAL_JID: 'local'
  20427. };
  20428. module.exports = Constants;
  20429. },{}],91:[function(require,module,exports){
  20430. arguments[4][86][0].apply(exports,arguments)
  20431. },{"dup":86}]},{},[7])(7)
  20432. });