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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241
  1. (function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.JitsiMeetJS = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
  2. (function (__filename){
  3. /* global Strophe, $, Promise */
  4. /* jshint -W101 */
  5. var logger = require("jitsi-meet-logger").getLogger(__filename);
  6. var RTC = require("./modules/RTC/RTC");
  7. var XMPPEvents = require("./service/xmpp/XMPPEvents");
  8. var RTCEvents = require("./service/RTC/RTCEvents");
  9. var EventEmitter = require("events");
  10. var JitsiConferenceEvents = require("./JitsiConferenceEvents");
  11. var JitsiConferenceErrors = require("./JitsiConferenceErrors");
  12. var JitsiParticipant = require("./JitsiParticipant");
  13. var Statistics = require("./modules/statistics/statistics");
  14. var JitsiDTMFManager = require('./modules/DTMF/JitsiDTMFManager');
  15. var JitsiTrackEvents = require("./JitsiTrackEvents");
  16. /**
  17. * Creates a JitsiConference object with the given name and properties.
  18. * Note: this constructor is not a part of the public API (objects should be
  19. * created using JitsiConnection.createConference).
  20. * @param options.config properties / settings related to the conference that will be created.
  21. * @param options.name the name of the conference
  22. * @param options.connection the JitsiConnection object for this JitsiConference.
  23. * @constructor
  24. */
  25. function JitsiConference(options) {
  26. if(!options.name || options.name.toLowerCase() !== options.name) {
  27. logger.error("Invalid conference name (no conference name passed or it"
  28. + "contains invalid characters like capital letters)!");
  29. return;
  30. }
  31. this.options = options;
  32. this.connection = this.options.connection;
  33. this.xmpp = this.connection.xmpp;
  34. this.eventEmitter = new EventEmitter();
  35. this.room = this.xmpp.createRoom(this.options.name, null, null, this.options.config);
  36. this.room.updateDeviceAvailability(RTC.getDeviceAvailability());
  37. this.rtc = new RTC(this.room, options);
  38. if(!RTC.options.disableAudioLevels)
  39. this.statistics = new Statistics();
  40. setupListeners(this);
  41. this.participants = {};
  42. this.lastActiveSpeaker = null;
  43. this.dtmfManager = null;
  44. this.somebodySupportsDTMF = false;
  45. }
  46. /**
  47. * Joins the conference.
  48. * @param password {string} the password
  49. */
  50. JitsiConference.prototype.join = function (password) {
  51. if(this.room)
  52. this.room.join(password, this.connection.tokenPassword);
  53. };
  54. /**
  55. * Check if joined to the conference.
  56. */
  57. JitsiConference.prototype.isJoined = function () {
  58. return this.room && this.room.joined;
  59. };
  60. /**
  61. * Leaves the conference.
  62. */
  63. JitsiConference.prototype.leave = function () {
  64. if(this.xmpp && this.room)
  65. this.xmpp.leaveRoom(this.room.roomjid);
  66. this.room = null;
  67. };
  68. /**
  69. * Returns name of this conference.
  70. */
  71. JitsiConference.prototype.getName = function () {
  72. return this.options.name;
  73. };
  74. /**
  75. * Check if external authentication is enabled for this conference.
  76. */
  77. JitsiConference.prototype.isExternalAuthEnabled = function () {
  78. return this.room && this.room.moderator.isExternalAuthEnabled();
  79. };
  80. /**
  81. * Get url for external authentication.
  82. * @param {boolean} [urlForPopup] if true then return url for login popup,
  83. * else url of login page.
  84. * @returns {Promise}
  85. */
  86. JitsiConference.prototype.getExternalAuthUrl = function (urlForPopup) {
  87. return new Promise(function (resolve, reject) {
  88. if (!this.isExternalAuthEnabled()) {
  89. reject();
  90. return;
  91. }
  92. if (urlForPopup) {
  93. this.room.moderator.getPopupLoginUrl(resolve, reject);
  94. } else {
  95. this.room.moderator.getLoginUrl(resolve, reject);
  96. }
  97. }.bind(this));
  98. };
  99. /**
  100. * Returns the local tracks.
  101. */
  102. JitsiConference.prototype.getLocalTracks = function () {
  103. if (this.rtc) {
  104. return this.rtc.localStreams;
  105. } else {
  106. return [];
  107. }
  108. };
  109. /**
  110. * Attaches a handler for events(For example - "participant joined".) in the conference. All possible event are defined
  111. * in JitsiConferenceEvents.
  112. * @param eventId the event ID.
  113. * @param handler handler for the event.
  114. *
  115. * Note: consider adding eventing functionality by extending an EventEmitter impl, instead of rolling ourselves
  116. */
  117. JitsiConference.prototype.on = function (eventId, handler) {
  118. if(this.eventEmitter)
  119. this.eventEmitter.on(eventId, handler);
  120. };
  121. /**
  122. * Removes event listener
  123. * @param eventId the event ID.
  124. * @param [handler] optional, the specific handler to unbind
  125. *
  126. * Note: consider adding eventing functionality by extending an EventEmitter impl, instead of rolling ourselves
  127. */
  128. JitsiConference.prototype.off = function (eventId, handler) {
  129. if(this.eventEmitter)
  130. this.eventEmitter.removeListener(eventId, handler);
  131. };
  132. // Common aliases for event emitter
  133. JitsiConference.prototype.addEventListener = JitsiConference.prototype.on;
  134. JitsiConference.prototype.removeEventListener = JitsiConference.prototype.off;
  135. /**
  136. * Receives notifications from another participants for commands / custom events
  137. * (send by sendPresenceCommand method).
  138. * @param command {String} the name of the command
  139. * @param handler {Function} handler for the command
  140. */
  141. JitsiConference.prototype.addCommandListener = function (command, handler) {
  142. if(this.room)
  143. this.room.addPresenceListener(command, handler);
  144. };
  145. /**
  146. * Removes command listener
  147. * @param command {String} the name of the command
  148. */
  149. JitsiConference.prototype.removeCommandListener = function (command) {
  150. if(this.room)
  151. this.room.removePresenceListener(command);
  152. };
  153. /**
  154. * Sends text message to the other participants in the conference
  155. * @param message the text message.
  156. */
  157. JitsiConference.prototype.sendTextMessage = function (message) {
  158. if(this.room)
  159. this.room.sendMessage(message);
  160. };
  161. /**
  162. * Send presence command.
  163. * @param name the name of the command.
  164. * @param values Object with keys and values that will be send.
  165. **/
  166. JitsiConference.prototype.sendCommand = function (name, values) {
  167. if(this.room) {
  168. this.room.addToPresence(name, values);
  169. this.room.sendPresence();
  170. }
  171. };
  172. /**
  173. * Send presence command one time.
  174. * @param name the name of the command.
  175. * @param values Object with keys and values that will be send.
  176. **/
  177. JitsiConference.prototype.sendCommandOnce = function (name, values) {
  178. this.sendCommand(name, values);
  179. this.removeCommand(name);
  180. };
  181. /**
  182. * Send presence command.
  183. * @param name the name of the command.
  184. * @param values Object with keys and values that will be send.
  185. * @param persistent if false the command will be sent only one time
  186. **/
  187. JitsiConference.prototype.removeCommand = function (name) {
  188. if(this.room)
  189. this.room.removeFromPresence(name);
  190. };
  191. /**
  192. * Sets the display name for this conference.
  193. * @param name the display name to set
  194. */
  195. JitsiConference.prototype.setDisplayName = function(name) {
  196. if(this.room){
  197. // remove previously set nickname
  198. this.room.removeFromPresence("nick");
  199. this.room.addToPresence("nick", {attributes: {xmlns: 'http://jabber.org/protocol/nick'}, value: name});
  200. this.room.sendPresence();
  201. }
  202. };
  203. /**
  204. * Adds JitsiLocalTrack object to the conference.
  205. * @param track the JitsiLocalTrack object.
  206. */
  207. JitsiConference.prototype.addTrack = function (track) {
  208. this.room.addStream(track.getOriginalStream(), function () {
  209. this.rtc.addLocalStream(track);
  210. var muteHandler = this._fireMuteChangeEvent.bind(this, track);
  211. var stopHandler = this.removeTrack.bind(this, track);
  212. var audioLevelHandler = this._fireAudioLevelChangeEvent.bind(this);
  213. track.addEventListener(JitsiTrackEvents.TRACK_MUTE_CHANGED, muteHandler);
  214. track.addEventListener(JitsiTrackEvents.TRACK_STOPPED, stopHandler);
  215. track.addEventListener(JitsiTrackEvents.TRACK_AUDIO_LEVEL_CHANGED, audioLevelHandler);
  216. this.addEventListener(JitsiConferenceEvents.TRACK_REMOVED, function (someTrack) {
  217. if (someTrack !== track) {
  218. return;
  219. }
  220. track.removeEventListener(JitsiTrackEvents.TRACK_MUTE_CHANGED, muteHandler);
  221. track.removeEventListener(JitsiTrackEvents.TRACK_STOPPED, stopHandler);
  222. track.removeEventListener(JitsiTrackEvents.TRACK_AUDIO_LEVEL_CHANGED, audioLevelHandler);
  223. });
  224. this.eventEmitter.emit(JitsiConferenceEvents.TRACK_ADDED, track);
  225. }.bind(this));
  226. };
  227. /**
  228. * Fires TRACK_AUDIO_LEVEL_CHANGED change conference event.
  229. * @param audioLevel the audio level
  230. */
  231. JitsiConference.prototype._fireAudioLevelChangeEvent = function (audioLevel) {
  232. this.eventEmitter.emit(
  233. JitsiConferenceEvents.TRACK_AUDIO_LEVEL_CHANGED,
  234. this.myUserId(), audioLevel);
  235. };
  236. /**
  237. * Fires TRACK_MUTE_CHANGED change conference event.
  238. * @param track the JitsiTrack object related to the event.
  239. */
  240. JitsiConference.prototype._fireMuteChangeEvent = function (track) {
  241. this.eventEmitter.emit(JitsiConferenceEvents.TRACK_MUTE_CHANGED, track);
  242. };
  243. /**
  244. * Removes JitsiLocalTrack object to the conference.
  245. * @param track the JitsiLocalTrack object.
  246. */
  247. JitsiConference.prototype.removeTrack = function (track) {
  248. if(!this.room){
  249. if(this.rtc)
  250. this.rtc.removeLocalStream(track);
  251. return;
  252. }
  253. this.room.removeStream(track.getOriginalStream(), function(){
  254. this.rtc.removeLocalStream(track);
  255. this.eventEmitter.emit(JitsiConferenceEvents.TRACK_REMOVED, track);
  256. }.bind(this));
  257. };
  258. /**
  259. * Get role of the local user.
  260. * @returns {string} user role: 'moderator' or 'none'
  261. */
  262. JitsiConference.prototype.getRole = function () {
  263. return this.room.role;
  264. };
  265. /**
  266. * Check if local user is moderator.
  267. * @returns {boolean} true if local user is moderator, false otherwise.
  268. */
  269. JitsiConference.prototype.isModerator = function () {
  270. return this.room.isModerator();
  271. };
  272. /**
  273. * Set password for the room.
  274. * @param {string} password new password for the room.
  275. * @returns {Promise}
  276. */
  277. JitsiConference.prototype.lock = function (password) {
  278. if (!this.isModerator()) {
  279. return Promise.reject();
  280. }
  281. var conference = this;
  282. return new Promise(function (resolve, reject) {
  283. conference.xmpp.lockRoom(password, function () {
  284. resolve();
  285. }, function (err) {
  286. reject(err);
  287. }, function () {
  288. reject(JitsiConferenceErrors.PASSWORD_NOT_SUPPORTED);
  289. });
  290. });
  291. };
  292. /**
  293. * Remove password from the room.
  294. * @returns {Promise}
  295. */
  296. JitsiConference.prototype.unlock = function () {
  297. return this.lock(undefined);
  298. };
  299. /**
  300. * Elects the participant with the given id to be the selected participant or the speaker.
  301. * @param id the identifier of the participant
  302. */
  303. JitsiConference.prototype.selectParticipant = function(participantId) {
  304. if (this.rtc) {
  305. this.rtc.selectedEndpoint(participantId);
  306. }
  307. };
  308. /**
  309. *
  310. * @param id the identifier of the participant
  311. */
  312. JitsiConference.prototype.pinParticipant = function(participantId) {
  313. if (this.rtc) {
  314. this.rtc.pinEndpoint(participantId);
  315. }
  316. };
  317. /**
  318. * Returns the list of participants for this conference.
  319. * @return Array<JitsiParticipant> a list of participant identifiers containing all conference participants.
  320. */
  321. JitsiConference.prototype.getParticipants = function() {
  322. return Object.keys(this.participants).map(function (key) {
  323. return this.participants[key];
  324. }, this);
  325. };
  326. /**
  327. * @returns {JitsiParticipant} the participant in this conference with the specified id (or
  328. * undefined if there isn't one).
  329. * @param id the id of the participant.
  330. */
  331. JitsiConference.prototype.getParticipantById = function(id) {
  332. return this.participants[id];
  333. };
  334. JitsiConference.prototype.onMemberJoined = function (jid, email, nick) {
  335. var id = Strophe.getResourceFromJid(jid);
  336. if (id === 'focus') {
  337. return;
  338. }
  339. var participant = new JitsiParticipant(id, this, nick);
  340. this.participants[id] = participant;
  341. this.eventEmitter.emit(JitsiConferenceEvents.USER_JOINED, id, participant);
  342. this.xmpp.connection.disco.info(
  343. jid, "node", function(iq) {
  344. participant._supportsDTMF = $(iq).find(
  345. '>query>feature[var="urn:xmpp:jingle:dtmf:0"]').length > 0;
  346. this.updateDTMFSupport();
  347. }.bind(this)
  348. );
  349. };
  350. JitsiConference.prototype.onMemberLeft = function (jid) {
  351. var id = Strophe.getResourceFromJid(jid);
  352. var participant = this.participants[id];
  353. delete this.participants[id];
  354. this.eventEmitter.emit(JitsiConferenceEvents.USER_LEFT, id, participant);
  355. };
  356. JitsiConference.prototype.onUserRoleChanged = function (jid, role) {
  357. var id = Strophe.getResourceFromJid(jid);
  358. var participant = this.getParticipantById(id);
  359. if (!participant) {
  360. return;
  361. }
  362. participant._role = role;
  363. this.eventEmitter.emit(JitsiConferenceEvents.USER_ROLE_CHANGED, id, role);
  364. };
  365. JitsiConference.prototype.onDisplayNameChanged = function (jid, displayName) {
  366. var id = Strophe.getResourceFromJid(jid);
  367. var participant = this.getParticipantById(id);
  368. if (!participant) {
  369. return;
  370. }
  371. participant._displayName = displayName;
  372. this.eventEmitter.emit(JitsiConferenceEvents.DISPLAY_NAME_CHANGED, id, displayName);
  373. };
  374. JitsiConference.prototype.onTrackAdded = function (track) {
  375. var id = track.getParticipantId();
  376. var participant = this.getParticipantById(id);
  377. if (!participant) {
  378. return;
  379. }
  380. // add track to JitsiParticipant
  381. participant._tracks.push(track);
  382. var emitter = this.eventEmitter;
  383. track.addEventListener(
  384. JitsiTrackEvents.TRACK_STOPPED,
  385. function () {
  386. // remove track from JitsiParticipant
  387. var pos = participant._tracks.indexOf(track);
  388. if (pos > -1) {
  389. participant._tracks.splice(pos, 1);
  390. }
  391. emitter.emit(JitsiConferenceEvents.TRACK_REMOVED, track);
  392. }
  393. );
  394. track.addEventListener(
  395. JitsiTrackEvents.TRACK_MUTE_CHANGED,
  396. function () {
  397. emitter.emit(JitsiConferenceEvents.TRACK_MUTE_CHANGED, track);
  398. }
  399. );
  400. track.addEventListener(
  401. JitsiTrackEvents.TRACK_AUDIO_LEVEL_CHANGED,
  402. function (audioLevel) {
  403. emitter.emit(JitsiConferenceEvents.TRACK_AUDIO_LEVEL_CHANGED, id, audioLevel);
  404. }
  405. );
  406. this.eventEmitter.emit(JitsiConferenceEvents.TRACK_ADDED, track);
  407. };
  408. JitsiConference.prototype.updateDTMFSupport = function () {
  409. var somebodySupportsDTMF = false;
  410. var participants = this.getParticipants();
  411. // check if at least 1 participant supports DTMF
  412. for (var i = 0; i < participants.length; i += 1) {
  413. if (participants[i].supportsDTMF()) {
  414. somebodySupportsDTMF = true;
  415. break;
  416. }
  417. }
  418. if (somebodySupportsDTMF !== this.somebodySupportsDTMF) {
  419. this.somebodySupportsDTMF = somebodySupportsDTMF;
  420. this.eventEmitter.emit(JitsiConferenceEvents.DTMF_SUPPORT_CHANGED, somebodySupportsDTMF);
  421. }
  422. };
  423. /**
  424. * Allows to check if there is at least one user in the conference
  425. * that supports DTMF.
  426. * @returns {boolean} true if somebody supports DTMF, false otherwise
  427. */
  428. JitsiConference.prototype.isDTMFSupported = function () {
  429. return this.somebodySupportsDTMF;
  430. };
  431. /**
  432. * Returns the local user's ID
  433. * @return {string} local user's ID
  434. */
  435. JitsiConference.prototype.myUserId = function () {
  436. return (this.room && this.room.myroomjid)? Strophe.getResourceFromJid(this.room.myroomjid) : null;
  437. };
  438. JitsiConference.prototype.sendTones = function (tones, duration, pause) {
  439. if (!this.dtmfManager) {
  440. var connection = this.xmpp.connection.jingle.activecall.peerconnection;
  441. if (!connection) {
  442. logger.warn("cannot sendTones: no conneciton");
  443. return;
  444. }
  445. var tracks = this.getLocalTracks().filter(function (track) {
  446. return track.isAudioTrack();
  447. });
  448. if (!tracks.length) {
  449. logger.warn("cannot sendTones: no local audio stream");
  450. return;
  451. }
  452. this.dtmfManager = new JitsiDTMFManager(tracks[0], connection);
  453. }
  454. this.dtmfManager.sendTones(tones, duration, pause);
  455. };
  456. /**
  457. * Setups the listeners needed for the conference.
  458. * @param conference the conference
  459. */
  460. function setupListeners(conference) {
  461. conference.xmpp.addListener(XMPPEvents.CALL_INCOMING, function (event) {
  462. conference.rtc.onIncommingCall(event);
  463. if(conference.statistics)
  464. conference.statistics.startRemoteStats(event.peerconnection);
  465. });
  466. conference.room.addListener(XMPPEvents.REMOTE_STREAM_RECEIVED,
  467. function (data, sid, thessrc) {
  468. var track = conference.rtc.createRemoteStream(data, sid, thessrc);
  469. if (track) {
  470. conference.onTrackAdded(track);
  471. }
  472. }
  473. );
  474. conference.room.addListener(XMPPEvents.MUC_JOINED, function () {
  475. conference.eventEmitter.emit(JitsiConferenceEvents.CONFERENCE_JOINED);
  476. });
  477. conference.room.addListener(XMPPEvents.ROOM_JOIN_ERROR, function (pres) {
  478. conference.eventEmitter.emit(JitsiConferenceEvents.CONFERENCE_FAILED, JitsiConferenceErrors.CONNECTION_ERROR, pres);
  479. });
  480. conference.room.addListener(XMPPEvents.ROOM_CONNECT_ERROR, function (pres) {
  481. conference.eventEmitter.emit(JitsiConferenceEvents.CONFERENCE_FAILED, JitsiConferenceErrors.CONNECTION_ERROR, pres);
  482. });
  483. conference.room.addListener(XMPPEvents.PASSWORD_REQUIRED, function (pres) {
  484. conference.eventEmitter.emit(JitsiConferenceEvents.CONFERENCE_FAILED, JitsiConferenceErrors.PASSWORD_REQUIRED, pres);
  485. });
  486. conference.room.addListener(XMPPEvents.AUTHENTICATION_REQUIRED, function () {
  487. conference.eventEmitter.emit(JitsiConferenceEvents.CONFERENCE_FAILED, JitsiConferenceErrors.AUTHENTICATION_REQUIRED);
  488. });
  489. // FIXME
  490. // conference.room.addListener(XMPPEvents.MUC_JOINED, function () {
  491. // conference.eventEmitter.emit(JitsiConferenceEvents.CONFERENCE_LEFT);
  492. // });
  493. conference.room.addListener(XMPPEvents.MUC_MEMBER_JOINED, conference.onMemberJoined.bind(conference));
  494. conference.room.addListener(XMPPEvents.MUC_MEMBER_LEFT, conference.onMemberLeft.bind(conference));
  495. conference.room.addListener(XMPPEvents.DISPLAY_NAME_CHANGED, conference.onDisplayNameChanged.bind(conference));
  496. conference.room.addListener(XMPPEvents.LOCAL_ROLE_CHANGED, function (role) {
  497. conference.eventEmitter.emit(JitsiConferenceEvents.USER_ROLE_CHANGED, conference.myUserId(), role);
  498. });
  499. conference.room.addListener(XMPPEvents.MUC_ROLE_CHANGED, conference.onUserRoleChanged.bind(conference));
  500. conference.room.addListener(XMPPEvents.CONNECTION_INTERRUPTED, function () {
  501. conference.eventEmitter.emit(JitsiConferenceEvents.CONNECTION_INTERRUPTED);
  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.CONFERENCE_FAILED, JitsiConferenceErrors.SETUP_FAILED);
  508. });
  509. conference.room.addListener(XMPPEvents.MESSAGE_RECEIVED, function (jid, displayName, txt, myJid, ts) {
  510. var id = Strophe.getResourceFromJid(jid);
  511. conference.eventEmitter.emit(JitsiConferenceEvents.MESSAGE_RECEIVED, id, txt, ts);
  512. });
  513. conference.rtc.addListener(RTCEvents.DOMINANTSPEAKER_CHANGED, function (id) {
  514. if(conference.lastActiveSpeaker !== id && conference.room) {
  515. conference.lastActiveSpeaker = id;
  516. conference.eventEmitter.emit(JitsiConferenceEvents.ACTIVE_SPEAKER_CHANGED, id);
  517. }
  518. });
  519. conference.rtc.addListener(RTCEvents.LASTN_CHANGED, function (oldValue, newValue) {
  520. conference.eventEmitter.emit(JitsiConferenceEvents.IN_LAST_N_CHANGED, oldValue, newValue);
  521. });
  522. conference.rtc.addListener(RTCEvents.LASTN_ENDPOINT_CHANGED,
  523. function (lastNEndpoints, endpointsEnteringLastN) {
  524. conference.eventEmitter.emit(JitsiConferenceEvents.LAST_N_ENDPOINTS_CHANGED,
  525. lastNEndpoints, endpointsEnteringLastN);
  526. });
  527. conference.xmpp.addListener(XMPPEvents.PASSWORD_REQUIRED, function () {
  528. conference.eventEmitter.emit(JitsiConferenceErrors.PASSWORD_REQUIRED);
  529. });
  530. if(conference.statistics) {
  531. //FIXME: Maybe remove event should not be associated with the conference.
  532. conference.statistics.addAudioLevelListener(function (ssrc, level) {
  533. var userId = null;
  534. var jid = conference.room.getJidBySSRC(ssrc);
  535. if (!jid)
  536. return;
  537. conference.rtc.setAudioLevel(jid, level);
  538. });
  539. conference.xmpp.addListener(XMPPEvents.DISPOSE_CONFERENCE,
  540. function () {
  541. conference.statistics.dispose();
  542. });
  543. // FIXME: Maybe we should move this.
  544. // RTC.addListener(RTCEvents.AVAILABLE_DEVICES_CHANGED, function (devices) {
  545. // conference.room.updateDeviceAvailability(devices);
  546. // });
  547. }
  548. }
  549. module.exports = JitsiConference;
  550. }).call(this,"/JitsiConference.js")
  551. },{"./JitsiConferenceErrors":2,"./JitsiConferenceEvents":3,"./JitsiParticipant":8,"./JitsiTrackEvents":10,"./modules/DTMF/JitsiDTMFManager":11,"./modules/RTC/RTC":16,"./modules/statistics/statistics":24,"./service/RTC/RTCEvents":79,"./service/xmpp/XMPPEvents":85,"events":43,"jitsi-meet-logger":47}],2:[function(require,module,exports){
  552. /**
  553. * Enumeration with the errors for the conference.
  554. * @type {{string: string}}
  555. */
  556. var JitsiConferenceErrors = {
  557. /**
  558. * Indicates that a password is required in order to join the conference.
  559. */
  560. PASSWORD_REQUIRED: "conference.passwordRequired",
  561. /**
  562. * Indicates that client must be authenticated to create the conference.
  563. */
  564. AUTHENTICATION_REQUIRED: "conference.authenticationRequired",
  565. /**
  566. * Indicates that password cannot be set for this conference.
  567. */
  568. PASSWORD_NOT_SUPPORTED: "conference.passwordNotSupported",
  569. /**
  570. * Indicates that a connection error occurred when trying to join a
  571. * conference.
  572. */
  573. CONNECTION_ERROR: "conference.connectionError",
  574. /**
  575. * Indicates that the conference setup failed.
  576. */
  577. SETUP_FAILED: "conference.setup_failed",
  578. /**
  579. * Indicates that there is no available videobridge.
  580. */
  581. VIDEOBRIDGE_NOT_AVAILABLE: "conference.videobridgeNotAvailable"
  582. /**
  583. * Many more errors TBD here.
  584. */
  585. };
  586. module.exports = JitsiConferenceErrors;
  587. },{}],3:[function(require,module,exports){
  588. /**
  589. * Enumeration with the events for the conference.
  590. * @type {{string: string}}
  591. */
  592. var JitsiConferenceEvents = {
  593. /**
  594. * A new media track was added to the conference.
  595. */
  596. TRACK_ADDED: "conference.trackAdded",
  597. /**
  598. * The media track was removed from the conference.
  599. */
  600. TRACK_REMOVED: "conference.trackRemoved",
  601. /**
  602. * The active speaker was changed.
  603. */
  604. ACTIVE_SPEAKER_CHANGED: "conference.activeSpeaker",
  605. /**
  606. * A new user joinned the conference.
  607. */
  608. USER_JOINED: "conference.userJoined",
  609. /**
  610. * A user has left the conference.
  611. */
  612. USER_LEFT: "conference.userLeft",
  613. /**
  614. * User role changed.
  615. */
  616. USER_ROLE_CHANGED: "conference.roleChanged",
  617. /**
  618. * New text message was received.
  619. */
  620. MESSAGE_RECEIVED: "conference.messageReceived",
  621. /**
  622. * A user has changed it display name
  623. */
  624. DISPLAY_NAME_CHANGED: "conference.displayNameChanged",
  625. /**
  626. * A participant avatar has changed.
  627. */
  628. AVATAR_CHANGED: "conference.avatarChanged",
  629. /**
  630. * New connection statistics are received.
  631. */
  632. CONNECTION_STATS_RECEIVED: "conference.connectionStatsReceived",
  633. /**
  634. * The Last N set is changed.
  635. */
  636. LAST_N_ENDPOINTS_CHANGED: "conference.lastNEndpointsChanged",
  637. /**
  638. * You are included / excluded in somebody's last N set
  639. */
  640. IN_LAST_N_CHANGED: "conference.lastNEndpointsChanged",
  641. /**
  642. * A media track ( attached to the conference) mute status was changed.
  643. */
  644. TRACK_MUTE_CHANGED: "conference.trackMuteChanged",
  645. /**
  646. * Audio levels of a media track ( attached to the conference) was changed.
  647. */
  648. TRACK_AUDIO_LEVEL_CHANGED: "conference.audioLevelsChanged",
  649. /**
  650. * Indicates that the connection to the conference has been interrupted
  651. * for some reason.
  652. */
  653. CONNECTION_INTERRUPTED: "conference.connectionInterrupted",
  654. /**
  655. * Indicates that the connection to the conference has been restored.
  656. */
  657. CONNECTION_RESTORED: "conference.connectionRestored",
  658. /**
  659. * Indicates that conference failed.
  660. */
  661. CONFERENCE_FAILED: "conference.failed",
  662. /**
  663. * Indicates that conference has been joined.
  664. */
  665. CONFERENCE_JOINED: "conference.joined",
  666. /**
  667. * Indicates that conference has been left.
  668. */
  669. CONFERENCE_LEFT: "conference.left",
  670. /**
  671. * Indicates that DTMF support changed.
  672. */
  673. DTMF_SUPPORT_CHANGED: "conference.dtmfSupportChanged"
  674. };
  675. module.exports = JitsiConferenceEvents;
  676. },{}],4:[function(require,module,exports){
  677. var JitsiConference = require("./JitsiConference");
  678. var XMPP = require("./modules/xmpp/xmpp");
  679. var RandomUtil = require("./modules/util/RandomUtil");
  680. /**
  681. * Utility method that generates user name based on random hex values.
  682. * Eg. 12345678-1234-1234-12345678
  683. * @returns {string}
  684. */
  685. function generateUserName() {
  686. return RandomUtil.randomHexString(8) + "-" + RandomUtil.randomHexString(4) +
  687. "-" + RandomUtil.randomHexString(4) + "-" +
  688. RandomUtil.randomHexDigit(8);
  689. }
  690. /**
  691. * Creates new connection object for the Jitsi Meet server side video conferencing service. Provides access to the
  692. * JitsiConference interface.
  693. * @param appID identification for the provider of Jitsi Meet video conferencing services.
  694. * @param tokenPassword secret generated by the provider of Jitsi Meet video conferencing services.
  695. * The token will be send to the provider from the Jitsi Meet server deployment for authorization of the current client.
  696. * The format is:
  697. * passwordToken = token + "_" + roomName + "_" + ts
  698. * See doc/tokens.md for more info on how tokens are generated.
  699. * @param options Object with properties / settings related to connection with the server.
  700. * @constructor
  701. */
  702. function JitsiConnection(appID, tokenPassword, options) {
  703. this.appID = appID;
  704. this.tokenPassword = tokenPassword;
  705. this.options = options;
  706. this.xmpp = new XMPP(options);
  707. this.conferences = {};
  708. }
  709. /**
  710. * Connect the client with the server.
  711. * @param options {object} connecting options (for example authentications parameters).
  712. */
  713. JitsiConnection.prototype.connect = function (options) {
  714. if(!options)
  715. options = {};
  716. // If we have token provided use it as a password and generate random username
  717. if (this.tokenPassword) {
  718. options.password = this.tokenPassword;
  719. if (!options.id) {
  720. options.id = generateUserName() + "@" + this.options.hosts.domain;
  721. }
  722. }
  723. this.xmpp.connect(options.id, options.password);
  724. }
  725. /**
  726. * Disconnect the client from the server.
  727. */
  728. JitsiConnection.prototype.disconnect = function () {
  729. this.xmpp.disconnect();
  730. }
  731. /**
  732. * This method allows renewal of the tokens if they are expiring.
  733. * @param token the new token.
  734. */
  735. JitsiConnection.prototype.setToken = function (token) {
  736. this.token = token;
  737. }
  738. /**
  739. * Creates and joins new conference.
  740. * @param name the name of the conference; if null - a generated name will be provided from the api
  741. * @param options Object with properties / settings related to the conference that will be created.
  742. * @returns {JitsiConference} returns the new conference object.
  743. */
  744. JitsiConnection.prototype.initJitsiConference = function (name, options) {
  745. this.conferences[name] = new JitsiConference({name: name, config: options, connection: this});
  746. return this.conferences[name];
  747. }
  748. /**
  749. * Subscribes the passed listener to the event.
  750. * @param event {JitsiConnectionEvents} the connection event.
  751. * @param listener {Function} the function that will receive the event
  752. */
  753. JitsiConnection.prototype.addEventListener = function (event, listener) {
  754. this.xmpp.addListener(event, listener);
  755. }
  756. /**
  757. * Unsubscribes the passed handler.
  758. * @param event {JitsiConnectionEvents} the connection event.
  759. * @param listener {Function} the function that will receive the event
  760. */
  761. JitsiConnection.prototype.removeEventListener = function (event, listener) {
  762. this.xmpp.removeListener(event, listener);
  763. }
  764. module.exports = JitsiConnection;
  765. },{"./JitsiConference":1,"./modules/util/RandomUtil":25,"./modules/xmpp/xmpp":41}],5:[function(require,module,exports){
  766. /**
  767. * Enumeration with the errors for the connection.
  768. * @type {{string: string}}
  769. */
  770. var JitsiConnectionErrors = {
  771. /**
  772. * Indicates that a password is required in order to join the conference.
  773. */
  774. PASSWORD_REQUIRED: "connection.passwordRequired",
  775. /**
  776. * Indicates that a connection error occurred when trying to join a
  777. * conference.
  778. */
  779. CONNECTION_ERROR: "connection.connectionError",
  780. /**
  781. * Not specified errors.
  782. */
  783. OTHER_ERROR: "connection.otherError"
  784. };
  785. module.exports = JitsiConnectionErrors;
  786. },{}],6:[function(require,module,exports){
  787. /**
  788. * Enumeration with the events for the connection.
  789. * @type {{string: string}}
  790. */
  791. var JitsiConnnectionEvents = {
  792. /**
  793. * Indicates that the connection has been failed for some reason.
  794. */
  795. CONNECTION_FAILED: "connection.connectionFailed",
  796. /**
  797. * Indicates that the connection has been established.
  798. */
  799. CONNECTION_ESTABLISHED: "connection.connectionEstablished",
  800. /**
  801. * Indicates that the connection has been disconnected.
  802. */
  803. CONNECTION_DISCONNECTED: "connection.connectionDisconnected",
  804. /**
  805. * Indicates that the perfomed action cannot be executed because the
  806. * connection is not in the correct state(connected, disconnected, etc.)
  807. */
  808. WRONG_STATE: "connection.wrongState"
  809. };
  810. module.exports = JitsiConnnectionEvents;
  811. },{}],7:[function(require,module,exports){
  812. var JitsiConnection = require("./JitsiConnection");
  813. var JitsiConferenceEvents = require("./JitsiConferenceEvents");
  814. var JitsiConnectionEvents = require("./JitsiConnectionEvents");
  815. var JitsiConnectionErrors = require("./JitsiConnectionErrors");
  816. var JitsiConferenceErrors = require("./JitsiConferenceErrors");
  817. var JitsiTrackEvents = require("./JitsiTrackEvents");
  818. var JitsiTrackErrors = require("./JitsiTrackErrors");
  819. var Logger = require("jitsi-meet-logger");
  820. var RTC = require("./modules/RTC/RTC");
  821. var Statistics = require("./modules/statistics/statistics");
  822. /**
  823. * Namespace for the interface of Jitsi Meet Library.
  824. */
  825. var LibJitsiMeet = {
  826. JitsiConnection: JitsiConnection,
  827. events: {
  828. conference: JitsiConferenceEvents,
  829. connection: JitsiConnectionEvents,
  830. track: JitsiTrackEvents
  831. },
  832. errors: {
  833. conference: JitsiConferenceErrors,
  834. connection: JitsiConnectionErrors,
  835. track: JitsiTrackErrors
  836. },
  837. logLevels: Logger.levels,
  838. init: function (options) {
  839. return RTC.init(options || {});
  840. },
  841. setLogLevel: function (level) {
  842. Logger.setLogLevel(level);
  843. },
  844. /**
  845. * Creates the media tracks and returns them trough the callback.
  846. * @param options Object with properties / settings specifying the tracks which should be created.
  847. * should be created or some additional configurations about resolution for example.
  848. * @param {Array} options.devices the devices that will be requested
  849. * @param {string} options.resolution resolution constraints
  850. * @param {bool} options.dontCreateJitsiTrack if <tt>true</tt> objects with the following structure {stream: the Media Stream,
  851. * type: "audio" or "video", videoType: "camera" or "desktop"}
  852. * will be returned trough the Promise, otherwise JitsiTrack objects will be returned.
  853. * @param {string} options.cameraDeviceId
  854. * @param {string} options.micDeviceId
  855. * @returns {Promise.<{Array.<JitsiTrack>}, JitsiConferenceError>}
  856. * A promise that returns an array of created JitsiTracks if resolved,
  857. * or a JitsiConferenceError if rejected.
  858. */
  859. createLocalTracks: function (options) {
  860. return RTC.obtainAudioAndVideoPermissions(options || {}).then(
  861. function(tracks) {
  862. if(!RTC.options.disableAudioLevels)
  863. for(var i = 0; i < tracks.length; i++) {
  864. var track = tracks[i];
  865. var mStream = track.getOriginalStream();
  866. if(track.getType() === "audio"){
  867. Statistics.startLocalStats(mStream,
  868. track.setAudioLevel.bind(track));
  869. track.addEventListener(
  870. JitsiTrackEvents.TRACK_STOPPED,
  871. function(){
  872. Statistics.stopLocalStats(mStream);
  873. });
  874. }
  875. }
  876. return tracks;
  877. });
  878. },
  879. /**
  880. * Checks if its possible to enumerate available cameras/micropones.
  881. * @returns {boolean} true if available, false otherwise.
  882. */
  883. isDeviceListAvailable: function () {
  884. return RTC.isDeviceListAvailable();
  885. },
  886. /**
  887. * Returns true if changing the camera / microphone device is supported and
  888. * false if not.
  889. * @returns {boolean} true if available, false otherwise.
  890. */
  891. isDeviceChangeAvailable: function () {
  892. return RTC.isDeviceChangeAvailable();
  893. },
  894. enumerateDevices: function (callback) {
  895. RTC.enumerateDevices(callback);
  896. }
  897. };
  898. require("es6-promise").polyfill()
  899. //Setups the promise object.
  900. window.Promise = window.Promise || require("es6-promise").Promise;
  901. module.exports = LibJitsiMeet;
  902. },{"./JitsiConferenceErrors":2,"./JitsiConferenceEvents":3,"./JitsiConnection":4,"./JitsiConnectionErrors":5,"./JitsiConnectionEvents":6,"./JitsiTrackErrors":9,"./JitsiTrackEvents":10,"./modules/RTC/RTC":16,"./modules/statistics/statistics":24,"es6-promise":45,"jitsi-meet-logger":47}],8:[function(require,module,exports){
  903. /**
  904. * Represents a participant in (a member of) a conference.
  905. */
  906. function JitsiParticipant(id, conference, displayName){
  907. this._id = id;
  908. this._conference = conference;
  909. this._displayName = displayName;
  910. this._supportsDTMF = false;
  911. this._tracks = [];
  912. this._role = 'none';
  913. }
  914. /**
  915. * @returns {JitsiConference} The conference that this participant belongs to.
  916. */
  917. JitsiParticipant.prototype.getConference = function() {
  918. return this._conference;
  919. };
  920. /**
  921. * @returns {Array.<JitsiTrack>} The list of media tracks for this participant.
  922. */
  923. JitsiParticipant.prototype.getTracks = function() {
  924. return this._tracks;
  925. };
  926. /**
  927. * @returns {String} The ID (i.e. JID) of this participant.
  928. */
  929. JitsiParticipant.prototype.getId = function() {
  930. return this._id;
  931. };
  932. /**
  933. * @returns {String} The human-readable display name of this participant.
  934. */
  935. JitsiParticipant.prototype.getDisplayName = function() {
  936. return this._displayName;
  937. };
  938. /**
  939. * @returns {Boolean} Whether this participant is a moderator or not.
  940. */
  941. JitsiParticipant.prototype.isModerator = function() {
  942. return this._role === 'moderator';
  943. };
  944. // Gets a link to an etherpad instance advertised by the participant?
  945. //JitsiParticipant.prototype.getEtherpad = function() {
  946. //
  947. //}
  948. /*
  949. * @returns {Boolean} Whether this participant has muted their audio.
  950. */
  951. JitsiParticipant.prototype.isAudioMuted = function() {
  952. return this.getTracks().reduce(function (track, isAudioMuted) {
  953. return isAudioMuted && (track.isVideoTrack() || track.isMuted());
  954. }, true);
  955. };
  956. /*
  957. * @returns {Boolean} Whether this participant has muted their video.
  958. */
  959. JitsiParticipant.prototype.isVideoMuted = function() {
  960. return this.getTracks().reduce(function (track, isVideoMuted) {
  961. return isVideoMuted && (track.isAudioTrack() || track.isMuted());
  962. }, true);
  963. };
  964. /*
  965. * @returns {???} The latest statistics reported by this participant (i.e. info used to populate the GSM bars)
  966. * TODO: do we expose this or handle it internally?
  967. */
  968. JitsiParticipant.prototype.getLatestStats = function() {
  969. };
  970. /**
  971. * @returns {String} The role of this participant.
  972. */
  973. JitsiParticipant.prototype.getRole = function() {
  974. return this._role;
  975. };
  976. /*
  977. * @returns {Boolean} Whether this participant is the conference focus (i.e. jicofo).
  978. */
  979. JitsiParticipant.prototype.isFocus = function() {
  980. };
  981. /*
  982. * @returns {Boolean} Whether this participant is a conference recorder (i.e. jirecon).
  983. */
  984. JitsiParticipant.prototype.isRecorder = function() {
  985. };
  986. /*
  987. * @returns {Boolean} Whether this participant is a SIP gateway (i.e. jigasi).
  988. */
  989. JitsiParticipant.prototype.isSipGateway = function() {
  990. };
  991. /**
  992. * @returns {Boolean} Whether this participant is currently sharing their screen.
  993. */
  994. JitsiParticipant.prototype.isScreenSharing = function() {
  995. };
  996. /**
  997. * @returns {String} The user agent of this participant (i.e. browser userAgent string).
  998. */
  999. JitsiParticipant.prototype.getUserAgent = function() {
  1000. };
  1001. /**
  1002. * Kicks the participant from the conference (requires certain privileges).
  1003. */
  1004. JitsiParticipant.prototype.kick = function() {
  1005. };
  1006. /**
  1007. * Asks this participant to mute themselves.
  1008. */
  1009. JitsiParticipant.prototype.askToMute = function() {
  1010. };
  1011. JitsiParticipant.prototype.supportsDTMF = function () {
  1012. return this._supportsDTMF;
  1013. };
  1014. module.exports = JitsiParticipant;
  1015. },{}],9:[function(require,module,exports){
  1016. module.exports = {
  1017. /**
  1018. * Returns JitsiTrackErrors based on the error object passed by GUM
  1019. * @param error the error
  1020. * @param {Object} options the options object given to GUM.
  1021. */
  1022. parseError: function (error, options) {
  1023. options = options || {};
  1024. if (typeof error == "object" && error.constraintName && error.name
  1025. && (error.name == "ConstraintNotSatisfiedError" ||
  1026. error.name == "OverconstrainedError") &&
  1027. (error.constraintName == "minWidth" ||
  1028. error.constraintName == "maxWidth" ||
  1029. error.constraintName == "minHeight" ||
  1030. error.constraintName == "maxHeight") &&
  1031. options.devices.indexOf("video") !== -1) {
  1032. return this.UNSUPPORTED_RESOLUTION;
  1033. } else {
  1034. return this.GENERAL;
  1035. }
  1036. },
  1037. UNSUPPORTED_RESOLUTION: "gum.unsupported_resolution",
  1038. GENERAL: "gum.general"
  1039. };
  1040. },{}],10:[function(require,module,exports){
  1041. var JitsiTrackEvents = {
  1042. /**
  1043. * A media track mute status was changed.
  1044. */
  1045. TRACK_MUTE_CHANGED: "track.trackMuteChanged",
  1046. /**
  1047. * Audio levels of a this track was changed.
  1048. */
  1049. TRACK_AUDIO_LEVEL_CHANGED: "track.audioLevelsChanged",
  1050. /**
  1051. * The media track was removed to the conference.
  1052. */
  1053. TRACK_STOPPED: "track.stopped"
  1054. };
  1055. module.exports = JitsiTrackEvents;
  1056. },{}],11:[function(require,module,exports){
  1057. (function (__filename){
  1058. var logger = require("jitsi-meet-logger").getLogger(__filename);
  1059. function JitsiDTMFManager (localAudio, peerConnection) {
  1060. var tracks = localAudio._getTracks();
  1061. if (!tracks.length) {
  1062. throw new Error("Failed to initialize DTMFSender: no audio track.");
  1063. }
  1064. this.dtmfSender = peerConnection.peerconnection.createDTMFSender(tracks[0]);
  1065. logger.debug("Initialized DTMFSender");
  1066. }
  1067. JitsiDTMFManager.prototype.sendTones = function (tones, duration, pause) {
  1068. this.dtmfSender.insertDTMF(tones, (duration || 200), (pause || 200));
  1069. };
  1070. }).call(this,"/modules/DTMF/JitsiDTMFManager.js")
  1071. },{"jitsi-meet-logger":47}],12:[function(require,module,exports){
  1072. (function (__filename){
  1073. /* global config, APP, Strophe */
  1074. // cache datachannels to avoid garbage collection
  1075. // https://code.google.com/p/chromium/issues/detail?id=405545
  1076. var logger = require("jitsi-meet-logger").getLogger(__filename);
  1077. var RTCEvents = require("../../service/RTC/RTCEvents");
  1078. /**
  1079. * Binds "ondatachannel" event listener to given PeerConnection instance.
  1080. * @param peerConnection WebRTC peer connection instance.
  1081. */
  1082. function DataChannels(peerConnection, emitter) {
  1083. peerConnection.ondatachannel = this.onDataChannel.bind(this);
  1084. this.eventEmitter = emitter;
  1085. this._dataChannels = [];
  1086. // Sample code for opening new data channel from Jitsi Meet to the bridge.
  1087. // Although it's not a requirement to open separate channels from both bridge
  1088. // and peer as single channel can be used for sending and receiving data.
  1089. // So either channel opened by the bridge or the one opened here is enough
  1090. // for communication with the bridge.
  1091. /*var dataChannelOptions =
  1092. {
  1093. reliable: true
  1094. };
  1095. var dataChannel
  1096. = peerConnection.createDataChannel("myChannel", dataChannelOptions);
  1097. // Can be used only when is in open state
  1098. dataChannel.onopen = function ()
  1099. {
  1100. dataChannel.send("My channel !!!");
  1101. };
  1102. dataChannel.onmessage = function (event)
  1103. {
  1104. var msgData = event.data;
  1105. logger.info("Got My Data Channel Message:", msgData, dataChannel);
  1106. };*/
  1107. };
  1108. /**
  1109. * Callback triggered by PeerConnection when new data channel is opened
  1110. * on the bridge.
  1111. * @param event the event info object.
  1112. */
  1113. DataChannels.prototype.onDataChannel = function (event) {
  1114. var dataChannel = event.channel;
  1115. var self = this;
  1116. dataChannel.onopen = function () {
  1117. logger.info("Data channel opened by the Videobridge!", dataChannel);
  1118. // Code sample for sending string and/or binary data
  1119. // Sends String message to the bridge
  1120. //dataChannel.send("Hello bridge!");
  1121. // Sends 12 bytes binary message to the bridge
  1122. //dataChannel.send(new ArrayBuffer(12));
  1123. self.eventEmitter.emit(RTCEvents.DATA_CHANNEL_OPEN);
  1124. };
  1125. dataChannel.onerror = function (error) {
  1126. logger.error("Data Channel Error:", error, dataChannel);
  1127. };
  1128. dataChannel.onmessage = function (event) {
  1129. var data = event.data;
  1130. // JSON
  1131. var obj;
  1132. try {
  1133. obj = JSON.parse(data);
  1134. }
  1135. catch (e) {
  1136. logger.error(
  1137. "Failed to parse data channel message as JSON: ",
  1138. data,
  1139. dataChannel);
  1140. }
  1141. if (('undefined' !== typeof(obj)) && (null !== obj)) {
  1142. var colibriClass = obj.colibriClass;
  1143. if ("DominantSpeakerEndpointChangeEvent" === colibriClass) {
  1144. // Endpoint ID from the Videobridge.
  1145. var dominantSpeakerEndpoint = obj.dominantSpeakerEndpoint;
  1146. logger.info(
  1147. "Data channel new dominant speaker event: ",
  1148. dominantSpeakerEndpoint);
  1149. self.eventEmitter.emit(RTCEvents.DOMINANTSPEAKER_CHANGED, dominantSpeakerEndpoint);
  1150. }
  1151. else if ("InLastNChangeEvent" === colibriClass) {
  1152. var oldValue = obj.oldValue;
  1153. var newValue = obj.newValue;
  1154. // Make sure that oldValue and newValue are of type boolean.
  1155. var type;
  1156. if ((type = typeof oldValue) !== 'boolean') {
  1157. if (type === 'string') {
  1158. oldValue = (oldValue == "true");
  1159. } else {
  1160. oldValue = new Boolean(oldValue).valueOf();
  1161. }
  1162. }
  1163. if ((type = typeof newValue) !== 'boolean') {
  1164. if (type === 'string') {
  1165. newValue = (newValue == "true");
  1166. } else {
  1167. newValue = new Boolean(newValue).valueOf();
  1168. }
  1169. }
  1170. self.eventEmitter.emit(RTCEvents.LASTN_CHANGED, oldValue, newValue);
  1171. }
  1172. else if ("LastNEndpointsChangeEvent" === colibriClass) {
  1173. // The new/latest list of last-n endpoint IDs.
  1174. var lastNEndpoints = obj.lastNEndpoints;
  1175. // The list of endpoint IDs which are entering the list of
  1176. // last-n at this time i.e. were not in the old list of last-n
  1177. // endpoint IDs.
  1178. var endpointsEnteringLastN = obj.endpointsEnteringLastN;
  1179. logger.info(
  1180. "Data channel new last-n event: ",
  1181. lastNEndpoints, endpointsEnteringLastN, obj);
  1182. self.eventEmitter.emit(RTCEvents.LASTN_ENDPOINT_CHANGED,
  1183. lastNEndpoints, endpointsEnteringLastN, obj);
  1184. }
  1185. else {
  1186. logger.debug("Data channel JSON-formatted message: ", obj);
  1187. // The received message appears to be appropriately formatted
  1188. // (i.e. is a JSON object which assigns a value to the mandatory
  1189. // property colibriClass) so don't just swallow it, expose it to
  1190. // public consumption.
  1191. self.eventEmitter.emit("rtc.datachannel." + colibriClass, obj);
  1192. }
  1193. }
  1194. };
  1195. dataChannel.onclose = function () {
  1196. logger.info("The Data Channel closed", dataChannel);
  1197. var idx = self._dataChannels.indexOf(dataChannel);
  1198. if (idx > -1)
  1199. self._dataChannels = self._dataChannels.splice(idx, 1);
  1200. };
  1201. this._dataChannels.push(dataChannel);
  1202. };
  1203. DataChannels.prototype.handleSelectedEndpointEvent = function (userResource) {
  1204. this._onXXXEndpointChanged("selected", userResource);
  1205. }
  1206. DataChannels.prototype.handlePinnedEndpointEvent = function (userResource) {
  1207. this._onXXXEndpointChanged("pinnned", userResource);
  1208. }
  1209. /**
  1210. * Notifies Videobridge about a change in the value of a specific
  1211. * endpoint-related property such as selected endpoint and pinnned endpoint.
  1212. *
  1213. * @param xxx the name of the endpoint-related property whose value changed
  1214. * @param userResource the new value of the endpoint-related property after the
  1215. * change
  1216. */
  1217. DataChannels.prototype._onXXXEndpointChanged = function (xxx, userResource) {
  1218. // Derive the correct words from xxx such as selected and Selected, pinned
  1219. // and Pinned.
  1220. var head = xxx.charAt(0);
  1221. var tail = xxx.substring(1);
  1222. var lower = head.toLowerCase() + tail;
  1223. var upper = head.toUpperCase() + tail;
  1224. // Notify Videobridge about the specified endpoint change.
  1225. console.log(lower + ' endpoint changed: ', userResource);
  1226. this._some(function (dataChannel) {
  1227. if (dataChannel.readyState == 'open') {
  1228. console.log(
  1229. 'sending ' + lower
  1230. + ' endpoint changed notification to the bridge: ',
  1231. userResource);
  1232. var jsonObject = {};
  1233. jsonObject.colibriClass = (upper + 'EndpointChangedEvent');
  1234. jsonObject[lower + "Endpoint"]
  1235. = (userResource ? userResource : null);
  1236. dataChannel.send(JSON.stringify(jsonObject));
  1237. return true;
  1238. }
  1239. });
  1240. }
  1241. DataChannels.prototype._some = function (callback, thisArg) {
  1242. var dataChannels = this._dataChannels;
  1243. if (dataChannels && dataChannels.length !== 0) {
  1244. if (thisArg)
  1245. return dataChannels.some(callback, thisArg);
  1246. else
  1247. return dataChannels.some(callback);
  1248. } else {
  1249. return false;
  1250. }
  1251. }
  1252. module.exports = DataChannels;
  1253. }).call(this,"/modules/RTC/DataChannels.js")
  1254. },{"../../service/RTC/RTCEvents":79,"jitsi-meet-logger":47}],13:[function(require,module,exports){
  1255. var JitsiTrack = require("./JitsiTrack");
  1256. var RTCBrowserType = require("./RTCBrowserType");
  1257. var JitsiTrackEvents = require('../../JitsiTrackEvents');
  1258. var RTC = require("./RTCUtils");
  1259. /**
  1260. * Represents a single media track (either audio or video).
  1261. * @constructor
  1262. */
  1263. function JitsiLocalTrack(stream, videoType,
  1264. resolution)
  1265. {
  1266. this.videoType = videoType;
  1267. this.dontFireRemoveEvent = false;
  1268. this.resolution = resolution;
  1269. this.startMuted = false;
  1270. var self = this;
  1271. JitsiTrack.call(this, null, stream,
  1272. function () {
  1273. if(!this.dontFireRemoveEvent)
  1274. this.eventEmitter.emit(
  1275. JitsiTrackEvents.TRACK_STOPPED);
  1276. this.dontFireRemoveEvent = false;
  1277. }.bind(this));
  1278. }
  1279. JitsiLocalTrack.prototype = Object.create(JitsiTrack.prototype);
  1280. JitsiLocalTrack.prototype.constructor = JitsiLocalTrack;
  1281. /**
  1282. * Mutes / unmutes the track.
  1283. * @param mute {boolean} if true the track will be muted. Otherwise the track will be unmuted.
  1284. */
  1285. JitsiLocalTrack.prototype._setMute = function (mute) {
  1286. if(!this.rtc) {
  1287. this.startMuted = mute;
  1288. return;
  1289. }
  1290. var isAudio = this.type === JitsiTrack.AUDIO;
  1291. this.dontFireRemoveEvent = false;
  1292. if ((window.location.protocol != "https:") ||
  1293. (isAudio) || this.videoType === "desktop" ||
  1294. // FIXME FF does not support 'removeStream' method used to mute
  1295. RTCBrowserType.isFirefox()) {
  1296. var tracks = this._getTracks();
  1297. for (var idx = 0; idx < tracks.length; idx++) {
  1298. tracks[idx].enabled = !mute;
  1299. }
  1300. if(isAudio)
  1301. this.rtc.room.setAudioMute(mute);
  1302. else
  1303. this.rtc.room.setVideoMute(mute);
  1304. this.eventEmitter.emit(JitsiTrackEvents.TRACK_MUTE_CHANGED);
  1305. } else {
  1306. if (mute) {
  1307. this.dontFireRemoveEvent = true;
  1308. this.rtc.room.removeStream(this.stream, function () {});
  1309. RTC.stopMediaStream(this.stream);
  1310. if(isAudio)
  1311. this.rtc.room.setAudioMute(mute);
  1312. else
  1313. this.rtc.room.setVideoMute(mute);
  1314. this.stream = null;
  1315. this.eventEmitter.emit(JitsiTrackEvents.TRACK_MUTE_CHANGED);
  1316. //FIXME: Maybe here we should set the SRC for the containers to something
  1317. } else {
  1318. var self = this;
  1319. RTC.obtainAudioAndVideoPermissions({
  1320. devices: (isAudio ? ["audio"] : ["video"]),
  1321. resolution: self.resolution})
  1322. .then(function (streams) {
  1323. var stream = null;
  1324. for(var i = 0; i < streams.length; i++) {
  1325. stream = streams[i];
  1326. if(stream.type === self.type) {
  1327. self.stream = stream.stream;
  1328. self.videoType = stream.videoType;
  1329. break;
  1330. }
  1331. }
  1332. if(!stream)
  1333. return;
  1334. for(var i = 0; i < self.containers.length; i++)
  1335. {
  1336. RTC.attachMediaStream(self.containers[i], self.stream);
  1337. }
  1338. self.rtc.room.addStream(stream.stream,
  1339. function () {
  1340. if(isAudio)
  1341. self.rtc.room.setAudioMute(mute);
  1342. else
  1343. self.rtc.room.setVideoMute(mute);
  1344. self.eventEmitter.emit(
  1345. JitsiTrackEvents.TRACK_MUTE_CHANGED);
  1346. });
  1347. });
  1348. }
  1349. }
  1350. }
  1351. /**
  1352. * Stops sending the media track. And removes it from the HTML.
  1353. * NOTE: Works for local tracks only.
  1354. */
  1355. JitsiLocalTrack.prototype.stop = function () {
  1356. if(!this.stream)
  1357. return;
  1358. if(this.rtc)
  1359. this.rtc.room.removeStream(this.stream, function () {});
  1360. RTC.stopMediaStream(this.stream);
  1361. this.detach();
  1362. }
  1363. /**
  1364. * Returns <tt>true</tt> - if the stream is muted
  1365. * and <tt>false</tt> otherwise.
  1366. * @returns {boolean} <tt>true</tt> - if the stream is muted
  1367. * and <tt>false</tt> otherwise.
  1368. */
  1369. JitsiLocalTrack.prototype.isMuted = function () {
  1370. if (!this.stream)
  1371. return true;
  1372. var tracks = [];
  1373. var isAudio = this.type === JitsiTrack.AUDIO;
  1374. if (isAudio) {
  1375. tracks = this.stream.getAudioTracks();
  1376. } else {
  1377. if (!this.isActive())
  1378. return true;
  1379. tracks = this.stream.getVideoTracks();
  1380. }
  1381. for (var idx = 0; idx < tracks.length; idx++) {
  1382. if(tracks[idx].enabled)
  1383. return false;
  1384. }
  1385. return true;
  1386. };
  1387. /**
  1388. * Private method. Updates rtc property of the track.
  1389. * @param rtc the rtc instance.
  1390. */
  1391. JitsiLocalTrack.prototype._setRTC = function (rtc) {
  1392. this.rtc = rtc;
  1393. };
  1394. /**
  1395. * Return true;
  1396. */
  1397. JitsiLocalTrack.prototype.isLocal = function () {
  1398. return true;
  1399. }
  1400. module.exports = JitsiLocalTrack;
  1401. },{"../../JitsiTrackEvents":10,"./JitsiTrack":15,"./RTCBrowserType":17,"./RTCUtils":18}],14:[function(require,module,exports){
  1402. var JitsiTrack = require("./JitsiTrack");
  1403. var JitsiTrackEvents = require("../../JitsiTrackEvents");
  1404. /**
  1405. * Represents a single media track (either audio or video).
  1406. * @param RTC the rtc instance.
  1407. * @param data object with the stream and some details about it(participant id, video type, etc.)
  1408. * @param sid sid for the Media Stream
  1409. * @param ssrc ssrc for the Media Stream
  1410. * @param eventEmitter the event emitter
  1411. * @constructor
  1412. */
  1413. function JitsiRemoteTrack(RTC, data, sid, ssrc) {
  1414. JitsiTrack.call(this, RTC, data.stream,
  1415. function () {
  1416. this.eventEmitter.emit(JitsiTrackEvents.TRACK_STOPPED);
  1417. }.bind(this));
  1418. this.rtc = RTC;
  1419. this.sid = sid;
  1420. this.stream = data.stream;
  1421. this.peerjid = data.peerjid;
  1422. this.videoType = data.videoType;
  1423. this.ssrc = ssrc;
  1424. this.muted = false;
  1425. if((this.type === JitsiTrack.AUDIO && data.audiomuted)
  1426. || (this.type === JitsiTrack.VIDEO && data.videomuted)) {
  1427. this.muted = true;
  1428. }
  1429. }
  1430. JitsiRemoteTrack.prototype = Object.create(JitsiTrack.prototype);
  1431. JitsiRemoteTrack.prototype.constructor = JitsiRemoteTrack;
  1432. /**
  1433. * Sets current muted status and fires an events for the change.
  1434. * @param value the muted status.
  1435. */
  1436. JitsiRemoteTrack.prototype.setMute = function (value) {
  1437. this.stream.muted = value;
  1438. this.muted = value;
  1439. this.eventEmitter.emit(JitsiTrackEvents.TRACK_MUTE_CHANGED);
  1440. };
  1441. /**
  1442. * Returns the current muted status of the track.
  1443. * @returns {boolean|*|JitsiRemoteTrack.muted} <tt>true</tt> if the track is muted and <tt>false</tt> otherwise.
  1444. */
  1445. JitsiRemoteTrack.prototype.isMuted = function () {
  1446. return this.muted;
  1447. };
  1448. /**
  1449. * Returns the participant id which owns the track.
  1450. * @returns {string} the id of the participants.
  1451. */
  1452. JitsiRemoteTrack.prototype.getParticipantId = function() {
  1453. return Strophe.getResourceFromJid(this.peerjid);
  1454. };
  1455. /**
  1456. * Return false;
  1457. */
  1458. JitsiRemoteTrack.prototype.isLocal = function () {
  1459. return false;
  1460. };
  1461. delete JitsiRemoteTrack.prototype.stop;
  1462. delete JitsiRemoteTrack.prototype.start;
  1463. module.exports = JitsiRemoteTrack;
  1464. },{"../../JitsiTrackEvents":10,"./JitsiTrack":15}],15:[function(require,module,exports){
  1465. var RTCBrowserType = require("./RTCBrowserType");
  1466. var JitsiTrackEvents = require("../../JitsiTrackEvents");
  1467. var EventEmitter = require("events");
  1468. /**
  1469. * This implements 'onended' callback normally fired by WebRTC after the stream
  1470. * is stopped. There is no such behaviour yet in FF, so we have to add it.
  1471. * @param jitsiTrack our track object holding the original WebRTC stream object
  1472. * to which 'onended' handling will be added.
  1473. */
  1474. function implementOnEndedHandling(jitsiTrack) {
  1475. var stream = jitsiTrack.getOriginalStream();
  1476. var originalStop = stream.stop;
  1477. stream.stop = function () {
  1478. originalStop.apply(stream);
  1479. if (jitsiTrack.isActive()) {
  1480. stream.onended();
  1481. }
  1482. };
  1483. }
  1484. /**
  1485. * Adds onended/oninactive handler to a MediaStream.
  1486. * @param mediaStream a MediaStream to attach onended/oninactive handler
  1487. * @param handler the handler
  1488. */
  1489. function addMediaStreamInactiveHandler(mediaStream, handler) {
  1490. if(RTCBrowserType.isTemasysPluginUsed()) {
  1491. // themasys
  1492. //FIXME: Seems that not working properly.
  1493. if(mediaStream.onended) {
  1494. mediaStream.onended = handler;
  1495. } else if(mediaStream.addEventListener) {
  1496. mediaStream.addEventListener('ended', function () {
  1497. handler(mediaStream);
  1498. });
  1499. } else if(mediaStream.attachEvent) {
  1500. mediaStream.attachEvent('ended', function () {
  1501. handler(mediaStream);
  1502. });
  1503. }
  1504. }
  1505. else {
  1506. if(typeof mediaStream.active !== "undefined")
  1507. mediaStream.oninactive = handler;
  1508. else
  1509. mediaStream.onended = handler;
  1510. }
  1511. }
  1512. /**
  1513. * Represents a single media track (either audio or video).
  1514. * @constructor
  1515. * @param rtc the rtc instance
  1516. * @param stream the stream
  1517. * @param streamInactiveHandler the function that will handle
  1518. * onended/oninactive events of the stream.
  1519. */
  1520. function JitsiTrack(rtc, stream, streamInactiveHandler)
  1521. {
  1522. /**
  1523. * Array with the HTML elements that are displaying the streams.
  1524. * @type {Array}
  1525. */
  1526. this.containers = [];
  1527. this.rtc = rtc;
  1528. this.stream = stream;
  1529. this.eventEmitter = new EventEmitter();
  1530. this.audioLevel = -1;
  1531. this.type = (this.stream.getVideoTracks().length > 0)?
  1532. JitsiTrack.VIDEO : JitsiTrack.AUDIO;
  1533. if(this.type == "audio") {
  1534. this._getTracks = function () {
  1535. return this.stream.getAudioTracks();
  1536. }.bind(this);
  1537. } else {
  1538. this._getTracks = function () {
  1539. return this.stream.getVideoTracks();
  1540. }.bind(this);
  1541. }
  1542. if (RTCBrowserType.isFirefox() && this.stream) {
  1543. implementOnEndedHandling(this);
  1544. }
  1545. if(stream)
  1546. addMediaStreamInactiveHandler(stream, streamInactiveHandler);
  1547. }
  1548. /**
  1549. * JitsiTrack video type.
  1550. * @type {string}
  1551. */
  1552. JitsiTrack.VIDEO = "video";
  1553. /**
  1554. * JitsiTrack audio type.
  1555. * @type {string}
  1556. */
  1557. JitsiTrack.AUDIO = "audio";
  1558. /**
  1559. * Returns the type (audio or video) of this track.
  1560. */
  1561. JitsiTrack.prototype.getType = function() {
  1562. return this.type;
  1563. };
  1564. /**
  1565. * Check if this is audiotrack.
  1566. */
  1567. JitsiTrack.prototype.isAudioTrack = function () {
  1568. return this.getType() === JitsiTrack.AUDIO;
  1569. };
  1570. /**
  1571. * Check if this is videotrack.
  1572. */
  1573. JitsiTrack.prototype.isVideoTrack = function () {
  1574. return this.getType() === JitsiTrack.VIDEO;
  1575. };
  1576. /**
  1577. * Returns the RTCMediaStream from the browser (?).
  1578. */
  1579. JitsiTrack.prototype.getOriginalStream = function() {
  1580. return this.stream;
  1581. }
  1582. /**
  1583. * Mutes the track.
  1584. */
  1585. JitsiTrack.prototype.mute = function () {
  1586. this._setMute(true);
  1587. }
  1588. /**
  1589. * Unmutes the stream.
  1590. */
  1591. JitsiTrack.prototype.unmute = function () {
  1592. this._setMute(false);
  1593. }
  1594. /**
  1595. * Attaches the MediaStream of this track to an HTML container (?).
  1596. * Adds the container to the list of containers that are displaying the track.
  1597. * @param container the HTML container
  1598. */
  1599. JitsiTrack.prototype.attach = function (container) {
  1600. if(this.stream)
  1601. require("./RTCUtils").attachMediaStream(container, this.stream);
  1602. this.containers.push(container);
  1603. }
  1604. /**
  1605. * Removes the track from the passed HTML container.
  1606. * @param container the HTML container. If <tt>null</tt> all containers are removed.
  1607. */
  1608. JitsiTrack.prototype.detach = function (container) {
  1609. for(var i = 0; i < this.containers.length; i++)
  1610. {
  1611. if(this.containers[i].is(container))
  1612. {
  1613. this.containers.splice(i,1);
  1614. }
  1615. if(!container)
  1616. {
  1617. this.containers[i].find(">video").remove();
  1618. }
  1619. }
  1620. if(container)
  1621. $(container).find(">video").remove();
  1622. }
  1623. /**
  1624. * Stops sending the media track. And removes it from the HTML.
  1625. * NOTE: Works for local tracks only.
  1626. */
  1627. JitsiTrack.prototype.stop = function () {
  1628. }
  1629. /**
  1630. * Returns true if this is a video track and the source of the video is a
  1631. * screen capture as opposed to a camera.
  1632. */
  1633. JitsiTrack.prototype.isScreenSharing = function(){
  1634. }
  1635. /**
  1636. * Returns id of the track.
  1637. * @returns {string} id of the track or null if this is fake track.
  1638. */
  1639. JitsiTrack.prototype.getId = function () {
  1640. var tracks = this.stream.getTracks();
  1641. if(!tracks || tracks.length === 0)
  1642. return null;
  1643. return tracks[0].id;
  1644. };
  1645. /**
  1646. * Checks whether the MediaStream is avtive/not ended.
  1647. * When there is no check for active we don't have information and so
  1648. * will return that stream is active (in case of FF).
  1649. * @returns {boolean} whether MediaStream is active.
  1650. */
  1651. JitsiTrack.prototype.isActive = function () {
  1652. if((typeof this.stream.active !== "undefined"))
  1653. return this.stream.active;
  1654. else
  1655. return true;
  1656. };
  1657. /**
  1658. * Attaches a handler for events(For example - "audio level changed".).
  1659. * All possible event are defined in JitsiTrackEvents.
  1660. * @param eventId the event ID.
  1661. * @param handler handler for the event.
  1662. */
  1663. JitsiTrack.prototype.on = function (eventId, handler) {
  1664. if(this.eventEmitter)
  1665. this.eventEmitter.on(eventId, handler);
  1666. }
  1667. /**
  1668. * Removes event listener
  1669. * @param eventId the event ID.
  1670. * @param [handler] optional, the specific handler to unbind
  1671. */
  1672. JitsiTrack.prototype.off = function (eventId, handler) {
  1673. if(this.eventEmitter)
  1674. this.eventEmitter.removeListener(eventId, handler);
  1675. }
  1676. // Common aliases for event emitter
  1677. JitsiTrack.prototype.addEventListener = JitsiTrack.prototype.on;
  1678. JitsiTrack.prototype.removeEventListener = JitsiTrack.prototype.off;
  1679. /**
  1680. * Sets the audio level for the stream
  1681. * @param audioLevel the new audio level
  1682. */
  1683. JitsiTrack.prototype.setAudioLevel = function (audioLevel) {
  1684. if(this.audioLevel !== audioLevel) {
  1685. this.eventEmitter.emit(JitsiTrackEvents.TRACK_AUDIO_LEVEL_CHANGED,
  1686. audioLevel);
  1687. this.audioLevel = audioLevel;
  1688. }
  1689. }
  1690. module.exports = JitsiTrack;
  1691. },{"../../JitsiTrackEvents":10,"./RTCBrowserType":17,"./RTCUtils":18,"events":43}],16:[function(require,module,exports){
  1692. /* global APP */
  1693. var EventEmitter = require("events");
  1694. var RTCBrowserType = require("./RTCBrowserType");
  1695. var RTCUtils = require("./RTCUtils.js");
  1696. var JitsiTrack = require("./JitsiTrack");
  1697. var JitsiLocalTrack = require("./JitsiLocalTrack.js");
  1698. var DataChannels = require("./DataChannels");
  1699. var JitsiRemoteTrack = require("./JitsiRemoteTrack.js");
  1700. var DesktopSharingEventTypes
  1701. = require("../../service/desktopsharing/DesktopSharingEventTypes");
  1702. var MediaStreamType = require("../../service/RTC/MediaStreamTypes");
  1703. var RTCEvents = require("../../service/RTC/RTCEvents.js");
  1704. function createLocalTracks(streams) {
  1705. var newStreams = []
  1706. for (var i = 0; i < streams.length; i++) {
  1707. var localStream = new JitsiLocalTrack(streams[i].stream,
  1708. streams[i].videoType, streams[i].resolution);
  1709. newStreams.push(localStream);
  1710. if (streams[i].isMuted === true)
  1711. localStream.setMute(true);
  1712. }
  1713. return newStreams;
  1714. }
  1715. function RTC(room, options) {
  1716. this.room = room;
  1717. this.localStreams = [];
  1718. //FIXME: we should start removing those streams.
  1719. //FIXME: We should support multiple streams per jid.
  1720. this.remoteStreams = {};
  1721. this.localAudio = null;
  1722. this.localVideo = null;
  1723. this.eventEmitter = new EventEmitter();
  1724. var self = this;
  1725. this.options = options || {};
  1726. room.addPresenceListener("videomuted", function (values, from) {
  1727. if(self.remoteStreams[from]) {
  1728. self.remoteStreams[from][JitsiTrack.VIDEO].setMute(values.value == "true");
  1729. }
  1730. });
  1731. room.addPresenceListener("audiomuted", function (values, from) {
  1732. if(self.remoteStreams[from]) {
  1733. self.remoteStreams[from][JitsiTrack.AUDIO].setMute(values.value == "true");
  1734. }
  1735. });
  1736. }
  1737. /**
  1738. * Creates the local MediaStreams.
  1739. * @param {Object} [options] optional parameters
  1740. * @param {Array} options.devices the devices that will be requested
  1741. * @param {string} options.resolution resolution constraints
  1742. * @param {bool} options.dontCreateJitsiTrack if <tt>true</tt> objects with the following structure {stream: the Media Stream,
  1743. * type: "audio" or "video", videoType: "camera" or "desktop"}
  1744. * will be returned trough the Promise, otherwise JitsiTrack objects will be returned.
  1745. * @param {string} options.cameraDeviceId
  1746. * @param {string} options.micDeviceId
  1747. * @returns {*} Promise object that will receive the new JitsiTracks
  1748. */
  1749. RTC.obtainAudioAndVideoPermissions = function (options) {
  1750. return RTCUtils.obtainAudioAndVideoPermissions(options).then(createLocalTracks);
  1751. }
  1752. RTC.prototype.onIncommingCall = function(event) {
  1753. if(this.options.config.openSctp)
  1754. this.dataChannels = new DataChannels(event.peerconnection, this.eventEmitter);
  1755. for(var i = 0; i < this.localStreams.length; i++)
  1756. if(this.localStreams[i])
  1757. {
  1758. this.room.addStream(this.localStreams[i].getOriginalStream(), function () {});
  1759. }
  1760. }
  1761. RTC.prototype.selectedEndpoint = function (id) {
  1762. if(this.dataChannels)
  1763. this.dataChannels.handleSelectedEndpointEvent(id);
  1764. }
  1765. RTC.prototype.pinEndpoint = function (id) {
  1766. if(this.dataChannels)
  1767. this.dataChannels.handlePinnedEndpointEvent(id);
  1768. }
  1769. RTC.prototype.addListener = function (type, listener) {
  1770. this.eventEmitter.on(type, listener);
  1771. };
  1772. RTC.prototype.removeListener = function (eventType, listener) {
  1773. this.eventEmitter.removeListener(eventType, listener);
  1774. };
  1775. RTC.addListener = function (eventType, listener) {
  1776. RTCUtils.addListener(eventType, listener);
  1777. }
  1778. RTC.removeListener = function (eventType, listener) {
  1779. RTCUtils.removeListener(eventType, listener)
  1780. }
  1781. RTC.isRTCReady = function () {
  1782. return RTCUtils.isRTCReady();
  1783. }
  1784. RTC.init = function (options) {
  1785. this.options = options || {};
  1786. return RTCUtils.init(this.options);
  1787. }
  1788. RTC.getDeviceAvailability = function () {
  1789. return RTCUtils.getDeviceAvailability();
  1790. }
  1791. RTC.prototype.addLocalStream = function (stream) {
  1792. this.localStreams.push(stream);
  1793. stream._setRTC(this);
  1794. if (stream.type == "audio") {
  1795. this.localAudio = stream;
  1796. } else {
  1797. this.localVideo = stream;
  1798. }
  1799. };
  1800. RTC.prototype.removeLocalStream = function (stream) {
  1801. for(var i = 0; i < this.localStreams.length; i++) {
  1802. if(this.localStreams[i].getOriginalStream() === stream) {
  1803. delete this.localStreams[i];
  1804. return;
  1805. }
  1806. }
  1807. };
  1808. RTC.prototype.createRemoteStream = function (data, sid, thessrc) {
  1809. var remoteStream = new JitsiRemoteTrack(this, data, sid, thessrc);
  1810. if(!data.peerjid)
  1811. return;
  1812. var jid = data.peerjid;
  1813. if(!this.remoteStreams[jid]) {
  1814. this.remoteStreams[jid] = {};
  1815. }
  1816. this.remoteStreams[jid][remoteStream.type]= remoteStream;
  1817. return remoteStream;
  1818. };
  1819. RTC.getPCConstraints = function () {
  1820. return RTCUtils.pc_constraints;
  1821. };
  1822. RTC.attachMediaStream = function (elSelector, stream) {
  1823. RTCUtils.attachMediaStream(elSelector, stream);
  1824. };
  1825. RTC.getStreamID = function (stream) {
  1826. return RTCUtils.getStreamID(stream);
  1827. };
  1828. RTC.getVideoSrc = function (element) {
  1829. return RTCUtils.getVideoSrc(element);
  1830. };
  1831. /**
  1832. * Returns true if retrieving the the list of input devices is supported and
  1833. * false if not.
  1834. */
  1835. RTC.isDeviceListAvailable = function () {
  1836. return RTCUtils.isDeviceListAvailable();
  1837. };
  1838. /**
  1839. * Returns true if changing the camera / microphone device is supported and
  1840. * false if not.
  1841. */
  1842. RTC.isDeviceChangeAvailable = function () {
  1843. return RTCUtils.isDeviceChangeAvailable();
  1844. }
  1845. /**
  1846. * Allows to receive list of available cameras/microphones.
  1847. * @param {function} callback would receive array of devices as an argument
  1848. */
  1849. RTC.enumerateDevices = function (callback) {
  1850. RTCUtils.enumerateDevices(callback);
  1851. };
  1852. RTC.setVideoSrc = function (element, src) {
  1853. RTCUtils.setVideoSrc(element, src);
  1854. };
  1855. /**
  1856. * A method to handle stopping of the stream.
  1857. * One point to handle the differences in various implementations.
  1858. * @param mediaStream MediaStream object to stop.
  1859. */
  1860. RTC.stopMediaStream = function (mediaStream) {
  1861. RTCUtils.stopMediaStream(mediaStream);
  1862. };
  1863. RTC.prototype.getVideoElementName = function () {
  1864. return RTCBrowserType.isTemasysPluginUsed() ? 'object' : 'video';
  1865. };
  1866. RTC.prototype.dispose = function() {
  1867. };
  1868. RTC.prototype.switchVideoStreams = function (newStream) {
  1869. this.localVideo.stream = newStream;
  1870. this.localStreams = [];
  1871. //in firefox we have only one stream object
  1872. if (this.localAudio.getOriginalStream() != newStream)
  1873. this.localStreams.push(this.localAudio);
  1874. this.localStreams.push(this.localVideo);
  1875. };
  1876. RTC.prototype.setAudioLevel = function (jid, audioLevel) {
  1877. if(this.remoteStreams[jid] && this.remoteStreams[jid][JitsiTrack.AUDIO])
  1878. this.remoteStreams[jid][JitsiTrack.AUDIO].setAudioLevel(audioLevel);
  1879. }
  1880. module.exports = RTC;
  1881. },{"../../service/RTC/MediaStreamTypes":78,"../../service/RTC/RTCEvents.js":79,"../../service/desktopsharing/DesktopSharingEventTypes":82,"./DataChannels":12,"./JitsiLocalTrack.js":13,"./JitsiRemoteTrack.js":14,"./JitsiTrack":15,"./RTCBrowserType":17,"./RTCUtils.js":18,"events":43}],17:[function(require,module,exports){
  1882. var currentBrowser;
  1883. var browserVersion;
  1884. var isAndroid;
  1885. var RTCBrowserType = {
  1886. RTC_BROWSER_CHROME: "rtc_browser.chrome",
  1887. RTC_BROWSER_OPERA: "rtc_browser.opera",
  1888. RTC_BROWSER_FIREFOX: "rtc_browser.firefox",
  1889. RTC_BROWSER_IEXPLORER: "rtc_browser.iexplorer",
  1890. RTC_BROWSER_SAFARI: "rtc_browser.safari",
  1891. getBrowserType: function () {
  1892. return currentBrowser;
  1893. },
  1894. isChrome: function () {
  1895. return currentBrowser === RTCBrowserType.RTC_BROWSER_CHROME;
  1896. },
  1897. isOpera: function () {
  1898. return currentBrowser === RTCBrowserType.RTC_BROWSER_OPERA;
  1899. },
  1900. isFirefox: function () {
  1901. return currentBrowser === RTCBrowserType.RTC_BROWSER_FIREFOX;
  1902. },
  1903. isIExplorer: function () {
  1904. return currentBrowser === RTCBrowserType.RTC_BROWSER_IEXPLORER;
  1905. },
  1906. isSafari: function () {
  1907. return currentBrowser === RTCBrowserType.RTC_BROWSER_SAFARI;
  1908. },
  1909. isTemasysPluginUsed: function () {
  1910. return RTCBrowserType.isIExplorer() || RTCBrowserType.isSafari();
  1911. },
  1912. getFirefoxVersion: function () {
  1913. return RTCBrowserType.isFirefox() ? browserVersion : null;
  1914. },
  1915. getChromeVersion: function () {
  1916. return RTCBrowserType.isChrome() ? browserVersion : null;
  1917. },
  1918. usesPlanB: function() {
  1919. return RTCBrowserType.isChrome() || RTCBrowserType.isOpera() ||
  1920. RTCBrowserType.isTemasysPluginUsed();
  1921. },
  1922. usesUnifiedPlan: function() {
  1923. return RTCBrowserType.isFirefox();
  1924. },
  1925. /**
  1926. * Whether the browser is running on an android device.
  1927. */
  1928. isAndroid: function() {
  1929. return isAndroid;
  1930. }
  1931. // Add version getters for other browsers when needed
  1932. };
  1933. // detectOpera() must be called before detectChrome() !!!
  1934. // otherwise Opera wil be detected as Chrome
  1935. function detectChrome() {
  1936. if (navigator.webkitGetUserMedia) {
  1937. currentBrowser = RTCBrowserType.RTC_BROWSER_CHROME;
  1938. var userAgent = navigator.userAgent.toLowerCase();
  1939. // We can assume that user agent is chrome, because it's
  1940. // enforced when 'ext' streaming method is set
  1941. var ver = parseInt(userAgent.match(/chrome\/(\d+)\./)[1], 10);
  1942. console.log("This appears to be Chrome, ver: " + ver);
  1943. return ver;
  1944. }
  1945. return null;
  1946. }
  1947. function detectOpera() {
  1948. var userAgent = navigator.userAgent;
  1949. if (userAgent.match(/Opera|OPR/)) {
  1950. currentBrowser = RTCBrowserType.RTC_BROWSER_OPERA;
  1951. var version = userAgent.match(/(Opera|OPR) ?\/?(\d+)\.?/)[2];
  1952. console.info("This appears to be Opera, ver: " + version);
  1953. return version;
  1954. }
  1955. return null;
  1956. }
  1957. function detectFirefox() {
  1958. if (navigator.mozGetUserMedia) {
  1959. currentBrowser = RTCBrowserType.RTC_BROWSER_FIREFOX;
  1960. var version = parseInt(
  1961. navigator.userAgent.match(/Firefox\/([0-9]+)\./)[1], 10);
  1962. console.log('This appears to be Firefox, ver: ' + version);
  1963. return version;
  1964. }
  1965. return null;
  1966. }
  1967. function detectSafari() {
  1968. if ((/^((?!chrome).)*safari/i.test(navigator.userAgent))) {
  1969. currentBrowser = RTCBrowserType.RTC_BROWSER_SAFARI;
  1970. console.info("This appears to be Safari");
  1971. // FIXME detect Safari version when needed
  1972. return 1;
  1973. }
  1974. return null;
  1975. }
  1976. function detectIE() {
  1977. var version;
  1978. var ua = window.navigator.userAgent;
  1979. var msie = ua.indexOf('MSIE ');
  1980. if (msie > 0) {
  1981. // IE 10 or older => return version number
  1982. version = parseInt(ua.substring(msie + 5, ua.indexOf('.', msie)), 10);
  1983. }
  1984. var trident = ua.indexOf('Trident/');
  1985. if (!version && trident > 0) {
  1986. // IE 11 => return version number
  1987. var rv = ua.indexOf('rv:');
  1988. version = parseInt(ua.substring(rv + 3, ua.indexOf('.', rv)), 10);
  1989. }
  1990. var edge = ua.indexOf('Edge/');
  1991. if (!version && edge > 0) {
  1992. // IE 12 => return version number
  1993. version = parseInt(ua.substring(edge + 5, ua.indexOf('.', edge)), 10);
  1994. }
  1995. if (version) {
  1996. currentBrowser = RTCBrowserType.RTC_BROWSER_IEXPLORER;
  1997. console.info("This appears to be IExplorer, ver: " + version);
  1998. }
  1999. return version;
  2000. }
  2001. function detectBrowser() {
  2002. var version;
  2003. var detectors = [
  2004. detectOpera,
  2005. detectChrome,
  2006. detectFirefox,
  2007. detectIE,
  2008. detectSafari
  2009. ];
  2010. // Try all browser detectors
  2011. for (var i = 0; i < detectors.length; i++) {
  2012. version = detectors[i]();
  2013. if (version)
  2014. return version;
  2015. }
  2016. console.error("Failed to detect browser type");
  2017. return undefined;
  2018. }
  2019. browserVersion = detectBrowser();
  2020. isAndroid = navigator.userAgent.indexOf('Android') != -1;
  2021. module.exports = RTCBrowserType;
  2022. },{}],18:[function(require,module,exports){
  2023. (function (__filename){
  2024. /* global config, require, attachMediaStream, getUserMedia,
  2025. RTCPeerConnection, RTCSessionDescription, RTCIceCandidate, MediaStreamTrack,
  2026. mozRTCPeerConnection, mozRTCSessionDescription, mozRTCIceCandidate,
  2027. webkitRTCPeerConnection, webkitMediaStream, webkitURL
  2028. */
  2029. /* jshint -W101 */
  2030. var logger = require("jitsi-meet-logger").getLogger(__filename);
  2031. var RTCBrowserType = require("./RTCBrowserType");
  2032. var Resolutions = require("../../service/RTC/Resolutions");
  2033. var RTCEvents = require("../../service/RTC/RTCEvents");
  2034. var AdapterJS = require("./adapter.screenshare");
  2035. var SDPUtil = require("../xmpp/SDPUtil");
  2036. var EventEmitter = require("events");
  2037. var screenObtainer = require("./ScreenObtainer");
  2038. var JitsiTrackErrors = require("../../JitsiTrackErrors");
  2039. var eventEmitter = new EventEmitter();
  2040. var devices = {
  2041. audio: true,
  2042. video: true
  2043. };
  2044. var rtcReady = false;
  2045. function setResolutionConstraints(constraints, resolution) {
  2046. var isAndroid = RTCBrowserType.isAndroid();
  2047. if (Resolutions[resolution]) {
  2048. constraints.video.mandatory.minWidth = Resolutions[resolution].width;
  2049. constraints.video.mandatory.minHeight = Resolutions[resolution].height;
  2050. }
  2051. else if (isAndroid) {
  2052. // FIXME can't remember if the purpose of this was to always request
  2053. // low resolution on Android ? if yes it should be moved up front
  2054. constraints.video.mandatory.minWidth = 320;
  2055. constraints.video.mandatory.minHeight = 240;
  2056. constraints.video.mandatory.maxFrameRate = 15;
  2057. }
  2058. if (constraints.video.mandatory.minWidth)
  2059. constraints.video.mandatory.maxWidth =
  2060. constraints.video.mandatory.minWidth;
  2061. if (constraints.video.mandatory.minHeight)
  2062. constraints.video.mandatory.maxHeight =
  2063. constraints.video.mandatory.minHeight;
  2064. }
  2065. /**
  2066. * @param {string[]} um required user media types
  2067. *
  2068. * @param {Object} [options={}] optional parameters
  2069. * @param {string} options.resolution
  2070. * @param {number} options.bandwidth
  2071. * @param {number} options.fps
  2072. * @param {string} options.desktopStream
  2073. * @param {string} options.cameraDeviceId
  2074. * @param {string} options.micDeviceId
  2075. * @param {bool} firefox_fake_device
  2076. */
  2077. function getConstraints(um, options) {
  2078. var constraints = {audio: false, video: false};
  2079. if (um.indexOf('video') >= 0) {
  2080. // same behaviour as true
  2081. constraints.video = { mandatory: {}, optional: [] };
  2082. if (options.cameraDeviceId) {
  2083. constraints.video.optional.push({
  2084. sourceId: options.cameraDeviceId
  2085. });
  2086. }
  2087. constraints.video.optional.push({ googLeakyBucket: true });
  2088. setResolutionConstraints(constraints, options.resolution);
  2089. }
  2090. if (um.indexOf('audio') >= 0) {
  2091. if (!RTCBrowserType.isFirefox()) {
  2092. // same behaviour as true
  2093. constraints.audio = { mandatory: {}, optional: []};
  2094. if (options.micDeviceId) {
  2095. constraints.audio.optional.push({
  2096. sourceId: options.micDeviceId
  2097. });
  2098. }
  2099. // if it is good enough for hangouts...
  2100. constraints.audio.optional.push(
  2101. {googEchoCancellation: true},
  2102. {googAutoGainControl: true},
  2103. {googNoiseSupression: true},
  2104. {googHighpassFilter: true},
  2105. {googNoisesuppression2: true},
  2106. {googEchoCancellation2: true},
  2107. {googAutoGainControl2: true}
  2108. );
  2109. } else {
  2110. if (options.micDeviceId) {
  2111. constraints.audio = {
  2112. mandatory: {},
  2113. optional: [{
  2114. sourceId: options.micDeviceId
  2115. }]};
  2116. } else {
  2117. constraints.audio = true;
  2118. }
  2119. }
  2120. }
  2121. if (um.indexOf('screen') >= 0) {
  2122. if (RTCBrowserType.isChrome()) {
  2123. constraints.video = {
  2124. mandatory: {
  2125. chromeMediaSource: "screen",
  2126. googLeakyBucket: true,
  2127. maxWidth: window.screen.width,
  2128. maxHeight: window.screen.height,
  2129. maxFrameRate: 3
  2130. },
  2131. optional: []
  2132. };
  2133. } else if (RTCBrowserType.isTemasysPluginUsed()) {
  2134. constraints.video = {
  2135. optional: [
  2136. {
  2137. sourceId: AdapterJS.WebRTCPlugin.plugin.screensharingKey
  2138. }
  2139. ]
  2140. };
  2141. } else if (RTCBrowserType.isFirefox()) {
  2142. constraints.video = {
  2143. mozMediaSource: "window",
  2144. mediaSource: "window"
  2145. };
  2146. } else {
  2147. logger.error(
  2148. "'screen' WebRTC media source is supported only in Chrome" +
  2149. " and with Temasys plugin");
  2150. }
  2151. }
  2152. if (um.indexOf('desktop') >= 0) {
  2153. constraints.video = {
  2154. mandatory: {
  2155. chromeMediaSource: "desktop",
  2156. chromeMediaSourceId: options.desktopStream,
  2157. googLeakyBucket: true,
  2158. maxWidth: window.screen.width,
  2159. maxHeight: window.screen.height,
  2160. maxFrameRate: 3
  2161. },
  2162. optional: []
  2163. };
  2164. }
  2165. if (options.bandwidth) {
  2166. if (!constraints.video) {
  2167. //same behaviour as true
  2168. constraints.video = {mandatory: {}, optional: []};
  2169. }
  2170. constraints.video.optional.push({bandwidth: options.bandwidth});
  2171. }
  2172. if (options.fps) {
  2173. // for some cameras it might be necessary to request 30fps
  2174. // so they choose 30fps mjpg over 10fps yuy2
  2175. if (!constraints.video) {
  2176. // same behaviour as true;
  2177. constraints.video = {mandatory: {}, optional: []};
  2178. }
  2179. constraints.video.mandatory.minFrameRate = options.fps;
  2180. }
  2181. // we turn audio for both audio and video tracks, the fake audio & video seems to work
  2182. // only when enabled in one getUserMedia call, we cannot get fake audio separate by fake video
  2183. // this later can be a problem with some of the tests
  2184. if(RTCBrowserType.isFirefox() && options.firefox_fake_device)
  2185. {
  2186. // seems to be fixed now, removing this experimental fix, as having
  2187. // multiple audio tracks brake the tests
  2188. //constraints.audio = true;
  2189. constraints.fake = true;
  2190. }
  2191. return constraints;
  2192. }
  2193. function setAvailableDevices(um, available) {
  2194. if (um.indexOf("video") != -1) {
  2195. devices.video = available;
  2196. }
  2197. if (um.indexOf("audio") != -1) {
  2198. devices.audio = available;
  2199. }
  2200. eventEmitter.emit(RTCEvents.AVAILABLE_DEVICES_CHANGED, devices);
  2201. }
  2202. // In case of IE we continue from 'onReady' callback
  2203. // passed to RTCUtils constructor. It will be invoked by Temasys plugin
  2204. // once it is initialized.
  2205. function onReady (options, GUM) {
  2206. rtcReady = true;
  2207. eventEmitter.emit(RTCEvents.RTC_READY, true);
  2208. screenObtainer.init(eventEmitter, options, GUM);
  2209. }
  2210. /**
  2211. * Apply function with arguments if function exists.
  2212. * Do nothing if function not provided.
  2213. * @param {function} [fn] function to apply
  2214. * @param {Array} [args=[]] arguments for function
  2215. */
  2216. function maybeApply(fn, args) {
  2217. if (fn) {
  2218. fn.apply(null, args || []);
  2219. }
  2220. }
  2221. var getUserMediaStatus = {
  2222. initialized: false,
  2223. callbacks: []
  2224. };
  2225. /**
  2226. * Wrap `getUserMedia` to allow others to know if it was executed at least
  2227. * once or not. Wrapper function uses `getUserMediaStatus` object.
  2228. * @param {Function} getUserMedia native function
  2229. * @returns {Function} wrapped function
  2230. */
  2231. function wrapGetUserMedia(getUserMedia) {
  2232. return function (constraints, successCallback, errorCallback) {
  2233. getUserMedia(constraints, function (stream) {
  2234. maybeApply(successCallback, [stream]);
  2235. if (!getUserMediaStatus.initialized) {
  2236. getUserMediaStatus.initialized = true;
  2237. getUserMediaStatus.callbacks.forEach(function (callback) {
  2238. callback();
  2239. });
  2240. getUserMediaStatus.callbacks.length = 0;
  2241. }
  2242. }, function (error) {
  2243. maybeApply(errorCallback, [error]);
  2244. });
  2245. };
  2246. }
  2247. /**
  2248. * Create stub device which equals to auto selected device.
  2249. * @param {string} kind if that should be `audio` or `video` device
  2250. * @returns {Object} stub device description in `enumerateDevices` format
  2251. */
  2252. function createAutoDeviceInfo(kind) {
  2253. return {
  2254. facing: null,
  2255. label: 'Auto',
  2256. kind: kind,
  2257. deviceId: '',
  2258. groupId: null
  2259. };
  2260. }
  2261. /**
  2262. * Execute function after getUserMedia was executed at least once.
  2263. * @param {Function} callback function to execute after getUserMedia
  2264. */
  2265. function afterUserMediaInitialized(callback) {
  2266. if (getUserMediaStatus.initialized) {
  2267. callback();
  2268. } else {
  2269. getUserMediaStatus.callbacks.push(callback);
  2270. }
  2271. }
  2272. /**
  2273. * Wrapper function which makes enumerateDevices to wait
  2274. * until someone executes getUserMedia first time.
  2275. * @param {Function} enumerateDevices native function
  2276. * @returns {Funtion} wrapped function
  2277. */
  2278. function wrapEnumerateDevices(enumerateDevices) {
  2279. return function (callback) {
  2280. // enumerate devices only after initial getUserMedia
  2281. afterUserMediaInitialized(function () {
  2282. enumerateDevices().then(function (devices) {
  2283. //add auto devices
  2284. devices.unshift(
  2285. createAutoDeviceInfo('audioinput'),
  2286. createAutoDeviceInfo('videoinput')
  2287. );
  2288. callback(devices);
  2289. }, function (err) {
  2290. console.error('cannot enumerate devices: ', err);
  2291. // return only auto devices
  2292. callback([createAutoDeviceInfo('audioInput'),
  2293. createAutoDeviceInfo('videoinput')]);
  2294. });
  2295. });
  2296. };
  2297. }
  2298. /**
  2299. * Use old MediaStreamTrack to get devices list and
  2300. * convert it to enumerateDevices format.
  2301. * @param {Function} callback function to call when received devices list.
  2302. */
  2303. function enumerateDevicesThroughMediaStreamTrack (callback) {
  2304. MediaStreamTrack.getSources(function (sources) {
  2305. var devices = sources.map(function (source) {
  2306. var kind = (source.kind || '').toLowerCase();
  2307. return {
  2308. facing: source.facing || null,
  2309. label: source.label,
  2310. kind: kind ? kind + 'input': null,
  2311. deviceId: source.id,
  2312. groupId: source.groupId || null
  2313. };
  2314. });
  2315. //add auto devices
  2316. devices.unshift(
  2317. createAutoDeviceInfo('audioinput'),
  2318. createAutoDeviceInfo('videoinput')
  2319. );
  2320. callback(devices);
  2321. });
  2322. }
  2323. function obtainDevices(options) {
  2324. if(!options.devices || options.devices.length === 0) {
  2325. return options.successCallback(options.streams || {});
  2326. }
  2327. var device = options.devices.splice(0, 1);
  2328. options.deviceGUM[device](function (stream) {
  2329. options.streams = options.streams || {};
  2330. options.streams[device] = stream;
  2331. obtainDevices(options);
  2332. },
  2333. function (error) {
  2334. logger.error(
  2335. "failed to obtain " + device + " stream - stop", error);
  2336. options.errorCallback(JitsiTrackErrors.parseError(error));
  2337. });
  2338. }
  2339. /**
  2340. * Handles the newly created Media Streams.
  2341. * @param streams the new Media Streams
  2342. * @param resolution the resolution of the video streams
  2343. * @returns {*[]} object that describes the new streams
  2344. */
  2345. function handleLocalStream(streams, resolution) {
  2346. var audioStream, videoStream, desktopStream, res = [];
  2347. // If this is FF, the stream parameter is *not* a MediaStream object, it's
  2348. // an object with two properties: audioStream, videoStream.
  2349. if (window.webkitMediaStream) {
  2350. var audioVideo = streams.audioVideo;
  2351. if (audioVideo) {
  2352. var audioTracks = audioVideo.getAudioTracks();
  2353. if(audioTracks.length) {
  2354. audioStream = new webkitMediaStream();
  2355. for (var i = 0; i < audioTracks.length; i++) {
  2356. audioStream.addTrack(audioTracks[i]);
  2357. }
  2358. }
  2359. var videoTracks = audioVideo.getVideoTracks();
  2360. if(videoTracks.length) {
  2361. videoStream = new webkitMediaStream();
  2362. for (var j = 0; j < videoTracks.length; j++) {
  2363. videoStream.addTrack(videoTracks[j]);
  2364. }
  2365. }
  2366. }
  2367. if (streams && streams.desktopStream)
  2368. desktopStream = streams.desktopStream;
  2369. }
  2370. else if (RTCBrowserType.isFirefox() || RTCBrowserType.isTemasysPluginUsed()) { // Firefox and Temasys plugin
  2371. if (streams && streams.audio)
  2372. audioStream = streams.audio;
  2373. if (streams && streams.video)
  2374. videoStream = streams.video;
  2375. if(streams && streams.desktop)
  2376. desktopStream = streams.desktop;
  2377. }
  2378. if (desktopStream)
  2379. res.push({stream: desktopStream,
  2380. type: "video", videoType: "desktop"});
  2381. if(audioStream)
  2382. res.push({stream: audioStream, type: "audio", videoType: null});
  2383. if(videoStream)
  2384. res.push({stream: videoStream, type: "video", videoType: "camera",
  2385. resolution: resolution});
  2386. return res;
  2387. }
  2388. //Options parameter is to pass config options. Currently uses only "useIPv6".
  2389. var RTCUtils = {
  2390. init: function (options) {
  2391. return new Promise(function(resolve, reject) {
  2392. if (RTCBrowserType.isFirefox()) {
  2393. var FFversion = RTCBrowserType.getFirefoxVersion();
  2394. if (FFversion < 40) {
  2395. logger.error(
  2396. "Firefox version too old: " + FFversion +
  2397. ". Required >= 40.");
  2398. reject(new Error("Firefox version too old: " + FFversion +
  2399. ". Required >= 40."));
  2400. return;
  2401. }
  2402. this.peerconnection = mozRTCPeerConnection;
  2403. this.getUserMedia = wrapGetUserMedia(navigator.mozGetUserMedia.bind(navigator));
  2404. this.enumerateDevices = wrapEnumerateDevices(
  2405. navigator.mediaDevices.enumerateDevices.bind(navigator.mediaDevices)
  2406. );
  2407. this.pc_constraints = {};
  2408. this.attachMediaStream = function (element, stream) {
  2409. // srcObject is being standardized and FF will eventually
  2410. // support that unprefixed. FF also supports the
  2411. // "element.src = URL.createObjectURL(...)" combo, but that
  2412. // will be deprecated in favour of srcObject.
  2413. //
  2414. // https://groups.google.com/forum/#!topic/mozilla.dev.media/pKOiioXonJg
  2415. // https://github.com/webrtc/samples/issues/302
  2416. if (!element[0])
  2417. return;
  2418. element[0].mozSrcObject = stream;
  2419. element[0].play();
  2420. };
  2421. this.getStreamID = function (stream) {
  2422. var id = stream.id;
  2423. if (!id) {
  2424. var tracks = stream.getVideoTracks();
  2425. if (!tracks || tracks.length === 0) {
  2426. tracks = stream.getAudioTracks();
  2427. }
  2428. id = tracks[0].id;
  2429. }
  2430. return SDPUtil.filter_special_chars(id);
  2431. };
  2432. this.getVideoSrc = function (element) {
  2433. if (!element)
  2434. return null;
  2435. return element.mozSrcObject;
  2436. };
  2437. this.setVideoSrc = function (element, src) {
  2438. if (element)
  2439. element.mozSrcObject = src;
  2440. };
  2441. RTCSessionDescription = mozRTCSessionDescription;
  2442. RTCIceCandidate = mozRTCIceCandidate;
  2443. } else if (RTCBrowserType.isChrome() || RTCBrowserType.isOpera()) {
  2444. this.peerconnection = webkitRTCPeerConnection;
  2445. var getUserMedia = navigator.webkitGetUserMedia.bind(navigator);
  2446. if (navigator.mediaDevices) {
  2447. this.getUserMedia = wrapGetUserMedia(getUserMedia);
  2448. this.enumerateDevices = wrapEnumerateDevices(
  2449. navigator.mediaDevices.enumerateDevices.bind(navigator.mediaDevices)
  2450. );
  2451. } else {
  2452. this.getUserMedia = getUserMedia;
  2453. this.enumerateDevices = enumerateDevicesThroughMediaStreamTrack;
  2454. }
  2455. this.attachMediaStream = function (element, stream) {
  2456. element.attr('src', webkitURL.createObjectURL(stream));
  2457. };
  2458. this.getStreamID = function (stream) {
  2459. // streams from FF endpoints have the characters '{' and '}'
  2460. // that make jQuery choke.
  2461. return SDPUtil.filter_special_chars(stream.id);
  2462. };
  2463. this.getVideoSrc = function (element) {
  2464. if (!element)
  2465. return null;
  2466. return element.getAttribute("src");
  2467. };
  2468. this.setVideoSrc = function (element, src) {
  2469. if (element)
  2470. element.setAttribute("src", src);
  2471. };
  2472. // DTLS should now be enabled by default but..
  2473. this.pc_constraints = {'optional': [
  2474. {'DtlsSrtpKeyAgreement': 'true'}
  2475. ]};
  2476. if (options.useIPv6) {
  2477. // https://code.google.com/p/webrtc/issues/detail?id=2828
  2478. this.pc_constraints.optional.push({googIPv6: true});
  2479. }
  2480. if (RTCBrowserType.isAndroid()) {
  2481. this.pc_constraints = {}; // disable DTLS on Android
  2482. }
  2483. if (!webkitMediaStream.prototype.getVideoTracks) {
  2484. webkitMediaStream.prototype.getVideoTracks = function () {
  2485. return this.videoTracks;
  2486. };
  2487. }
  2488. if (!webkitMediaStream.prototype.getAudioTracks) {
  2489. webkitMediaStream.prototype.getAudioTracks = function () {
  2490. return this.audioTracks;
  2491. };
  2492. }
  2493. }
  2494. // Detect IE/Safari
  2495. else if (RTCBrowserType.isTemasysPluginUsed()) {
  2496. //AdapterJS.WebRTCPlugin.setLogLevel(
  2497. // AdapterJS.WebRTCPlugin.PLUGIN_LOG_LEVELS.VERBOSE);
  2498. var self = this;
  2499. AdapterJS.webRTCReady(function (isPlugin) {
  2500. self.peerconnection = RTCPeerConnection;
  2501. self.getUserMedia = window.getUserMedia;
  2502. self.enumerateDevices = enumerateDevicesThroughMediaStreamTrack;
  2503. self.attachMediaStream = function (elSel, stream) {
  2504. if (stream.id === "dummyAudio" || stream.id === "dummyVideo") {
  2505. return;
  2506. }
  2507. attachMediaStream(elSel[0], stream);
  2508. };
  2509. self.getStreamID = function (stream) {
  2510. var id = SDPUtil.filter_special_chars(stream.label);
  2511. return id;
  2512. };
  2513. self.getVideoSrc = function (element) {
  2514. if (!element) {
  2515. logger.warn("Attempt to get video SRC of null element");
  2516. return null;
  2517. }
  2518. var children = element.children;
  2519. for (var i = 0; i !== children.length; ++i) {
  2520. if (children[i].name === 'streamId') {
  2521. return children[i].value;
  2522. }
  2523. }
  2524. //logger.info(element.id + " SRC: " + src);
  2525. return null;
  2526. };
  2527. self.setVideoSrc = function (element, src) {
  2528. //logger.info("Set video src: ", element, src);
  2529. if (!src) {
  2530. logger.warn("Not attaching video stream, 'src' is null");
  2531. return;
  2532. }
  2533. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  2534. var stream = AdapterJS.WebRTCPlugin.plugin
  2535. .getStreamWithId(AdapterJS.WebRTCPlugin.pageId, src);
  2536. attachMediaStream(element, stream);
  2537. };
  2538. onReady(options, self.getUserMediaWithConstraints);
  2539. resolve();
  2540. });
  2541. } else {
  2542. try {
  2543. logger.error('Browser does not appear to be WebRTC-capable');
  2544. } catch (e) {
  2545. }
  2546. reject('Browser does not appear to be WebRTC-capable');
  2547. return;
  2548. }
  2549. // Call onReady() if Temasys plugin is not used
  2550. if (!RTCBrowserType.isTemasysPluginUsed()) {
  2551. onReady(options, this.getUserMediaWithConstraints);
  2552. resolve();
  2553. }
  2554. }.bind(this));
  2555. },
  2556. /**
  2557. * @param {string[]} um required user media types
  2558. * @param {function} success_callback
  2559. * @param {Function} failure_callback
  2560. * @param {Object} [options] optional parameters
  2561. * @param {string} options.resolution
  2562. * @param {number} options.bandwidth
  2563. * @param {number} options.fps
  2564. * @param {string} options.desktopStream
  2565. * @param {string} options.cameraDeviceId
  2566. * @param {string} options.micDeviceId
  2567. **/
  2568. getUserMediaWithConstraints: function ( um, success_callback, failure_callback, options) {
  2569. options = options || {};
  2570. var resolution = options.resolution;
  2571. var constraints = getConstraints(um, options);
  2572. logger.info("Get media constraints", constraints);
  2573. try {
  2574. this.getUserMedia(constraints,
  2575. function (stream) {
  2576. logger.log('onUserMediaSuccess');
  2577. setAvailableDevices(um, true);
  2578. success_callback(stream);
  2579. },
  2580. function (error) {
  2581. setAvailableDevices(um, false);
  2582. logger.warn('Failed to get access to local media. Error ',
  2583. error, constraints);
  2584. if (failure_callback) {
  2585. failure_callback(error, resolution);
  2586. }
  2587. });
  2588. } catch (e) {
  2589. logger.error('GUM failed: ', e);
  2590. if (failure_callback) {
  2591. failure_callback(e);
  2592. }
  2593. }
  2594. },
  2595. /**
  2596. * Creates the local MediaStreams.
  2597. * @param {Object} [options] optional parameters
  2598. * @param {Array} options.devices the devices that will be requested
  2599. * @param {string} options.resolution resolution constraints
  2600. * @param {bool} options.dontCreateJitsiTrack if <tt>true</tt> objects with the following structure {stream: the Media Stream,
  2601. * type: "audio" or "video", videoType: "camera" or "desktop"}
  2602. * will be returned trough the Promise, otherwise JitsiTrack objects will be returned.
  2603. * @param {string} options.cameraDeviceId
  2604. * @param {string} options.micDeviceId
  2605. * @returns {*} Promise object that will receive the new JitsiTracks
  2606. */
  2607. obtainAudioAndVideoPermissions: function (options) {
  2608. var self = this;
  2609. options = options || {};
  2610. return new Promise(function (resolve, reject) {
  2611. var successCallback = function (stream) {
  2612. resolve(handleLocalStream(stream, options.resolution));
  2613. };
  2614. options.devices = options.devices || ['audio', 'video'];
  2615. if(!screenObtainer.isSupported()
  2616. && options.devices.indexOf("desktop") !== -1){
  2617. reject(new Error("Desktop sharing is not supported!"));
  2618. }
  2619. if (RTCBrowserType.isFirefox() ||
  2620. RTCBrowserType.isTemasysPluginUsed()) {
  2621. var GUM = function (device, s, e) {
  2622. this.getUserMediaWithConstraints(device, s, e, options);
  2623. };
  2624. var deviceGUM = {
  2625. "audio": GUM.bind(self, ["audio"]),
  2626. "video": GUM.bind(self, ["video"]),
  2627. "desktop": screenObtainer.obtainStream
  2628. };
  2629. // With FF/IE we can't split the stream into audio and video because FF
  2630. // doesn't support media stream constructors. So, we need to get the
  2631. // audio stream separately from the video stream using two distinct GUM
  2632. // calls. Not very user friendly :-( but we don't have many other
  2633. // options neither.
  2634. //
  2635. // Note that we pack those 2 streams in a single object and pass it to
  2636. // the successCallback method.
  2637. obtainDevices({
  2638. devices: options.devices,
  2639. streams: [],
  2640. successCallback: successCallback,
  2641. errorCallback: reject,
  2642. deviceGUM: deviceGUM
  2643. });
  2644. } else {
  2645. var hasDesktop = options.devices.indexOf('desktop') > -1;
  2646. if (hasDesktop) {
  2647. options.devices.splice(options.devices.indexOf("desktop"), 1);
  2648. }
  2649. options.resolution = options.resolution || '360';
  2650. if(options.devices.length) {
  2651. this.getUserMediaWithConstraints(
  2652. options.devices,
  2653. function (stream) {
  2654. if(hasDesktop) {
  2655. screenObtainer.obtainStream(
  2656. function (desktopStream) {
  2657. successCallback({audioVideo: stream,
  2658. desktopStream: desktopStream});
  2659. }, function (error) {
  2660. reject(
  2661. JitsiTrackErrors.parseError(error));
  2662. });
  2663. } else {
  2664. successCallback({audioVideo: stream});
  2665. }
  2666. },
  2667. function (error) {
  2668. reject(JitsiTrackErrors.parseError(error));
  2669. },
  2670. options);
  2671. } else if (hasDesktop) {
  2672. screenObtainer.obtainStream(
  2673. function (stream) {
  2674. successCallback({desktopStream: stream});
  2675. }, function (error) {
  2676. reject(
  2677. JitsiTrackErrors.parseError(error));
  2678. });
  2679. }
  2680. }
  2681. }.bind(this));
  2682. },
  2683. addListener: function (eventType, listener) {
  2684. eventEmitter.on(eventType, listener);
  2685. },
  2686. removeListener: function (eventType, listener) {
  2687. eventEmitter.removeListener(eventType, listener);
  2688. },
  2689. getDeviceAvailability: function () {
  2690. return devices;
  2691. },
  2692. isRTCReady: function () {
  2693. return rtcReady;
  2694. },
  2695. /**
  2696. * Checks if its possible to enumerate available cameras/micropones.
  2697. * @returns {boolean} true if available, false otherwise.
  2698. */
  2699. isDeviceListAvailable: function () {
  2700. var isEnumerateDevicesAvailable = navigator.mediaDevices && navigator.mediaDevices.enumerateDevices;
  2701. if (isEnumerateDevicesAvailable) {
  2702. return true;
  2703. }
  2704. return (MediaStreamTrack && MediaStreamTrack.getSources)? true : false;
  2705. },
  2706. /**
  2707. * Returns true if changing the camera / microphone device is supported and
  2708. * false if not.
  2709. */
  2710. isDeviceChangeAvailable: function () {
  2711. if(RTCBrowserType.isChrome() || RTCBrowserType.isOpera() ||
  2712. RTCBrowserType.isTemasysPluginUsed())
  2713. return true;
  2714. return false;
  2715. },
  2716. /**
  2717. * A method to handle stopping of the stream.
  2718. * One point to handle the differences in various implementations.
  2719. * @param mediaStream MediaStream object to stop.
  2720. */
  2721. stopMediaStream: function (mediaStream) {
  2722. mediaStream.getTracks().forEach(function (track) {
  2723. // stop() not supported with IE
  2724. if (track.stop) {
  2725. track.stop();
  2726. }
  2727. });
  2728. // leave stop for implementation still using it
  2729. if (mediaStream.stop) {
  2730. mediaStream.stop();
  2731. }
  2732. }
  2733. };
  2734. module.exports = RTCUtils;
  2735. }).call(this,"/modules/RTC/RTCUtils.js")
  2736. },{"../../JitsiTrackErrors":9,"../../service/RTC/RTCEvents":79,"../../service/RTC/Resolutions":80,"../xmpp/SDPUtil":32,"./RTCBrowserType":17,"./ScreenObtainer":19,"./adapter.screenshare":20,"events":43,"jitsi-meet-logger":47}],19:[function(require,module,exports){
  2737. (function (__filename){
  2738. /* global chrome, $, alert */
  2739. /* jshint -W003 */
  2740. var logger = require("jitsi-meet-logger").getLogger(__filename);
  2741. var RTCBrowserType = require("./RTCBrowserType");
  2742. var AdapterJS = require("./adapter.screenshare");
  2743. var DesktopSharingEventTypes
  2744. = require("../../service/desktopsharing/DesktopSharingEventTypes");
  2745. /**
  2746. * Indicates whether the Chrome desktop sharing extension is installed.
  2747. * @type {boolean}
  2748. */
  2749. var chromeExtInstalled = false;
  2750. /**
  2751. * Indicates whether an update of the Chrome desktop sharing extension is
  2752. * required.
  2753. * @type {boolean}
  2754. */
  2755. var chromeExtUpdateRequired = false;
  2756. /**
  2757. * Whether the jidesha extension for firefox is installed for the domain on
  2758. * which we are running. Null designates an unknown value.
  2759. * @type {null}
  2760. */
  2761. var firefoxExtInstalled = null;
  2762. /**
  2763. * If set to true, detection of an installed firefox extension will be started
  2764. * again the next time obtainScreenOnFirefox is called (e.g. next time the
  2765. * user tries to enable screen sharing).
  2766. */
  2767. var reDetectFirefoxExtension = false;
  2768. var GUM = null;
  2769. /**
  2770. * Handles obtaining a stream from a screen capture on different browsers.
  2771. */
  2772. var ScreenObtainer = {
  2773. /**
  2774. * The EventEmitter to use to emit events.
  2775. * @type {null}
  2776. */
  2777. eventEmitter: null,
  2778. obtainStream: null,
  2779. /**
  2780. * Initializes the function used to obtain a screen capture
  2781. * (this.obtainStream).
  2782. *
  2783. * If the browser is Chrome, it uses the value of
  2784. * 'options.desktopSharingChromeMethod' (or 'options.desktopSharing') to
  2785. * decide whether to use the a Chrome extension (if the value is 'ext'),
  2786. * use the "screen" media source (if the value is 'webrtc'),
  2787. * or disable screen capture (if the value is other).
  2788. * Note that for the "screen" media source to work the
  2789. * 'chrome://flags/#enable-usermedia-screen-capture' flag must be set.
  2790. */
  2791. init: function(eventEmitter, options, gum) {
  2792. this.eventEmitter = eventEmitter;
  2793. var obtainDesktopStream = null;
  2794. this.options = options = options || {};
  2795. GUM = gum;
  2796. if (RTCBrowserType.isFirefox())
  2797. initFirefoxExtensionDetection(options);
  2798. // TODO remove this, options.desktopSharing is deprecated.
  2799. var chromeMethod =
  2800. (options.desktopSharingChromeMethod || options.desktopSharing);
  2801. if (RTCBrowserType.isTemasysPluginUsed()) {
  2802. if (!AdapterJS.WebRTCPlugin.plugin.HasScreensharingFeature) {
  2803. logger.info("Screensharing not supported by this plugin " +
  2804. "version");
  2805. } else if(!AdapterJS.WebRTCPlugin.plugin.isScreensharingAvailable) {
  2806. logger.info(
  2807. "Screensharing not available with Temasys plugin on" +
  2808. " this site");
  2809. } else {
  2810. obtainDesktopStream = obtainWebRTCScreen;
  2811. logger.info("Using Temasys plugin for desktop sharing");
  2812. }
  2813. } else if (RTCBrowserType.isChrome()) {
  2814. if (chromeMethod == "ext") {
  2815. if (RTCBrowserType.getChromeVersion() >= 34) {
  2816. obtainDesktopStream =
  2817. this.obtainScreenFromExtension;
  2818. logger.info("Using Chrome extension for desktop sharing");
  2819. initChromeExtension(options);
  2820. } else {
  2821. logger.info("Chrome extension not supported until ver 34");
  2822. }
  2823. } else if (chromeMethod == "webrtc") {
  2824. obtainDesktopStream = obtainWebRTCScreen;
  2825. logger.info("Using Chrome WebRTC for desktop sharing");
  2826. }
  2827. } else if (RTCBrowserType.isFirefox()) {
  2828. if (options.desktopSharingFirefoxDisabled) {
  2829. obtainDesktopStream = null;
  2830. } else if (window.location.protocol === "http:"){
  2831. logger.log("Screen sharing is not supported over HTTP. " +
  2832. "Use of HTTPS is required.");
  2833. obtainDesktopStream = null;
  2834. } else {
  2835. obtainDesktopStream = this.obtainScreenOnFirefox;
  2836. }
  2837. }
  2838. if (!obtainDesktopStream) {
  2839. logger.info("Desktop sharing disabled");
  2840. }
  2841. this.obtainStream = obtainDesktopStream;
  2842. },
  2843. /**
  2844. * Checks whether obtaining a screen capture is supported in the current
  2845. * environment.
  2846. * @returns {boolean}
  2847. */
  2848. isSupported: function() {
  2849. return !!this.obtainStream;
  2850. },
  2851. /**
  2852. * Obtains a screen capture stream on Firefox.
  2853. * @param callback
  2854. * @param errorCallback
  2855. */
  2856. obtainScreenOnFirefox:
  2857. function (callback, errorCallback) {
  2858. var self = this;
  2859. var extensionRequired = false;
  2860. if (this.options.desktopSharingFirefoxMaxVersionExtRequired === -1 ||
  2861. (this.options.desktopSharingFirefoxMaxVersionExtRequired >= 0 &&
  2862. RTCBrowserType.getFirefoxVersion() <=
  2863. this.options.desktopSharingFirefoxMaxVersionExtRequired)) {
  2864. extensionRequired = true;
  2865. logger.log("Jidesha extension required on firefox version " +
  2866. RTCBrowserType.getFirefoxVersion());
  2867. }
  2868. if (!extensionRequired || firefoxExtInstalled === true) {
  2869. obtainWebRTCScreen(callback, errorCallback);
  2870. return;
  2871. }
  2872. if (reDetectFirefoxExtension) {
  2873. reDetectFirefoxExtension = false;
  2874. initFirefoxExtensionDetection(this.options);
  2875. }
  2876. // Give it some (more) time to initialize, and assume lack of
  2877. // extension if it hasn't.
  2878. if (firefoxExtInstalled === null) {
  2879. window.setTimeout(
  2880. function() {
  2881. if (firefoxExtInstalled === null)
  2882. firefoxExtInstalled = false;
  2883. self.obtainScreenOnFirefox(callback, errorCallback);
  2884. },
  2885. 300
  2886. );
  2887. logger.log("Waiting for detection of jidesha on firefox to " +
  2888. "finish.");
  2889. return;
  2890. }
  2891. // We need an extension and it isn't installed.
  2892. // Make sure we check for the extension when the user clicks again.
  2893. firefoxExtInstalled = null;
  2894. reDetectFirefoxExtension = true;
  2895. // Prompt the user to install the extension
  2896. this.eventEmitter.emit(
  2897. DesktopSharingEventTypes.FIREFOX_EXTENSION_NEEDED,
  2898. this.options.desktopSharingFirefoxExtensionURL);
  2899. // Make sure desktopsharing knows that we failed, so that it doesn't get
  2900. // stuck in 'switching' mode.
  2901. errorCallback('Firefox extension required.');
  2902. },
  2903. /**
  2904. * Asks Chrome extension to call chooseDesktopMedia and gets chrome
  2905. * 'desktop' stream for returned stream token.
  2906. */
  2907. obtainScreenFromExtension: function (streamCallback, failCallback) {
  2908. if (chromeExtInstalled) {
  2909. doGetStreamFromExtension(this.options, streamCallback,
  2910. failCallback);
  2911. } else {
  2912. if (chromeExtUpdateRequired) {
  2913. alert(
  2914. 'Jitsi Desktop Streamer requires update. ' +
  2915. 'Changes will take effect after next Chrome restart.');
  2916. }
  2917. chrome.webstore.install(
  2918. getWebStoreInstallUrl(this.options),
  2919. function (arg) {
  2920. logger.log("Extension installed successfully", arg);
  2921. chromeExtInstalled = true;
  2922. // We need to give a moment for the endpoint to become
  2923. // available
  2924. window.setTimeout(function () {
  2925. doGetStreamFromExtension(this.options, streamCallback,
  2926. failCallback);
  2927. }, 500);
  2928. },
  2929. function (arg) {
  2930. logger.log("Failed to install the extension", arg);
  2931. failCallback(arg);
  2932. }
  2933. );
  2934. }
  2935. }
  2936. };
  2937. /**
  2938. * Obtains a desktop stream using getUserMedia.
  2939. * For this to work on Chrome, the
  2940. * 'chrome://flags/#enable-usermedia-screen-capture' flag must be enabled.
  2941. *
  2942. * On firefox, the document's domain must be white-listed in the
  2943. * 'media.getusermedia.screensharing.allowed_domains' preference in
  2944. * 'about:config'.
  2945. */
  2946. function obtainWebRTCScreen(streamCallback, failCallback) {
  2947. GUM(
  2948. ['screen'],
  2949. streamCallback,
  2950. failCallback
  2951. );
  2952. }
  2953. /**
  2954. * Constructs inline install URL for Chrome desktop streaming extension.
  2955. * The 'chromeExtensionId' must be defined in options parameter.
  2956. * @param options supports "desktopSharingChromeExtId" and "chromeExtensionId"
  2957. * @returns {string}
  2958. */
  2959. function getWebStoreInstallUrl(options)
  2960. {
  2961. //TODO remove chromeExtensionId (deprecated)
  2962. return "https://chrome.google.com/webstore/detail/" +
  2963. (options.desktopSharingChromeExtId || options.chromeExtensionId);
  2964. }
  2965. /**
  2966. * Checks whether an update of the Chrome extension is required.
  2967. * @param minVersion minimal required version
  2968. * @param extVersion current extension version
  2969. * @returns {boolean}
  2970. */
  2971. function isUpdateRequired(minVersion, extVersion) {
  2972. try {
  2973. var s1 = minVersion.split('.');
  2974. var s2 = extVersion.split('.');
  2975. var len = Math.max(s1.length, s2.length);
  2976. for (var i = 0; i < len; i++) {
  2977. var n1 = 0,
  2978. n2 = 0;
  2979. if (i < s1.length)
  2980. n1 = parseInt(s1[i]);
  2981. if (i < s2.length)
  2982. n2 = parseInt(s2[i]);
  2983. if (isNaN(n1) || isNaN(n2)) {
  2984. return true;
  2985. } else if (n1 !== n2) {
  2986. return n1 > n2;
  2987. }
  2988. }
  2989. // will happen if both versions have identical numbers in
  2990. // their components (even if one of them is longer, has more components)
  2991. return false;
  2992. }
  2993. catch (e) {
  2994. logger.error("Failed to parse extension version", e);
  2995. return true;
  2996. }
  2997. }
  2998. function checkChromeExtInstalled(callback, options) {
  2999. if (!chrome || !chrome.runtime) {
  3000. // No API, so no extension for sure
  3001. callback(false, false);
  3002. return;
  3003. }
  3004. chrome.runtime.sendMessage(
  3005. //TODO: remove chromeExtensionId (deprecated)
  3006. (options.desktopSharingChromeExtId || options.chromeExtensionId),
  3007. { getVersion: true },
  3008. function (response) {
  3009. if (!response || !response.version) {
  3010. // Communication failure - assume that no endpoint exists
  3011. logger.warn(
  3012. "Extension not installed?: ", chrome.runtime.lastError);
  3013. callback(false, false);
  3014. return;
  3015. }
  3016. // Check installed extension version
  3017. var extVersion = response.version;
  3018. logger.log('Extension version is: ' + extVersion);
  3019. //TODO: remove minChromeExtVersion (deprecated)
  3020. var updateRequired
  3021. = isUpdateRequired(
  3022. (options.desktopSharingChromeMinExtVersion ||
  3023. options.minChromeExtVersion),
  3024. extVersion);
  3025. callback(!updateRequired, updateRequired);
  3026. }
  3027. );
  3028. }
  3029. function doGetStreamFromExtension(options, streamCallback, failCallback) {
  3030. // Sends 'getStream' msg to the extension.
  3031. // Extension id must be defined in the config.
  3032. chrome.runtime.sendMessage(
  3033. //TODO: remove chromeExtensionId (deprecated)
  3034. (options.desktopSharingChromeExtId || options.chromeExtensionId),
  3035. {
  3036. getStream: true,
  3037. //TODO: remove desktopSharingSources (deprecated).
  3038. sources: (options.desktopSharingChromeSources ||
  3039. options.desktopSharingSources)
  3040. },
  3041. function (response) {
  3042. if (!response) {
  3043. failCallback(chrome.runtime.lastError);
  3044. return;
  3045. }
  3046. logger.log("Response from extension: " + response);
  3047. if (response.streamId) {
  3048. GUM(
  3049. ['desktop'],
  3050. function (stream) {
  3051. streamCallback(stream);
  3052. },
  3053. failCallback,
  3054. {desktopStream: response.streamId});
  3055. } else {
  3056. failCallback("Extension failed to get the stream");
  3057. }
  3058. }
  3059. );
  3060. }
  3061. /**
  3062. * Initializes <link rel=chrome-webstore-item /> with extension id set in
  3063. * config.js to support inline installs. Host site must be selected as main
  3064. * website of published extension.
  3065. * @param options supports "desktopSharingChromeExtId" and "chromeExtensionId"
  3066. */
  3067. function initInlineInstalls(options)
  3068. {
  3069. $("link[rel=chrome-webstore-item]").attr("href",
  3070. getWebStoreInstallUrl(options));
  3071. }
  3072. function initChromeExtension(options) {
  3073. // Initialize Chrome extension inline installs
  3074. initInlineInstalls(options);
  3075. // Check if extension is installed
  3076. checkChromeExtInstalled(function (installed, updateRequired) {
  3077. chromeExtInstalled = installed;
  3078. chromeExtUpdateRequired = updateRequired;
  3079. logger.info(
  3080. "Chrome extension installed: " + chromeExtInstalled +
  3081. " updateRequired: " + chromeExtUpdateRequired);
  3082. }, options);
  3083. }
  3084. /**
  3085. * Starts the detection of an installed jidesha extension for firefox.
  3086. * @param options supports "desktopSharingFirefoxDisabled",
  3087. * "desktopSharingFirefoxExtId" and "chromeExtensionId"
  3088. */
  3089. function initFirefoxExtensionDetection(options) {
  3090. if (options.desktopSharingFirefoxDisabled) {
  3091. return;
  3092. }
  3093. if (firefoxExtInstalled === false || firefoxExtInstalled === true)
  3094. return;
  3095. if (!options.desktopSharingFirefoxExtId) {
  3096. firefoxExtInstalled = false;
  3097. return;
  3098. }
  3099. var img = document.createElement('img');
  3100. img.onload = function(){
  3101. logger.log("Detected firefox screen sharing extension.");
  3102. firefoxExtInstalled = true;
  3103. };
  3104. img.onerror = function(){
  3105. logger.log("Detected lack of firefox screen sharing extension.");
  3106. firefoxExtInstalled = false;
  3107. };
  3108. // The jidesha extension exposes an empty image file under the url:
  3109. // "chrome://EXT_ID/content/DOMAIN.png"
  3110. // Where EXT_ID is the ID of the extension with "@" replaced by ".", and
  3111. // DOMAIN is a domain whitelisted by the extension.
  3112. var src = "chrome://" +
  3113. (options.desktopSharingFirefoxExtId.replace('@', '.')) +
  3114. "/content/" + document.location.hostname + ".png";
  3115. img.setAttribute('src', src);
  3116. }
  3117. module.exports = ScreenObtainer;
  3118. }).call(this,"/modules/RTC/ScreenObtainer.js")
  3119. },{"../../service/desktopsharing/DesktopSharingEventTypes":82,"./RTCBrowserType":17,"./adapter.screenshare":20,"jitsi-meet-logger":47}],20:[function(require,module,exports){
  3120. (function (__filename){
  3121. /*! adapterjs - v0.12.3 - 2015-11-16 */
  3122. var console = require("jitsi-meet-logger").getLogger(__filename);
  3123. // Adapter's interface.
  3124. var AdapterJS = AdapterJS || {};
  3125. // Browserify compatibility
  3126. if(typeof exports !== 'undefined') {
  3127. module.exports = AdapterJS;
  3128. }
  3129. AdapterJS.options = AdapterJS.options || {};
  3130. // uncomment to get virtual webcams
  3131. // AdapterJS.options.getAllCams = true;
  3132. // uncomment to prevent the install prompt when the plugin in not yet installed
  3133. // AdapterJS.options.hidePluginInstallPrompt = true;
  3134. // AdapterJS version
  3135. AdapterJS.VERSION = '0.12.3';
  3136. // This function will be called when the WebRTC API is ready to be used
  3137. // Whether it is the native implementation (Chrome, Firefox, Opera) or
  3138. // the plugin
  3139. // You may Override this function to synchronise the start of your application
  3140. // with the WebRTC API being ready.
  3141. // If you decide not to override use this synchronisation, it may result in
  3142. // an extensive CPU usage on the plugin start (once per tab loaded)
  3143. // Params:
  3144. // - isUsingPlugin: true is the WebRTC plugin is being used, false otherwise
  3145. //
  3146. AdapterJS.onwebrtcready = AdapterJS.onwebrtcready || function(isUsingPlugin) {
  3147. // The WebRTC API is ready.
  3148. // Override me and do whatever you want here
  3149. };
  3150. // Sets a callback function to be called when the WebRTC interface is ready.
  3151. // The first argument is the function to callback.\
  3152. // Throws an error if the first argument is not a function
  3153. AdapterJS.webRTCReady = function (callback) {
  3154. if (typeof callback !== 'function') {
  3155. throw new Error('Callback provided is not a function');
  3156. }
  3157. if (true === AdapterJS.onwebrtcreadyDone) {
  3158. // All WebRTC interfaces are ready, just call the callback
  3159. callback(null !== AdapterJS.WebRTCPlugin.plugin);
  3160. } else {
  3161. // will be triggered automatically when your browser/plugin is ready.
  3162. AdapterJS.onwebrtcready = callback;
  3163. }
  3164. };
  3165. // Plugin namespace
  3166. AdapterJS.WebRTCPlugin = AdapterJS.WebRTCPlugin || {};
  3167. // The object to store plugin information
  3168. AdapterJS.WebRTCPlugin.pluginInfo = {
  3169. prefix : 'Tem',
  3170. plugName : 'TemWebRTCPlugin',
  3171. pluginId : 'plugin0',
  3172. type : 'application/x-temwebrtcplugin',
  3173. onload : '__TemWebRTCReady0',
  3174. portalLink : 'http://skylink.io/plugin/',
  3175. downloadLink : null, //set below
  3176. companyName: 'Temasys'
  3177. };
  3178. if(!!navigator.platform.match(/^Mac/i)) {
  3179. AdapterJS.WebRTCPlugin.pluginInfo.downloadLink = 'http://bit.ly/1n77hco';
  3180. }
  3181. else if(!!navigator.platform.match(/^Win/i)) {
  3182. AdapterJS.WebRTCPlugin.pluginInfo.downloadLink = 'http://bit.ly/1kkS4FN';
  3183. }
  3184. AdapterJS.WebRTCPlugin.TAGS = {
  3185. NONE : 'none',
  3186. AUDIO : 'audio',
  3187. VIDEO : 'video'
  3188. };
  3189. // Unique identifier of each opened page
  3190. AdapterJS.WebRTCPlugin.pageId = Math.random().toString(36).slice(2);
  3191. // Use this whenever you want to call the plugin.
  3192. AdapterJS.WebRTCPlugin.plugin = null;
  3193. // Set log level for the plugin once it is ready.
  3194. // The different values are
  3195. // This is an asynchronous function that will run when the plugin is ready
  3196. AdapterJS.WebRTCPlugin.setLogLevel = null;
  3197. // Defines webrtc's JS interface according to the plugin's implementation.
  3198. // Define plugin Browsers as WebRTC Interface.
  3199. AdapterJS.WebRTCPlugin.defineWebRTCInterface = null;
  3200. // This function detects whether or not a plugin is installed.
  3201. // Checks if Not IE (firefox, for example), else if it's IE,
  3202. // we're running IE and do something. If not it is not supported.
  3203. AdapterJS.WebRTCPlugin.isPluginInstalled = null;
  3204. // Lets adapter.js wait until the the document is ready before injecting the plugin
  3205. AdapterJS.WebRTCPlugin.pluginInjectionInterval = null;
  3206. // Inject the HTML DOM object element into the page.
  3207. AdapterJS.WebRTCPlugin.injectPlugin = null;
  3208. // States of readiness that the plugin goes through when
  3209. // being injected and stated
  3210. AdapterJS.WebRTCPlugin.PLUGIN_STATES = {
  3211. NONE : 0, // no plugin use
  3212. INITIALIZING : 1, // Detected need for plugin
  3213. INJECTING : 2, // Injecting plugin
  3214. INJECTED: 3, // Plugin element injected but not usable yet
  3215. READY: 4 // Plugin ready to be used
  3216. };
  3217. // Current state of the plugin. You cannot use the plugin before this is
  3218. // equal to AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY
  3219. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.NONE;
  3220. // True is AdapterJS.onwebrtcready was already called, false otherwise
  3221. // Used to make sure AdapterJS.onwebrtcready is only called once
  3222. AdapterJS.onwebrtcreadyDone = false;
  3223. // Log levels for the plugin.
  3224. // To be set by calling AdapterJS.WebRTCPlugin.setLogLevel
  3225. /*
  3226. Log outputs are prefixed in some cases.
  3227. INFO: Information reported by the plugin.
  3228. ERROR: Errors originating from within the plugin.
  3229. WEBRTC: Error originating from within the libWebRTC library
  3230. */
  3231. // From the least verbose to the most verbose
  3232. AdapterJS.WebRTCPlugin.PLUGIN_LOG_LEVELS = {
  3233. NONE : 'NONE',
  3234. ERROR : 'ERROR',
  3235. WARNING : 'WARNING',
  3236. INFO: 'INFO',
  3237. VERBOSE: 'VERBOSE',
  3238. SENSITIVE: 'SENSITIVE'
  3239. };
  3240. // Does a waiting check before proceeding to load the plugin.
  3241. AdapterJS.WebRTCPlugin.WaitForPluginReady = null;
  3242. // This methid will use an interval to wait for the plugin to be ready.
  3243. AdapterJS.WebRTCPlugin.callWhenPluginReady = null;
  3244. // !!!! WARNING: DO NOT OVERRIDE THIS FUNCTION. !!!
  3245. // This function will be called when plugin is ready. It sends necessary
  3246. // details to the plugin.
  3247. // The function will wait for the document to be ready and the set the
  3248. // plugin state to AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY,
  3249. // indicating that it can start being requested.
  3250. // This function is not in the IE/Safari condition brackets so that
  3251. // TemPluginLoaded function might be called on Chrome/Firefox.
  3252. // This function is the only private function that is not encapsulated to
  3253. // allow the plugin method to be called.
  3254. __TemWebRTCReady0 = function () {
  3255. if (document.readyState === 'complete') {
  3256. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY;
  3257. AdapterJS.maybeThroughWebRTCReady();
  3258. } else {
  3259. AdapterJS.WebRTCPlugin.documentReadyInterval = setInterval(function () {
  3260. if (document.readyState === 'complete') {
  3261. // TODO: update comments, we wait for the document to be ready
  3262. clearInterval(AdapterJS.WebRTCPlugin.documentReadyInterval);
  3263. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY;
  3264. AdapterJS.maybeThroughWebRTCReady();
  3265. }
  3266. }, 100);
  3267. }
  3268. };
  3269. AdapterJS.maybeThroughWebRTCReady = function() {
  3270. if (!AdapterJS.onwebrtcreadyDone) {
  3271. AdapterJS.onwebrtcreadyDone = true;
  3272. if (typeof(AdapterJS.onwebrtcready) === 'function') {
  3273. AdapterJS.onwebrtcready(AdapterJS.WebRTCPlugin.plugin !== null);
  3274. }
  3275. }
  3276. };
  3277. // Text namespace
  3278. AdapterJS.TEXT = {
  3279. PLUGIN: {
  3280. REQUIRE_INSTALLATION: 'This website requires you to install a WebRTC-enabling plugin ' +
  3281. 'to work on this browser.',
  3282. NOT_SUPPORTED: 'Your browser does not support WebRTC.',
  3283. BUTTON: 'Install Now'
  3284. },
  3285. REFRESH: {
  3286. REQUIRE_REFRESH: 'Please refresh page',
  3287. BUTTON: 'Refresh Page'
  3288. }
  3289. };
  3290. // The result of ice connection states.
  3291. // - starting: Ice connection is starting.
  3292. // - checking: Ice connection is checking.
  3293. // - connected Ice connection is connected.
  3294. // - completed Ice connection is connected.
  3295. // - done Ice connection has been completed.
  3296. // - disconnected Ice connection has been disconnected.
  3297. // - failed Ice connection has failed.
  3298. // - closed Ice connection is closed.
  3299. AdapterJS._iceConnectionStates = {
  3300. starting : 'starting',
  3301. checking : 'checking',
  3302. connected : 'connected',
  3303. completed : 'connected',
  3304. done : 'completed',
  3305. disconnected : 'disconnected',
  3306. failed : 'failed',
  3307. closed : 'closed'
  3308. };
  3309. //The IceConnection states that has been fired for each peer.
  3310. AdapterJS._iceConnectionFiredStates = [];
  3311. // Check if WebRTC Interface is defined.
  3312. AdapterJS.isDefined = null;
  3313. // This function helps to retrieve the webrtc detected browser information.
  3314. // This sets:
  3315. // - webrtcDetectedBrowser: The browser agent name.
  3316. // - webrtcDetectedVersion: The browser version.
  3317. // - webrtcDetectedType: The types of webRTC support.
  3318. // - 'moz': Mozilla implementation of webRTC.
  3319. // - 'webkit': WebKit implementation of webRTC.
  3320. // - 'plugin': Using the plugin implementation.
  3321. AdapterJS.parseWebrtcDetectedBrowser = function () {
  3322. var hasMatch, checkMatch = navigator.userAgent.match(
  3323. /(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i) || [];
  3324. if (/trident/i.test(checkMatch[1])) {
  3325. hasMatch = /\brv[ :]+(\d+)/g.exec(navigator.userAgent) || [];
  3326. webrtcDetectedBrowser = 'IE';
  3327. webrtcDetectedVersion = parseInt(hasMatch[1] || '0', 10);
  3328. } else if (checkMatch[1] === 'Chrome') {
  3329. hasMatch = navigator.userAgent.match(/\bOPR\/(\d+)/);
  3330. if (hasMatch !== null) {
  3331. webrtcDetectedBrowser = 'opera';
  3332. webrtcDetectedVersion = parseInt(hasMatch[1], 10);
  3333. }
  3334. }
  3335. if (navigator.userAgent.indexOf('Safari')) {
  3336. if (typeof InstallTrigger !== 'undefined') {
  3337. webrtcDetectedBrowser = 'firefox';
  3338. } else if (/*@cc_on!@*/ false || !!document.documentMode) {
  3339. webrtcDetectedBrowser = 'IE';
  3340. } else if (
  3341. Object.prototype.toString.call(window.HTMLElement).indexOf('Constructor') > 0) {
  3342. webrtcDetectedBrowser = 'safari';
  3343. } else if (!!window.opera || navigator.userAgent.indexOf(' OPR/') >= 0) {
  3344. webrtcDetectedBrowser = 'opera';
  3345. } else if (!!window.chrome) {
  3346. webrtcDetectedBrowser = 'chrome';
  3347. }
  3348. }
  3349. if (!webrtcDetectedBrowser) {
  3350. webrtcDetectedVersion = checkMatch[1];
  3351. }
  3352. if (!webrtcDetectedVersion) {
  3353. try {
  3354. checkMatch = (checkMatch[2]) ? [checkMatch[1], checkMatch[2]] :
  3355. [navigator.appName, navigator.appVersion, '-?'];
  3356. if ((hasMatch = navigator.userAgent.match(/version\/(\d+)/i)) !== null) {
  3357. checkMatch.splice(1, 1, hasMatch[1]);
  3358. }
  3359. webrtcDetectedVersion = parseInt(checkMatch[1], 10);
  3360. } catch (error) { }
  3361. }
  3362. };
  3363. // To fix configuration as some browsers does not support
  3364. // the 'urls' attribute.
  3365. AdapterJS.maybeFixConfiguration = function (pcConfig) {
  3366. if (pcConfig === null) {
  3367. return;
  3368. }
  3369. for (var i = 0; i < pcConfig.iceServers.length; i++) {
  3370. if (pcConfig.iceServers[i].hasOwnProperty('urls')) {
  3371. pcConfig.iceServers[i].url = pcConfig.iceServers[i].urls;
  3372. delete pcConfig.iceServers[i].urls;
  3373. }
  3374. }
  3375. };
  3376. AdapterJS.addEvent = function(elem, evnt, func) {
  3377. if (elem.addEventListener) { // W3C DOM
  3378. elem.addEventListener(evnt, func, false);
  3379. } else if (elem.attachEvent) {// OLD IE DOM
  3380. elem.attachEvent('on'+evnt, func);
  3381. } else { // No much to do
  3382. elem[evnt] = func;
  3383. }
  3384. };
  3385. AdapterJS.renderNotificationBar = function (text, buttonText, buttonLink, openNewTab, displayRefreshBar) {
  3386. // only inject once the page is ready
  3387. if (document.readyState !== 'complete') {
  3388. return;
  3389. }
  3390. var w = window;
  3391. var i = document.createElement('iframe');
  3392. i.style.position = 'fixed';
  3393. i.style.top = '-41px';
  3394. i.style.left = 0;
  3395. i.style.right = 0;
  3396. i.style.width = '100%';
  3397. i.style.height = '40px';
  3398. i.style.backgroundColor = '#ffffe1';
  3399. i.style.border = 'none';
  3400. i.style.borderBottom = '1px solid #888888';
  3401. i.style.zIndex = '9999999';
  3402. if(typeof i.style.webkitTransition === 'string') {
  3403. i.style.webkitTransition = 'all .5s ease-out';
  3404. } else if(typeof i.style.transition === 'string') {
  3405. i.style.transition = 'all .5s ease-out';
  3406. }
  3407. document.body.appendChild(i);
  3408. c = (i.contentWindow) ? i.contentWindow :
  3409. (i.contentDocument.document) ? i.contentDocument.document : i.contentDocument;
  3410. c.document.open();
  3411. c.document.write('<span style="display: inline-block; font-family: Helvetica, Arial,' +
  3412. 'sans-serif; font-size: .9rem; padding: 4px; vertical-align: ' +
  3413. 'middle; cursor: default;">' + text + '</span>');
  3414. if(buttonText && buttonLink) {
  3415. c.document.write('<button id="okay">' + buttonText + '</button><button id="cancel">Cancel</button>');
  3416. c.document.close();
  3417. // On click on okay
  3418. AdapterJS.addEvent(c.document.getElementById('okay'), 'click', function(e) {
  3419. if (!!displayRefreshBar) {
  3420. AdapterJS.renderNotificationBar(AdapterJS.TEXT.EXTENSION ?
  3421. AdapterJS.TEXT.EXTENSION.REQUIRE_REFRESH : AdapterJS.TEXT.REFRESH.REQUIRE_REFRESH,
  3422. AdapterJS.TEXT.REFRESH.BUTTON, 'javascript:location.reload()');
  3423. }
  3424. window.open(buttonLink, !!openNewTab ? '_blank' : '_top');
  3425. e.preventDefault();
  3426. try {
  3427. event.cancelBubble = true;
  3428. } catch(error) { }
  3429. var pluginInstallInterval = setInterval(function(){
  3430. if(! isIE) {
  3431. navigator.plugins.refresh(false);
  3432. }
  3433. AdapterJS.WebRTCPlugin.isPluginInstalled(
  3434. AdapterJS.WebRTCPlugin.pluginInfo.prefix,
  3435. AdapterJS.WebRTCPlugin.pluginInfo.plugName,
  3436. function() { // plugin now installed
  3437. clearInterval(pluginInstallInterval);
  3438. AdapterJS.WebRTCPlugin.defineWebRTCInterface();
  3439. },
  3440. function() {
  3441. // still no plugin detected, nothing to do
  3442. });
  3443. } , 500);
  3444. });
  3445. // On click on Cancel
  3446. AdapterJS.addEvent(c.document.getElementById('cancel'), 'click', function(e) {
  3447. w.document.body.removeChild(i);
  3448. });
  3449. } else {
  3450. c.document.close();
  3451. }
  3452. setTimeout(function() {
  3453. if(typeof i.style.webkitTransform === 'string') {
  3454. i.style.webkitTransform = 'translateY(40px)';
  3455. } else if(typeof i.style.transform === 'string') {
  3456. i.style.transform = 'translateY(40px)';
  3457. } else {
  3458. i.style.top = '0px';
  3459. }
  3460. }, 300);
  3461. };
  3462. // -----------------------------------------------------------
  3463. // Detected webrtc implementation. Types are:
  3464. // - 'moz': Mozilla implementation of webRTC.
  3465. // - 'webkit': WebKit implementation of webRTC.
  3466. // - 'plugin': Using the plugin implementation.
  3467. webrtcDetectedType = null;
  3468. // Detected webrtc datachannel support. Types are:
  3469. // - 'SCTP': SCTP datachannel support.
  3470. // - 'RTP': RTP datachannel support.
  3471. webrtcDetectedDCSupport = null;
  3472. // Set the settings for creating DataChannels, MediaStream for
  3473. // Cross-browser compability.
  3474. // - This is only for SCTP based support browsers.
  3475. // the 'urls' attribute.
  3476. checkMediaDataChannelSettings =
  3477. function (peerBrowserAgent, peerBrowserVersion, callback, constraints) {
  3478. if (typeof callback !== 'function') {
  3479. return;
  3480. }
  3481. var beOfferer = true;
  3482. var isLocalFirefox = webrtcDetectedBrowser === 'firefox';
  3483. // Nightly version does not require MozDontOfferDataChannel for interop
  3484. var isLocalFirefoxInterop = webrtcDetectedType === 'moz' && webrtcDetectedVersion > 30;
  3485. var isPeerFirefox = peerBrowserAgent === 'firefox';
  3486. var isPeerFirefoxInterop = peerBrowserAgent === 'firefox' &&
  3487. ((peerBrowserVersion) ? (peerBrowserVersion > 30) : false);
  3488. // Resends an updated version of constraints for MozDataChannel to work
  3489. // If other userAgent is firefox and user is firefox, remove MozDataChannel
  3490. if ((isLocalFirefox && isPeerFirefox) || (isLocalFirefoxInterop)) {
  3491. try {
  3492. delete constraints.mandatory.MozDontOfferDataChannel;
  3493. } catch (error) {
  3494. console.error('Failed deleting MozDontOfferDataChannel');
  3495. console.error(error);
  3496. }
  3497. } else if ((isLocalFirefox && !isPeerFirefox)) {
  3498. constraints.mandatory.MozDontOfferDataChannel = true;
  3499. }
  3500. if (!isLocalFirefox) {
  3501. // temporary measure to remove Moz* constraints in non Firefox browsers
  3502. for (var prop in constraints.mandatory) {
  3503. if (constraints.mandatory.hasOwnProperty(prop)) {
  3504. if (prop.indexOf('Moz') !== -1) {
  3505. delete constraints.mandatory[prop];
  3506. }
  3507. }
  3508. }
  3509. }
  3510. // Firefox (not interopable) cannot offer DataChannel as it will cause problems to the
  3511. // interopability of the media stream
  3512. if (isLocalFirefox && !isPeerFirefox && !isLocalFirefoxInterop) {
  3513. beOfferer = false;
  3514. }
  3515. callback(beOfferer, constraints);
  3516. };
  3517. // Handles the differences for all browsers ice connection state output.
  3518. // - Tested outcomes are:
  3519. // - Chrome (offerer) : 'checking' > 'completed' > 'completed'
  3520. // - Chrome (answerer) : 'checking' > 'connected'
  3521. // - Firefox (offerer) : 'checking' > 'connected'
  3522. // - Firefox (answerer): 'checking' > 'connected'
  3523. checkIceConnectionState = function (peerId, iceConnectionState, callback) {
  3524. if (typeof callback !== 'function') {
  3525. console.warn('No callback specified in checkIceConnectionState. Aborted.');
  3526. return;
  3527. }
  3528. peerId = (peerId) ? peerId : 'peer';
  3529. if (!AdapterJS._iceConnectionFiredStates[peerId] ||
  3530. iceConnectionState === AdapterJS._iceConnectionStates.disconnected ||
  3531. iceConnectionState === AdapterJS._iceConnectionStates.failed ||
  3532. iceConnectionState === AdapterJS._iceConnectionStates.closed) {
  3533. AdapterJS._iceConnectionFiredStates[peerId] = [];
  3534. }
  3535. iceConnectionState = AdapterJS._iceConnectionStates[iceConnectionState];
  3536. if (AdapterJS._iceConnectionFiredStates[peerId].indexOf(iceConnectionState) < 0) {
  3537. AdapterJS._iceConnectionFiredStates[peerId].push(iceConnectionState);
  3538. if (iceConnectionState === AdapterJS._iceConnectionStates.connected) {
  3539. setTimeout(function () {
  3540. AdapterJS._iceConnectionFiredStates[peerId]
  3541. .push(AdapterJS._iceConnectionStates.done);
  3542. callback(AdapterJS._iceConnectionStates.done);
  3543. }, 1000);
  3544. }
  3545. callback(iceConnectionState);
  3546. }
  3547. return;
  3548. };
  3549. // Firefox:
  3550. // - Creates iceServer from the url for Firefox.
  3551. // - Create iceServer with stun url.
  3552. // - Create iceServer with turn url.
  3553. // - Ignore the transport parameter from TURN url for FF version <=27.
  3554. // - Return null for createIceServer if transport=tcp.
  3555. // - FF 27 and above supports transport parameters in TURN url,
  3556. // - So passing in the full url to create iceServer.
  3557. // Chrome:
  3558. // - Creates iceServer from the url for Chrome M33 and earlier.
  3559. // - Create iceServer with stun url.
  3560. // - Chrome M28 & above uses below TURN format.
  3561. // Plugin:
  3562. // - Creates Ice Server for Plugin Browsers
  3563. // - If Stun - Create iceServer with stun url.
  3564. // - Else - Create iceServer with turn url
  3565. // - This is a WebRTC Function
  3566. createIceServer = null;
  3567. // Firefox:
  3568. // - Creates IceServers for Firefox
  3569. // - Use .url for FireFox.
  3570. // - Multiple Urls support
  3571. // Chrome:
  3572. // - Creates iceServers from the urls for Chrome M34 and above.
  3573. // - .urls is supported since Chrome M34.
  3574. // - Multiple Urls support
  3575. // Plugin:
  3576. // - Creates Ice Servers for Plugin Browsers
  3577. // - Multiple Urls support
  3578. // - This is a WebRTC Function
  3579. createIceServers = null;
  3580. //------------------------------------------------------------
  3581. //The RTCPeerConnection object.
  3582. RTCPeerConnection = null;
  3583. // Creates RTCSessionDescription object for Plugin Browsers
  3584. RTCSessionDescription = (typeof RTCSessionDescription === 'function') ?
  3585. RTCSessionDescription : null;
  3586. // Creates RTCIceCandidate object for Plugin Browsers
  3587. RTCIceCandidate = (typeof RTCIceCandidate === 'function') ?
  3588. RTCIceCandidate : null;
  3589. // Get UserMedia (only difference is the prefix).
  3590. // Code from Adam Barth.
  3591. getUserMedia = null;
  3592. // Attach a media stream to an element.
  3593. attachMediaStream = null;
  3594. // Re-attach a media stream to an element.
  3595. reattachMediaStream = null;
  3596. // Detected browser agent name. Types are:
  3597. // - 'firefox': Firefox browser.
  3598. // - 'chrome': Chrome browser.
  3599. // - 'opera': Opera browser.
  3600. // - 'safari': Safari browser.
  3601. // - 'IE' - Internet Explorer browser.
  3602. webrtcDetectedBrowser = null;
  3603. // Detected browser version.
  3604. webrtcDetectedVersion = null;
  3605. // Check for browser types and react accordingly
  3606. if (navigator.mozGetUserMedia) {
  3607. webrtcDetectedBrowser = 'firefox';
  3608. webrtcDetectedVersion = parseInt(navigator
  3609. .userAgent.match(/Firefox\/([0-9]+)\./)[1], 10);
  3610. webrtcDetectedType = 'moz';
  3611. webrtcDetectedDCSupport = 'SCTP';
  3612. RTCPeerConnection = function (pcConfig, pcConstraints) {
  3613. AdapterJS.maybeFixConfiguration(pcConfig);
  3614. return new mozRTCPeerConnection(pcConfig, pcConstraints);
  3615. };
  3616. // The RTCSessionDescription object.
  3617. RTCSessionDescription = mozRTCSessionDescription;
  3618. window.RTCSessionDescription = RTCSessionDescription;
  3619. // The RTCIceCandidate object.
  3620. RTCIceCandidate = mozRTCIceCandidate;
  3621. window.RTCIceCandidate = RTCIceCandidate;
  3622. window.getUserMedia = navigator.mozGetUserMedia.bind(navigator);
  3623. navigator.getUserMedia = window.getUserMedia;
  3624. // Shim for MediaStreamTrack.getSources.
  3625. MediaStreamTrack.getSources = function(successCb) {
  3626. setTimeout(function() {
  3627. var infos = [
  3628. { kind: 'audio', id: 'default', label:'', facing:'' },
  3629. { kind: 'video', id: 'default', label:'', facing:'' }
  3630. ];
  3631. successCb(infos);
  3632. }, 0);
  3633. };
  3634. createIceServer = function (url, username, password) {
  3635. var iceServer = null;
  3636. var url_parts = url.split(':');
  3637. if (url_parts[0].indexOf('stun') === 0) {
  3638. iceServer = { url : url };
  3639. } else if (url_parts[0].indexOf('turn') === 0) {
  3640. if (webrtcDetectedVersion < 27) {
  3641. var turn_url_parts = url.split('?');
  3642. if (turn_url_parts.length === 1 ||
  3643. turn_url_parts[1].indexOf('transport=udp') === 0) {
  3644. iceServer = {
  3645. url : turn_url_parts[0],
  3646. credential : password,
  3647. username : username
  3648. };
  3649. }
  3650. } else {
  3651. iceServer = {
  3652. url : url,
  3653. credential : password,
  3654. username : username
  3655. };
  3656. }
  3657. }
  3658. return iceServer;
  3659. };
  3660. createIceServers = function (urls, username, password) {
  3661. var iceServers = [];
  3662. for (var i = 0; i < urls.length; i++) {
  3663. var iceServer = createIceServer(urls[i], username, password);
  3664. if (iceServer !== null) {
  3665. iceServers.push(iceServer);
  3666. }
  3667. }
  3668. return iceServers;
  3669. };
  3670. attachMediaStream = function (element, stream) {
  3671. element.mozSrcObject = stream;
  3672. if (stream !== null)
  3673. element.play();
  3674. return element;
  3675. };
  3676. reattachMediaStream = function (to, from) {
  3677. to.mozSrcObject = from.mozSrcObject;
  3678. to.play();
  3679. return to;
  3680. };
  3681. MediaStreamTrack.getSources = MediaStreamTrack.getSources || function (callback) {
  3682. if (!callback) {
  3683. throw new TypeError('Failed to execute \'getSources\' on \'MediaStreamTrack\'' +
  3684. ': 1 argument required, but only 0 present.');
  3685. }
  3686. return callback([]);
  3687. };
  3688. // Fake get{Video,Audio}Tracks
  3689. if (!MediaStream.prototype.getVideoTracks) {
  3690. MediaStream.prototype.getVideoTracks = function () {
  3691. return [];
  3692. };
  3693. }
  3694. if (!MediaStream.prototype.getAudioTracks) {
  3695. MediaStream.prototype.getAudioTracks = function () {
  3696. return [];
  3697. };
  3698. }
  3699. AdapterJS.maybeThroughWebRTCReady();
  3700. } else if (navigator.webkitGetUserMedia) {
  3701. webrtcDetectedBrowser = 'chrome';
  3702. webrtcDetectedType = 'webkit';
  3703. webrtcDetectedVersion = parseInt(navigator
  3704. .userAgent.match(/Chrom(e|ium)\/([0-9]+)\./)[2], 10);
  3705. // check if browser is opera 20+
  3706. var checkIfOpera = navigator.userAgent.match(/\bOPR\/(\d+)/);
  3707. if (checkIfOpera !== null) {
  3708. webrtcDetectedBrowser = 'opera';
  3709. webrtcDetectedVersion = parseInt(checkIfOpera[1], 10);
  3710. }
  3711. // check browser datachannel support
  3712. if ((webrtcDetectedBrowser === 'chrome' && webrtcDetectedVersion >= 31) ||
  3713. (webrtcDetectedBrowser === 'opera' && webrtcDetectedVersion >= 20)) {
  3714. webrtcDetectedDCSupport = 'SCTP';
  3715. } else if (webrtcDetectedBrowser === 'chrome' && webrtcDetectedVersion < 30 &&
  3716. webrtcDetectedVersion > 24) {
  3717. webrtcDetectedDCSupport = 'RTP';
  3718. } else {
  3719. webrtcDetectedDCSupport = '';
  3720. }
  3721. createIceServer = function (url, username, password) {
  3722. var iceServer = null;
  3723. var url_parts = url.split(':');
  3724. if (url_parts[0].indexOf('stun') === 0) {
  3725. iceServer = { 'url' : url };
  3726. } else if (url_parts[0].indexOf('turn') === 0) {
  3727. iceServer = {
  3728. 'url' : url,
  3729. 'credential' : password,
  3730. 'username' : username
  3731. };
  3732. }
  3733. return iceServer;
  3734. };
  3735. createIceServers = function (urls, username, password) {
  3736. var iceServers = [];
  3737. if (webrtcDetectedVersion >= 34) {
  3738. iceServers = {
  3739. 'urls' : urls,
  3740. 'credential' : password,
  3741. 'username' : username
  3742. };
  3743. } else {
  3744. for (var i = 0; i < urls.length; i++) {
  3745. var iceServer = createIceServer(urls[i], username, password);
  3746. if (iceServer !== null) {
  3747. iceServers.push(iceServer);
  3748. }
  3749. }
  3750. }
  3751. return iceServers;
  3752. };
  3753. RTCPeerConnection = function (pcConfig, pcConstraints) {
  3754. if (webrtcDetectedVersion < 34) {
  3755. AdapterJS.maybeFixConfiguration(pcConfig);
  3756. }
  3757. return new webkitRTCPeerConnection(pcConfig, pcConstraints);
  3758. };
  3759. window.getUserMedia = navigator.webkitGetUserMedia.bind(navigator);
  3760. navigator.getUserMedia = window.getUserMedia;
  3761. attachMediaStream = function (element, stream) {
  3762. if (typeof element.srcObject !== 'undefined') {
  3763. element.srcObject = stream;
  3764. } else if (typeof element.mozSrcObject !== 'undefined') {
  3765. element.mozSrcObject = stream;
  3766. } else if (typeof element.src !== 'undefined') {
  3767. element.src = (stream === null ? '' : URL.createObjectURL(stream));
  3768. } else {
  3769. console.log('Error attaching stream to element.');
  3770. }
  3771. return element;
  3772. };
  3773. reattachMediaStream = function (to, from) {
  3774. to.src = from.src;
  3775. return to;
  3776. };
  3777. AdapterJS.maybeThroughWebRTCReady();
  3778. } else if (navigator.mediaDevices && navigator.userAgent.match(
  3779. /Edge\/(\d+).(\d+)$/)) {
  3780. webrtcDetectedBrowser = 'edge';
  3781. webrtcDetectedVersion =
  3782. parseInt(navigator.userAgent.match(/Edge\/(\d+).(\d+)$/)[2], 10);
  3783. // the minimum version still supported by adapter.
  3784. webrtcMinimumVersion = 12;
  3785. window.getUserMedia = navigator.getUserMedia.bind(navigator);
  3786. attachMediaStream = function(element, stream) {
  3787. element.srcObject = stream;
  3788. return element;
  3789. };
  3790. reattachMediaStream = function(to, from) {
  3791. to.srcObject = from.srcObject;
  3792. return to;
  3793. };
  3794. AdapterJS.maybeThroughWebRTCReady();
  3795. } else { // TRY TO USE PLUGIN
  3796. // IE 9 is not offering an implementation of console.log until you open a console
  3797. if (typeof console !== 'object' || typeof console.log !== 'function') {
  3798. /* jshint -W020 */
  3799. console = {} || console;
  3800. // Implemented based on console specs from MDN
  3801. // You may override these functions
  3802. console.log = function (arg) {};
  3803. console.info = function (arg) {};
  3804. console.error = function (arg) {};
  3805. console.dir = function (arg) {};
  3806. console.exception = function (arg) {};
  3807. console.trace = function (arg) {};
  3808. console.warn = function (arg) {};
  3809. console.count = function (arg) {};
  3810. console.debug = function (arg) {};
  3811. console.count = function (arg) {};
  3812. console.time = function (arg) {};
  3813. console.timeEnd = function (arg) {};
  3814. console.group = function (arg) {};
  3815. console.groupCollapsed = function (arg) {};
  3816. console.groupEnd = function (arg) {};
  3817. /* jshint +W020 */
  3818. }
  3819. webrtcDetectedType = 'plugin';
  3820. webrtcDetectedDCSupport = 'plugin';
  3821. AdapterJS.parseWebrtcDetectedBrowser();
  3822. isIE = webrtcDetectedBrowser === 'IE';
  3823. /* jshint -W035 */
  3824. AdapterJS.WebRTCPlugin.WaitForPluginReady = function() {
  3825. while (AdapterJS.WebRTCPlugin.pluginState !== AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY) {
  3826. /* empty because it needs to prevent the function from running. */
  3827. }
  3828. };
  3829. /* jshint +W035 */
  3830. AdapterJS.WebRTCPlugin.callWhenPluginReady = function (callback) {
  3831. if (AdapterJS.WebRTCPlugin.pluginState === AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY) {
  3832. // Call immediately if possible
  3833. // Once the plugin is set, the code will always take this path
  3834. callback();
  3835. } else {
  3836. // otherwise start a 100ms interval
  3837. var checkPluginReadyState = setInterval(function () {
  3838. if (AdapterJS.WebRTCPlugin.pluginState === AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY) {
  3839. clearInterval(checkPluginReadyState);
  3840. callback();
  3841. }
  3842. }, 100);
  3843. }
  3844. };
  3845. AdapterJS.WebRTCPlugin.setLogLevel = function(logLevel) {
  3846. AdapterJS.WebRTCPlugin.callWhenPluginReady(function() {
  3847. AdapterJS.WebRTCPlugin.plugin.setLogLevel(logLevel);
  3848. });
  3849. };
  3850. AdapterJS.WebRTCPlugin.injectPlugin = function () {
  3851. // only inject once the page is ready
  3852. if (document.readyState !== 'complete') {
  3853. return;
  3854. }
  3855. // Prevent multiple injections
  3856. if (AdapterJS.WebRTCPlugin.pluginState !== AdapterJS.WebRTCPlugin.PLUGIN_STATES.INITIALIZING) {
  3857. return;
  3858. }
  3859. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.INJECTING;
  3860. if (webrtcDetectedBrowser === 'IE' && webrtcDetectedVersion <= 10) {
  3861. var frag = document.createDocumentFragment();
  3862. AdapterJS.WebRTCPlugin.plugin = document.createElement('div');
  3863. AdapterJS.WebRTCPlugin.plugin.innerHTML = '<object id="' +
  3864. AdapterJS.WebRTCPlugin.pluginInfo.pluginId + '" type="' +
  3865. AdapterJS.WebRTCPlugin.pluginInfo.type + '" ' + 'width="1" height="1">' +
  3866. '<param name="pluginId" value="' +
  3867. AdapterJS.WebRTCPlugin.pluginInfo.pluginId + '" /> ' +
  3868. '<param name="windowless" value="false" /> ' +
  3869. '<param name="pageId" value="' + AdapterJS.WebRTCPlugin.pageId + '" /> ' +
  3870. '<param name="onload" value="' + AdapterJS.WebRTCPlugin.pluginInfo.onload + '" />' +
  3871. '<param name="tag" value="' + AdapterJS.WebRTCPlugin.TAGS.NONE + '" />' +
  3872. // uncomment to be able to use virtual cams
  3873. (AdapterJS.options.getAllCams ? '<param name="forceGetAllCams" value="True" />':'') +
  3874. '</object>';
  3875. while (AdapterJS.WebRTCPlugin.plugin.firstChild) {
  3876. frag.appendChild(AdapterJS.WebRTCPlugin.plugin.firstChild);
  3877. }
  3878. document.body.appendChild(frag);
  3879. // Need to re-fetch the plugin
  3880. AdapterJS.WebRTCPlugin.plugin =
  3881. document.getElementById(AdapterJS.WebRTCPlugin.pluginInfo.pluginId);
  3882. } else {
  3883. // Load Plugin
  3884. AdapterJS.WebRTCPlugin.plugin = document.createElement('object');
  3885. AdapterJS.WebRTCPlugin.plugin.id =
  3886. AdapterJS.WebRTCPlugin.pluginInfo.pluginId;
  3887. // IE will only start the plugin if it's ACTUALLY visible
  3888. if (isIE) {
  3889. AdapterJS.WebRTCPlugin.plugin.width = '1px';
  3890. AdapterJS.WebRTCPlugin.plugin.height = '1px';
  3891. } else { // The size of the plugin on Safari should be 0x0px
  3892. // so that the autorisation prompt is at the top
  3893. AdapterJS.WebRTCPlugin.plugin.width = '0px';
  3894. AdapterJS.WebRTCPlugin.plugin.height = '0px';
  3895. }
  3896. AdapterJS.WebRTCPlugin.plugin.type = AdapterJS.WebRTCPlugin.pluginInfo.type;
  3897. AdapterJS.WebRTCPlugin.plugin.innerHTML = '<param name="onload" value="' +
  3898. AdapterJS.WebRTCPlugin.pluginInfo.onload + '">' +
  3899. '<param name="pluginId" value="' +
  3900. AdapterJS.WebRTCPlugin.pluginInfo.pluginId + '">' +
  3901. '<param name="windowless" value="false" /> ' +
  3902. (AdapterJS.options.getAllCams ? '<param name="forceGetAllCams" value="True" />':'') +
  3903. '<param name="pageId" value="' + AdapterJS.WebRTCPlugin.pageId + '">' +
  3904. '<param name="tag" value="' + AdapterJS.WebRTCPlugin.TAGS.NONE + '" />';
  3905. document.body.appendChild(AdapterJS.WebRTCPlugin.plugin);
  3906. }
  3907. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.INJECTED;
  3908. };
  3909. AdapterJS.WebRTCPlugin.isPluginInstalled =
  3910. function (comName, plugName, installedCb, notInstalledCb) {
  3911. if (!isIE) {
  3912. var pluginArray = navigator.plugins;
  3913. for (var i = 0; i < pluginArray.length; i++) {
  3914. if (pluginArray[i].name.indexOf(plugName) >= 0) {
  3915. installedCb();
  3916. return;
  3917. }
  3918. }
  3919. notInstalledCb();
  3920. } else {
  3921. try {
  3922. var axo = new ActiveXObject(comName + '.' + plugName);
  3923. } catch (e) {
  3924. notInstalledCb();
  3925. return;
  3926. }
  3927. installedCb();
  3928. }
  3929. };
  3930. AdapterJS.WebRTCPlugin.defineWebRTCInterface = function () {
  3931. if (AdapterJS.WebRTCPlugin.pluginState ===
  3932. AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY) {
  3933. console.error("AdapterJS - WebRTC interface has already been defined");
  3934. return;
  3935. }
  3936. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.INITIALIZING;
  3937. AdapterJS.isDefined = function (variable) {
  3938. return variable !== null && variable !== undefined;
  3939. };
  3940. createIceServer = function (url, username, password) {
  3941. var iceServer = null;
  3942. var url_parts = url.split(':');
  3943. if (url_parts[0].indexOf('stun') === 0) {
  3944. iceServer = {
  3945. 'url' : url,
  3946. 'hasCredentials' : false
  3947. };
  3948. } else if (url_parts[0].indexOf('turn') === 0) {
  3949. iceServer = {
  3950. 'url' : url,
  3951. 'hasCredentials' : true,
  3952. 'credential' : password,
  3953. 'username' : username
  3954. };
  3955. }
  3956. return iceServer;
  3957. };
  3958. createIceServers = function (urls, username, password) {
  3959. var iceServers = [];
  3960. for (var i = 0; i < urls.length; ++i) {
  3961. iceServers.push(createIceServer(urls[i], username, password));
  3962. }
  3963. return iceServers;
  3964. };
  3965. RTCSessionDescription = function (info) {
  3966. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  3967. return AdapterJS.WebRTCPlugin.plugin.
  3968. ConstructSessionDescription(info.type, info.sdp);
  3969. };
  3970. RTCPeerConnection = function (servers, constraints) {
  3971. var iceServers = null;
  3972. if (servers) {
  3973. iceServers = servers.iceServers;
  3974. for (var i = 0; i < iceServers.length; i++) {
  3975. if (iceServers[i].urls && !iceServers[i].url) {
  3976. iceServers[i].url = iceServers[i].urls;
  3977. }
  3978. iceServers[i].hasCredentials = AdapterJS.
  3979. isDefined(iceServers[i].username) &&
  3980. AdapterJS.isDefined(iceServers[i].credential);
  3981. }
  3982. }
  3983. var mandatory = (constraints && constraints.mandatory) ?
  3984. constraints.mandatory : null;
  3985. var optional = (constraints && constraints.optional) ?
  3986. constraints.optional : null;
  3987. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  3988. return AdapterJS.WebRTCPlugin.plugin.
  3989. PeerConnection(AdapterJS.WebRTCPlugin.pageId,
  3990. iceServers, mandatory, optional);
  3991. };
  3992. MediaStreamTrack = {};
  3993. MediaStreamTrack.getSources = function (callback) {
  3994. AdapterJS.WebRTCPlugin.callWhenPluginReady(function() {
  3995. AdapterJS.WebRTCPlugin.plugin.GetSources(callback);
  3996. });
  3997. };
  3998. window.getUserMedia = function (constraints, successCallback, failureCallback) {
  3999. constraints.audio = constraints.audio || false;
  4000. constraints.video = constraints.video || false;
  4001. AdapterJS.WebRTCPlugin.callWhenPluginReady(function() {
  4002. AdapterJS.WebRTCPlugin.plugin.
  4003. getUserMedia(constraints, successCallback, failureCallback);
  4004. });
  4005. };
  4006. window.navigator.getUserMedia = window.getUserMedia;
  4007. attachMediaStream = function (element, stream) {
  4008. if (!element || !element.parentNode) {
  4009. return;
  4010. }
  4011. var streamId;
  4012. if (stream === null) {
  4013. streamId = '';
  4014. } else {
  4015. if (typeof stream.enableSoundTracks !== 'undefined') {
  4016. stream.enableSoundTracks(true);
  4017. }
  4018. streamId = stream.id;
  4019. }
  4020. var elementId = element.id.length === 0 ? Math.random().toString(36).slice(2) : element.id;
  4021. var nodeName = element.nodeName.toLowerCase();
  4022. if (nodeName !== 'object') { // not a plugin <object> tag yet
  4023. var tag;
  4024. switch(nodeName) {
  4025. case 'audio':
  4026. tag = AdapterJS.WebRTCPlugin.TAGS.AUDIO;
  4027. break;
  4028. case 'video':
  4029. tag = AdapterJS.WebRTCPlugin.TAGS.VIDEO;
  4030. break;
  4031. default:
  4032. tag = AdapterJS.WebRTCPlugin.TAGS.NONE;
  4033. }
  4034. var frag = document.createDocumentFragment();
  4035. var temp = document.createElement('div');
  4036. var classHTML = '';
  4037. if (element.className) {
  4038. classHTML = 'class="' + element.className + '" ';
  4039. } else if (element.attributes && element.attributes['class']) {
  4040. classHTML = 'class="' + element.attributes['class'].value + '" ';
  4041. }
  4042. temp.innerHTML = '<object id="' + elementId + '" ' + classHTML +
  4043. 'type="' + AdapterJS.WebRTCPlugin.pluginInfo.type + '">' +
  4044. '<param name="pluginId" value="' + elementId + '" /> ' +
  4045. '<param name="pageId" value="' + AdapterJS.WebRTCPlugin.pageId + '" /> ' +
  4046. '<param name="windowless" value="true" /> ' +
  4047. '<param name="streamId" value="' + streamId + '" /> ' +
  4048. '<param name="tag" value="' + tag + '" /> ' +
  4049. '</object>';
  4050. while (temp.firstChild) {
  4051. frag.appendChild(temp.firstChild);
  4052. }
  4053. var height = '';
  4054. var width = '';
  4055. if (element.clientWidth || element.clientHeight) {
  4056. width = element.clientWidth;
  4057. height = element.clientHeight;
  4058. }
  4059. else if (element.width || element.height) {
  4060. width = element.width;
  4061. height = element.height;
  4062. }
  4063. element.parentNode.insertBefore(frag, element);
  4064. frag = document.getElementById(elementId);
  4065. frag.width = width;
  4066. frag.height = height;
  4067. element.parentNode.removeChild(element);
  4068. } else { // already an <object> tag, just change the stream id
  4069. var children = element.children;
  4070. for (var i = 0; i !== children.length; ++i) {
  4071. if (children[i].name === 'streamId') {
  4072. children[i].value = streamId;
  4073. break;
  4074. }
  4075. }
  4076. element.setStreamId(streamId);
  4077. }
  4078. var newElement = document.getElementById(elementId);
  4079. AdapterJS.forwardEventHandlers(newElement, element, Object.getPrototypeOf(element));
  4080. return newElement;
  4081. };
  4082. reattachMediaStream = function (to, from) {
  4083. var stream = null;
  4084. var children = from.children;
  4085. for (var i = 0; i !== children.length; ++i) {
  4086. if (children[i].name === 'streamId') {
  4087. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  4088. stream = AdapterJS.WebRTCPlugin.plugin
  4089. .getStreamWithId(AdapterJS.WebRTCPlugin.pageId, children[i].value);
  4090. break;
  4091. }
  4092. }
  4093. if (stream !== null) {
  4094. return attachMediaStream(to, stream);
  4095. } else {
  4096. console.log('Could not find the stream associated with this element');
  4097. }
  4098. };
  4099. AdapterJS.forwardEventHandlers = function (destElem, srcElem, prototype) {
  4100. properties = Object.getOwnPropertyNames( prototype );
  4101. for(prop in properties) {
  4102. propName = properties[prop];
  4103. if (typeof(propName.slice) === 'function') {
  4104. if (propName.slice(0,2) == 'on' && srcElem[propName] != null) {
  4105. if (isIE) {
  4106. destElem.attachEvent(propName,srcElem[propName]);
  4107. } else {
  4108. destElem.addEventListener(propName.slice(2), srcElem[propName], false)
  4109. }
  4110. } else {
  4111. //TODO (http://jira.temasys.com.sg/browse/TWP-328) Forward non-event properties ?
  4112. }
  4113. }
  4114. }
  4115. var subPrototype = Object.getPrototypeOf(prototype)
  4116. if(subPrototype != null) {
  4117. AdapterJS.forwardEventHandlers(destElem, srcElem, subPrototype);
  4118. }
  4119. }
  4120. RTCIceCandidate = function (candidate) {
  4121. if (!candidate.sdpMid) {
  4122. candidate.sdpMid = '';
  4123. }
  4124. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  4125. return AdapterJS.WebRTCPlugin.plugin.ConstructIceCandidate(
  4126. candidate.sdpMid, candidate.sdpMLineIndex, candidate.candidate
  4127. );
  4128. };
  4129. // inject plugin
  4130. AdapterJS.addEvent(document, 'readystatechange', AdapterJS.WebRTCPlugin.injectPlugin);
  4131. AdapterJS.WebRTCPlugin.injectPlugin();
  4132. };
  4133. // This function will be called if the plugin is needed (browser different
  4134. // from Chrome or Firefox), but the plugin is not installed.
  4135. AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCb = AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCb ||
  4136. function() {
  4137. AdapterJS.addEvent(document,
  4138. 'readystatechange',
  4139. AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCbPriv);
  4140. AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCbPriv();
  4141. };
  4142. AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCbPriv = function () {
  4143. if (AdapterJS.options.hidePluginInstallPrompt) {
  4144. return;
  4145. }
  4146. var downloadLink = AdapterJS.WebRTCPlugin.pluginInfo.downloadLink;
  4147. if(downloadLink) { // if download link
  4148. var popupString;
  4149. if (AdapterJS.WebRTCPlugin.pluginInfo.portalLink) { // is portal link
  4150. popupString = 'This website requires you to install the ' +
  4151. ' <a href="' + AdapterJS.WebRTCPlugin.pluginInfo.portalLink +
  4152. '" target="_blank">' + AdapterJS.WebRTCPlugin.pluginInfo.companyName +
  4153. ' WebRTC Plugin</a>' +
  4154. ' to work on this browser.';
  4155. } else { // no portal link, just print a generic explanation
  4156. popupString = AdapterJS.TEXT.PLUGIN.REQUIRE_INSTALLATION;
  4157. }
  4158. AdapterJS.renderNotificationBar(popupString, AdapterJS.TEXT.PLUGIN.BUTTON, downloadLink);
  4159. } else { // no download link, just print a generic explanation
  4160. AdapterJS.renderNotificationBar(AdapterJS.TEXT.PLUGIN.NOT_SUPPORTED);
  4161. }
  4162. };
  4163. // Try to detect the plugin and act accordingly
  4164. AdapterJS.WebRTCPlugin.isPluginInstalled(
  4165. AdapterJS.WebRTCPlugin.pluginInfo.prefix,
  4166. AdapterJS.WebRTCPlugin.pluginInfo.plugName,
  4167. AdapterJS.WebRTCPlugin.defineWebRTCInterface,
  4168. AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCb);
  4169. }
  4170. }).call(this,"/modules/RTC/adapter.screenshare.js")
  4171. },{"jitsi-meet-logger":47}],21:[function(require,module,exports){
  4172. (function (__filename){
  4173. var logger = require("jitsi-meet-logger").getLogger(__filename);
  4174. function supportsLocalStorage() {
  4175. try {
  4176. return 'localStorage' in window && window.localStorage !== null;
  4177. } catch (e) {
  4178. logger.log("localstorage is not supported");
  4179. return false;
  4180. }
  4181. }
  4182. function generateUniqueId() {
  4183. function _p8() {
  4184. return (Math.random().toString(16) + "000000000").substr(2, 8);
  4185. }
  4186. return _p8() + _p8() + _p8() + _p8();
  4187. }
  4188. function Settings(conferenceID) {
  4189. this.email = '';
  4190. this.displayName = '';
  4191. this.userId;
  4192. this.language = null;
  4193. this.confSettings = null;
  4194. this.conferenceID = conferenceID;
  4195. if (supportsLocalStorage()) {
  4196. if(!window.localStorage.getItem(conferenceID))
  4197. this.confSettings = {};
  4198. else
  4199. this.confSettings = JSON.parse(window.localStorage.getItem(conferenceID));
  4200. if(!this.confSettings.jitsiMeetId) {
  4201. this.confSettings.jitsiMeetId = generateUniqueId();
  4202. logger.log("generated id",
  4203. this.confSettings.jitsiMeetId);
  4204. this.save();
  4205. }
  4206. this.userId = this.confSettings.jitsiMeetId || '';
  4207. this.email = this.confSettings.email || '';
  4208. this.displayName = this.confSettings.displayname || '';
  4209. this.language = this.confSettings.language;
  4210. } else {
  4211. logger.log("local storage is not supported");
  4212. this.userId = generateUniqueId();
  4213. }
  4214. }
  4215. Settings.prototype.save = function () {
  4216. if(!supportsLocalStorage())
  4217. window.localStorage.setItem(this.conferenceID, JSON.stringify(this.confSettings));
  4218. }
  4219. Settings.prototype.setDisplayName = function (newDisplayName) {
  4220. this.displayName = newDisplayName;
  4221. if(this.confSettings != null)
  4222. this.confSettings.displayname = displayName;
  4223. this.save();
  4224. return this.displayName;
  4225. },
  4226. Settings.prototype.setEmail = function (newEmail) {
  4227. this.email = newEmail;
  4228. if(this.confSettings != null)
  4229. this.confSettings.email = newEmail;
  4230. this.save();
  4231. return this.email;
  4232. },
  4233. Settings.prototype.getSettings = function () {
  4234. return {
  4235. email: this.email,
  4236. displayName: this.displayName,
  4237. uid: this.userId,
  4238. language: this.language
  4239. };
  4240. },
  4241. Settings.prototype.setLanguage = function (lang) {
  4242. this.language = lang;
  4243. if(this.confSettings != null)
  4244. this.confSettings.language = lang;
  4245. this.save();
  4246. }
  4247. module.exports = Settings;
  4248. }).call(this,"/modules/settings/Settings.js")
  4249. },{"jitsi-meet-logger":47}],22:[function(require,module,exports){
  4250. /* global config */
  4251. /**
  4252. * Provides statistics for the local stream.
  4253. */
  4254. var RTCBrowserType = require('../RTC/RTCBrowserType');
  4255. /**
  4256. * Size of the webaudio analyzer buffer.
  4257. * @type {number}
  4258. */
  4259. var WEBAUDIO_ANALYZER_FFT_SIZE = 2048;
  4260. /**
  4261. * Value of the webaudio analyzer smoothing time parameter.
  4262. * @type {number}
  4263. */
  4264. var WEBAUDIO_ANALYZER_SMOOTING_TIME = 0.8;
  4265. /**
  4266. * Converts time domain data array to audio level.
  4267. * @param samples the time domain data array.
  4268. * @returns {number} the audio level
  4269. */
  4270. function timeDomainDataToAudioLevel(samples) {
  4271. var maxVolume = 0;
  4272. var length = samples.length;
  4273. for (var i = 0; i < length; i++) {
  4274. if (maxVolume < samples[i])
  4275. maxVolume = samples[i];
  4276. }
  4277. return parseFloat(((maxVolume - 127) / 128).toFixed(3));
  4278. }
  4279. /**
  4280. * Animates audio level change
  4281. * @param newLevel the new audio level
  4282. * @param lastLevel the last audio level
  4283. * @returns {Number} the audio level to be set
  4284. */
  4285. function animateLevel(newLevel, lastLevel) {
  4286. var value = 0;
  4287. var diff = lastLevel - newLevel;
  4288. if(diff > 0.2) {
  4289. value = lastLevel - 0.2;
  4290. }
  4291. else if(diff < -0.4) {
  4292. value = lastLevel + 0.4;
  4293. }
  4294. else {
  4295. value = newLevel;
  4296. }
  4297. return parseFloat(value.toFixed(3));
  4298. }
  4299. /**
  4300. * <tt>LocalStatsCollector</tt> calculates statistics for the local stream.
  4301. *
  4302. * @param stream the local stream
  4303. * @param interval stats refresh interval given in ms.
  4304. * @param callback function that receives the audio levels.
  4305. * @constructor
  4306. */
  4307. function LocalStatsCollector(stream, interval, callback) {
  4308. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  4309. this.stream = stream;
  4310. this.intervalId = null;
  4311. this.intervalMilis = interval;
  4312. this.audioLevel = 0;
  4313. this.callback = callback;
  4314. }
  4315. /**
  4316. * Starts the collecting the statistics.
  4317. */
  4318. LocalStatsCollector.prototype.start = function () {
  4319. if (!window.AudioContext ||
  4320. RTCBrowserType.isTemasysPluginUsed())
  4321. return;
  4322. var context = new AudioContext();
  4323. var analyser = context.createAnalyser();
  4324. analyser.smoothingTimeConstant = WEBAUDIO_ANALYZER_SMOOTING_TIME;
  4325. analyser.fftSize = WEBAUDIO_ANALYZER_FFT_SIZE;
  4326. var source = context.createMediaStreamSource(this.stream);
  4327. source.connect(analyser);
  4328. var self = this;
  4329. this.intervalId = setInterval(
  4330. function () {
  4331. var array = new Uint8Array(analyser.frequencyBinCount);
  4332. analyser.getByteTimeDomainData(array);
  4333. var audioLevel = timeDomainDataToAudioLevel(array);
  4334. if (audioLevel != self.audioLevel) {
  4335. self.audioLevel = animateLevel(audioLevel, self.audioLevel);
  4336. self.callback(self.audioLevel);
  4337. }
  4338. },
  4339. this.intervalMilis
  4340. );
  4341. };
  4342. /**
  4343. * Stops collecting the statistics.
  4344. */
  4345. LocalStatsCollector.prototype.stop = function () {
  4346. if (this.intervalId) {
  4347. clearInterval(this.intervalId);
  4348. this.intervalId = null;
  4349. }
  4350. };
  4351. module.exports = LocalStatsCollector;
  4352. },{"../RTC/RTCBrowserType":17}],23:[function(require,module,exports){
  4353. (function (__filename){
  4354. /* global require, ssrc2jid */
  4355. /* jshint -W117 */
  4356. var logger = require("jitsi-meet-logger").getLogger(__filename);
  4357. var RTCBrowserType = require("../RTC/RTCBrowserType");
  4358. var StatisticsEvents = require("../../service/statistics/Events");
  4359. /* Whether we support the browser we are running into for logging statistics */
  4360. var browserSupported = RTCBrowserType.isChrome() ||
  4361. RTCBrowserType.isOpera();
  4362. var keyMap = {};
  4363. keyMap[RTCBrowserType.RTC_BROWSER_FIREFOX] = {
  4364. "ssrc": "ssrc",
  4365. "packetsReceived": "packetsReceived",
  4366. "packetsLost": "packetsLost",
  4367. "packetsSent": "packetsSent",
  4368. "bytesReceived": "bytesReceived",
  4369. "bytesSent": "bytesSent"
  4370. };
  4371. keyMap[RTCBrowserType.RTC_BROWSER_CHROME] = {
  4372. "receiveBandwidth": "googAvailableReceiveBandwidth",
  4373. "sendBandwidth": "googAvailableSendBandwidth",
  4374. "remoteAddress": "googRemoteAddress",
  4375. "transportType": "googTransportType",
  4376. "localAddress": "googLocalAddress",
  4377. "activeConnection": "googActiveConnection",
  4378. "ssrc": "ssrc",
  4379. "packetsReceived": "packetsReceived",
  4380. "packetsSent": "packetsSent",
  4381. "packetsLost": "packetsLost",
  4382. "bytesReceived": "bytesReceived",
  4383. "bytesSent": "bytesSent",
  4384. "googFrameHeightReceived": "googFrameHeightReceived",
  4385. "googFrameWidthReceived": "googFrameWidthReceived",
  4386. "googFrameHeightSent": "googFrameHeightSent",
  4387. "googFrameWidthSent": "googFrameWidthSent",
  4388. "audioInputLevel": "audioInputLevel",
  4389. "audioOutputLevel": "audioOutputLevel"
  4390. };
  4391. keyMap[RTCBrowserType.RTC_BROWSER_OPERA] =
  4392. keyMap[RTCBrowserType.RTC_BROWSER_CHROME];
  4393. /**
  4394. * Calculates packet lost percent using the number of lost packets and the
  4395. * number of all packet.
  4396. * @param lostPackets the number of lost packets
  4397. * @param totalPackets the number of all packets.
  4398. * @returns {number} packet loss percent
  4399. */
  4400. function calculatePacketLoss(lostPackets, totalPackets) {
  4401. if(!totalPackets || totalPackets <= 0 || !lostPackets || lostPackets <= 0)
  4402. return 0;
  4403. return Math.round((lostPackets/totalPackets)*100);
  4404. }
  4405. function getStatValue(item, name) {
  4406. var browserType = RTCBrowserType.getBrowserType();
  4407. if (!keyMap[browserType][name])
  4408. throw "The property isn't supported!";
  4409. var key = keyMap[browserType][name];
  4410. return (RTCBrowserType.isChrome() || RTCBrowserType.isOpera()) ?
  4411. item.stat(key) : item[key];
  4412. }
  4413. function formatAudioLevel(audioLevel) {
  4414. return Math.min(Math.max(audioLevel, 0), 1);
  4415. }
  4416. /**
  4417. * Checks whether a certain record should be included in the logged statistics.
  4418. */
  4419. function acceptStat(reportId, reportType, statName) {
  4420. if (reportType == "googCandidatePair" && statName == "googChannelId")
  4421. return false;
  4422. if (reportType == "ssrc") {
  4423. if (statName == "googTrackId" ||
  4424. statName == "transportId" ||
  4425. statName == "ssrc")
  4426. return false;
  4427. }
  4428. return true;
  4429. }
  4430. /**
  4431. * Checks whether a certain record should be included in the logged statistics.
  4432. */
  4433. function acceptReport(id, type) {
  4434. if (id.substring(0, 15) == "googCertificate" ||
  4435. id.substring(0, 9) == "googTrack" ||
  4436. id.substring(0, 20) == "googLibjingleSession")
  4437. return false;
  4438. if (type == "googComponent")
  4439. return false;
  4440. return true;
  4441. }
  4442. /**
  4443. * Peer statistics data holder.
  4444. * @constructor
  4445. */
  4446. function PeerStats()
  4447. {
  4448. this.ssrc2Loss = {};
  4449. this.ssrc2AudioLevel = {};
  4450. this.ssrc2bitrate = {};
  4451. this.ssrc2resolution = {};
  4452. }
  4453. /**
  4454. * Sets packets loss rate for given <tt>ssrc</tt> that blong to the peer
  4455. * represented by this instance.
  4456. * @param lossRate new packet loss rate value to be set.
  4457. */
  4458. PeerStats.prototype.setSsrcLoss = function (lossRate)
  4459. {
  4460. this.ssrc2Loss = lossRate;
  4461. };
  4462. /**
  4463. * Sets resolution that belong to the ssrc
  4464. * represented by this instance.
  4465. * @param resolution new resolution value to be set.
  4466. */
  4467. PeerStats.prototype.setSsrcResolution = function (resolution)
  4468. {
  4469. if(resolution === null && this.ssrc2resolution[ssrc])
  4470. {
  4471. delete this.ssrc2resolution[ssrc];
  4472. }
  4473. else if(resolution !== null)
  4474. this.ssrc2resolution[ssrc] = resolution;
  4475. };
  4476. /**
  4477. * Sets the bit rate for given <tt>ssrc</tt> that blong to the peer
  4478. * represented by this instance.
  4479. * @param ssrc audio or video RTP stream SSRC.
  4480. * @param bitrate new bitrate value to be set.
  4481. */
  4482. PeerStats.prototype.setSsrcBitrate = function (ssrc, bitrate)
  4483. {
  4484. if(this.ssrc2bitrate[ssrc])
  4485. {
  4486. this.ssrc2bitrate[ssrc].download += bitrate.download;
  4487. this.ssrc2bitrate[ssrc].upload += bitrate.upload;
  4488. }
  4489. else {
  4490. this.ssrc2bitrate[ssrc] = bitrate;
  4491. }
  4492. };
  4493. /**
  4494. * Sets new audio level(input or output) for given <tt>ssrc</tt> that identifies
  4495. * the stream which belongs to the peer represented by this instance.
  4496. * @param ssrc RTP stream SSRC for which current audio level value will be
  4497. * updated.
  4498. * @param audioLevel the new audio level value to be set. Value is truncated to
  4499. * fit the range from 0 to 1.
  4500. */
  4501. PeerStats.prototype.setSsrcAudioLevel = function (ssrc, audioLevel)
  4502. {
  4503. // Range limit 0 - 1
  4504. this.ssrc2AudioLevel[ssrc] = formatAudioLevel(audioLevel);
  4505. };
  4506. function ConferenceStats() {
  4507. /**
  4508. * The bandwidth
  4509. * @type {{}}
  4510. */
  4511. this.bandwidth = {};
  4512. /**
  4513. * The bit rate
  4514. * @type {{}}
  4515. */
  4516. this.bitrate = {};
  4517. /**
  4518. * The packet loss rate
  4519. * @type {{}}
  4520. */
  4521. this.packetLoss = null;
  4522. /**
  4523. * Array with the transport information.
  4524. * @type {Array}
  4525. */
  4526. this.transport = [];
  4527. }
  4528. /**
  4529. * <tt>StatsCollector</tt> registers for stats updates of given
  4530. * <tt>peerconnection</tt> in given <tt>interval</tt>. On each update particular
  4531. * stats are extracted and put in {@link PeerStats} objects. Once the processing
  4532. * is done <tt>audioLevelsUpdateCallback</tt> is called with <tt>this</tt>
  4533. * instance as an event source.
  4534. *
  4535. * @param peerconnection webRTC peer connection object.
  4536. * @param interval stats refresh interval given in ms.
  4537. * @param {function(StatsCollector)} audioLevelsUpdateCallback the callback
  4538. * called on stats update.
  4539. * @param config {object} supports the following properties - disableAudioLevels, disableStats, logStats
  4540. * @constructor
  4541. */
  4542. function StatsCollector(peerconnection, audioLevelsInterval, statsInterval, eventEmitter, config)
  4543. {
  4544. this.peerconnection = peerconnection;
  4545. this.baselineAudioLevelsReport = null;
  4546. this.currentAudioLevelsReport = null;
  4547. this.currentStatsReport = null;
  4548. this.baselineStatsReport = null;
  4549. this.audioLevelsIntervalId = null;
  4550. this.eventEmitter = eventEmitter;
  4551. this.config = config || {};
  4552. this.conferenceStats = new ConferenceStats();
  4553. /**
  4554. * Gather PeerConnection stats once every this many milliseconds.
  4555. */
  4556. this.GATHER_INTERVAL = 15000;
  4557. /**
  4558. * Log stats via the focus once every this many milliseconds.
  4559. */
  4560. this.LOG_INTERVAL = 60000;
  4561. /**
  4562. * Gather stats and store them in this.statsToBeLogged.
  4563. */
  4564. this.gatherStatsIntervalId = null;
  4565. /**
  4566. * Send the stats already saved in this.statsToBeLogged to be logged via
  4567. * the focus.
  4568. */
  4569. this.logStatsIntervalId = null;
  4570. /**
  4571. * Stores the statistics which will be send to the focus to be logged.
  4572. */
  4573. this.statsToBeLogged =
  4574. {
  4575. timestamps: [],
  4576. stats: {}
  4577. };
  4578. // Updates stats interval
  4579. this.audioLevelsIntervalMilis = audioLevelsInterval;
  4580. this.statsIntervalId = null;
  4581. this.statsIntervalMilis = statsInterval;
  4582. // Map of ssrcs to PeerStats
  4583. this.ssrc2stats = {};
  4584. }
  4585. module.exports = StatsCollector;
  4586. /**
  4587. * Stops stats updates.
  4588. */
  4589. StatsCollector.prototype.stop = function () {
  4590. if (this.audioLevelsIntervalId) {
  4591. clearInterval(this.audioLevelsIntervalId);
  4592. this.audioLevelsIntervalId = null;
  4593. }
  4594. if (this.statsIntervalId)
  4595. {
  4596. clearInterval(this.statsIntervalId);
  4597. this.statsIntervalId = null;
  4598. }
  4599. if(this.logStatsIntervalId)
  4600. {
  4601. clearInterval(this.logStatsIntervalId);
  4602. this.logStatsIntervalId = null;
  4603. }
  4604. if(this.gatherStatsIntervalId)
  4605. {
  4606. clearInterval(this.gatherStatsIntervalId);
  4607. this.gatherStatsIntervalId = null;
  4608. }
  4609. };
  4610. /**
  4611. * Callback passed to <tt>getStats</tt> method.
  4612. * @param error an error that occurred on <tt>getStats</tt> call.
  4613. */
  4614. StatsCollector.prototype.errorCallback = function (error)
  4615. {
  4616. logger.error("Get stats error", error);
  4617. this.stop();
  4618. };
  4619. /**
  4620. * Starts stats updates.
  4621. */
  4622. StatsCollector.prototype.start = function ()
  4623. {
  4624. var self = this;
  4625. this.audioLevelsIntervalId = setInterval(
  4626. function () {
  4627. // Interval updates
  4628. self.peerconnection.getStats(
  4629. function (report) {
  4630. var results = null;
  4631. if (!report || !report.result ||
  4632. typeof report.result != 'function') {
  4633. results = report;
  4634. }
  4635. else {
  4636. results = report.result();
  4637. }
  4638. //logger.error("Got interval report", results);
  4639. self.currentAudioLevelsReport = results;
  4640. self.processAudioLevelReport();
  4641. self.baselineAudioLevelsReport =
  4642. self.currentAudioLevelsReport;
  4643. },
  4644. self.errorCallback
  4645. );
  4646. },
  4647. self.audioLevelsIntervalMilis
  4648. );
  4649. // if (!this.config.disableStats && browserSupported) {
  4650. // this.statsIntervalId = setInterval(
  4651. // function () {
  4652. // // Interval updates
  4653. // self.peerconnection.getStats(
  4654. // function (report) {
  4655. // var results = null;
  4656. // if (!report || !report.result ||
  4657. // typeof report.result != 'function') {
  4658. // //firefox
  4659. // results = report;
  4660. // }
  4661. // else {
  4662. // //chrome
  4663. // results = report.result();
  4664. // }
  4665. // //logger.error("Got interval report", results);
  4666. // self.currentStatsReport = results;
  4667. // try {
  4668. // self.processStatsReport();
  4669. // }
  4670. // catch (e) {
  4671. // logger.error("Unsupported key:" + e, e);
  4672. // }
  4673. //
  4674. // self.baselineStatsReport = self.currentStatsReport;
  4675. // },
  4676. // self.errorCallback
  4677. // );
  4678. // },
  4679. // self.statsIntervalMilis
  4680. // );
  4681. // }
  4682. //
  4683. // if (this.config.logStats && browserSupported) {
  4684. // this.gatherStatsIntervalId = setInterval(
  4685. // function () {
  4686. // self.peerconnection.getStats(
  4687. // function (report) {
  4688. // self.addStatsToBeLogged(report.result());
  4689. // },
  4690. // function () {
  4691. // }
  4692. // );
  4693. // },
  4694. // this.GATHER_INTERVAL
  4695. // );
  4696. //
  4697. // this.logStatsIntervalId = setInterval(
  4698. // function() { self.logStats(); },
  4699. // this.LOG_INTERVAL);
  4700. // }
  4701. };
  4702. /**
  4703. * Converts the stats to the format used for logging, and saves the data in
  4704. * this.statsToBeLogged.
  4705. * @param reports Reports as given by webkitRTCPerConnection.getStats.
  4706. */
  4707. StatsCollector.prototype.addStatsToBeLogged = function (reports) {
  4708. var self = this;
  4709. var num_records = this.statsToBeLogged.timestamps.length;
  4710. this.statsToBeLogged.timestamps.push(new Date().getTime());
  4711. reports.map(function (report) {
  4712. if (!acceptReport(report.id, report.type))
  4713. return;
  4714. var stat = self.statsToBeLogged.stats[report.id];
  4715. if (!stat) {
  4716. stat = self.statsToBeLogged.stats[report.id] = {};
  4717. }
  4718. stat.type = report.type;
  4719. report.names().map(function (name) {
  4720. if (!acceptStat(report.id, report.type, name))
  4721. return;
  4722. var values = stat[name];
  4723. if (!values) {
  4724. values = stat[name] = [];
  4725. }
  4726. while (values.length < num_records) {
  4727. values.push(null);
  4728. }
  4729. values.push(report.stat(name));
  4730. });
  4731. });
  4732. };
  4733. //FIXME:
  4734. //StatsCollector.prototype.logStats = function () {
  4735. //
  4736. // if(!APP.xmpp.sendLogs(this.statsToBeLogged))
  4737. // return;
  4738. // // Reset the stats
  4739. // this.statsToBeLogged.stats = {};
  4740. // this.statsToBeLogged.timestamps = [];
  4741. //};
  4742. /**
  4743. * Stats processing logic.
  4744. */
  4745. StatsCollector.prototype.processStatsReport = function () {
  4746. if (!this.baselineStatsReport) {
  4747. return;
  4748. }
  4749. for (var idx in this.currentStatsReport) {
  4750. var now = this.currentStatsReport[idx];
  4751. try {
  4752. if (getStatValue(now, 'receiveBandwidth') ||
  4753. getStatValue(now, 'sendBandwidth')) {
  4754. this.conferenceStats.bandwidth = {
  4755. "download": Math.round(
  4756. (getStatValue(now, 'receiveBandwidth')) / 1000),
  4757. "upload": Math.round(
  4758. (getStatValue(now, 'sendBandwidth')) / 1000)
  4759. };
  4760. }
  4761. }
  4762. catch(e){/*not supported*/}
  4763. if(now.type == 'googCandidatePair')
  4764. {
  4765. var ip, type, localIP, active;
  4766. try {
  4767. ip = getStatValue(now, 'remoteAddress');
  4768. type = getStatValue(now, "transportType");
  4769. localIP = getStatValue(now, "localAddress");
  4770. active = getStatValue(now, "activeConnection");
  4771. }
  4772. catch(e){/*not supported*/}
  4773. if(!ip || !type || !localIP || active != "true")
  4774. continue;
  4775. var addressSaved = false;
  4776. for(var i = 0; i < this.conferenceStats.transport.length; i++)
  4777. {
  4778. if(this.conferenceStats.transport[i].ip == ip &&
  4779. this.conferenceStats.transport[i].type == type &&
  4780. this.conferenceStats.transport[i].localip == localIP)
  4781. {
  4782. addressSaved = true;
  4783. }
  4784. }
  4785. if(addressSaved)
  4786. continue;
  4787. this.conferenceStats.transport.push({localip: localIP, ip: ip, type: type});
  4788. continue;
  4789. }
  4790. if(now.type == "candidatepair")
  4791. {
  4792. if(now.state == "succeeded")
  4793. continue;
  4794. var local = this.currentStatsReport[now.localCandidateId];
  4795. var remote = this.currentStatsReport[now.remoteCandidateId];
  4796. this.conferenceStats.transport.push({localip: local.ipAddress + ":" + local.portNumber,
  4797. ip: remote.ipAddress + ":" + remote.portNumber, type: local.transport});
  4798. }
  4799. if (now.type != 'ssrc' && now.type != "outboundrtp" &&
  4800. now.type != "inboundrtp") {
  4801. continue;
  4802. }
  4803. var before = this.baselineStatsReport[idx];
  4804. if (!before) {
  4805. logger.warn(getStatValue(now, 'ssrc') + ' not enough data');
  4806. continue;
  4807. }
  4808. var ssrc = getStatValue(now, 'ssrc');
  4809. if(!ssrc)
  4810. continue;
  4811. var ssrcStats = this.ssrc2stats[ssrc];
  4812. if (!ssrcStats) {
  4813. ssrcStats = new PeerStats();
  4814. this.ssrc2stats[ssrc] = ssrcStats;
  4815. }
  4816. var isDownloadStream = true;
  4817. var key = 'packetsReceived';
  4818. var packetsNow = getStatValue(now, key);
  4819. if (typeof packetsNow === 'undefined' || packetsNow === null) {
  4820. isDownloadStream = false;
  4821. key = 'packetsSent';
  4822. packetsNow = getStatValue(now, key);
  4823. if (typeof packetsNow === 'undefined' || packetsNow === null) {
  4824. console.warn("No packetsReceived nor packetsSent stat found");
  4825. continue;
  4826. }
  4827. }
  4828. if (!packetsNow || packetsNow < 0)
  4829. packetsNow = 0;
  4830. var packetsBefore = getStatValue(before, key);
  4831. if (!packetsBefore || packetsBefore < 0)
  4832. packetsBefore = 0;
  4833. var packetRate = packetsNow - packetsBefore;
  4834. if (!packetRate || packetRate < 0)
  4835. packetRate = 0;
  4836. var currentLoss = getStatValue(now, 'packetsLost');
  4837. if (!currentLoss || currentLoss < 0)
  4838. currentLoss = 0;
  4839. var previousLoss = getStatValue(before, 'packetsLost');
  4840. if (!previousLoss || previousLoss < 0)
  4841. previousLoss = 0;
  4842. var lossRate = currentLoss - previousLoss;
  4843. if (!lossRate || lossRate < 0)
  4844. lossRate = 0;
  4845. var packetsTotal = (packetRate + lossRate);
  4846. ssrcStats.setSsrcLoss(ssrc,
  4847. {"packetsTotal": packetsTotal,
  4848. "packetsLost": lossRate,
  4849. "isDownloadStream": isDownloadStream});
  4850. var bytesReceived = 0, bytesSent = 0;
  4851. if(getStatValue(now, "bytesReceived")) {
  4852. bytesReceived = getStatValue(now, "bytesReceived") -
  4853. getStatValue(before, "bytesReceived");
  4854. }
  4855. if (getStatValue(now, "bytesSent")) {
  4856. bytesSent = getStatValue(now, "bytesSent") -
  4857. getStatValue(before, "bytesSent");
  4858. }
  4859. var time = Math.round((now.timestamp - before.timestamp) / 1000);
  4860. if (bytesReceived <= 0 || time <= 0) {
  4861. bytesReceived = 0;
  4862. } else {
  4863. bytesReceived = Math.round(((bytesReceived * 8) / time) / 1000);
  4864. }
  4865. if (bytesSent <= 0 || time <= 0) {
  4866. bytesSent = 0;
  4867. } else {
  4868. bytesSent = Math.round(((bytesSent * 8) / time) / 1000);
  4869. }
  4870. ssrcStats.setSsrcBitrate(ssrc, {
  4871. "download": bytesReceived,
  4872. "upload": bytesSent});
  4873. var resolution = {height: null, width: null};
  4874. try {
  4875. if (getStatValue(now, "googFrameHeightReceived") &&
  4876. getStatValue(now, "googFrameWidthReceived")) {
  4877. resolution.height =
  4878. getStatValue(now, "googFrameHeightReceived");
  4879. resolution.width = getStatValue(now, "googFrameWidthReceived");
  4880. }
  4881. else if (getStatValue(now, "googFrameHeightSent") &&
  4882. getStatValue(now, "googFrameWidthSent")) {
  4883. resolution.height = getStatValue(now, "googFrameHeightSent");
  4884. resolution.width = getStatValue(now, "googFrameWidthSent");
  4885. }
  4886. }
  4887. catch(e){/*not supported*/}
  4888. if (resolution.height && resolution.width) {
  4889. ssrcStats.setSsrcResolution(ssrc, resolution);
  4890. } else {
  4891. ssrcStats.setSsrcResolution(ssrc, null);
  4892. }
  4893. }
  4894. var self = this;
  4895. // Jid stats
  4896. var totalPackets = {download: 0, upload: 0};
  4897. var lostPackets = {download: 0, upload: 0};
  4898. var bitrateDownload = 0;
  4899. var bitrateUpload = 0;
  4900. var resolutions = {};
  4901. Object.keys(this.ssrc2stats).forEach(
  4902. function (jid) {
  4903. Object.keys(self.ssrc2stats[jid].ssrc2Loss).forEach(
  4904. function (ssrc) {
  4905. var type = "upload";
  4906. if(self.ssrc2stats[jid].ssrc2Loss[ssrc].isDownloadStream)
  4907. type = "download";
  4908. totalPackets[type] +=
  4909. self.ssrc2stats[jid].ssrc2Loss[ssrc].packetsTotal;
  4910. lostPackets[type] +=
  4911. self.ssrc2stats[jid].ssrc2Loss[ssrc].packetsLost;
  4912. }
  4913. );
  4914. Object.keys(self.ssrc2stats[jid].ssrc2bitrate).forEach(
  4915. function (ssrc) {
  4916. bitrateDownload +=
  4917. self.ssrc2stats[jid].ssrc2bitrate[ssrc].download;
  4918. bitrateUpload +=
  4919. self.ssrc2stats[jid].ssrc2bitrate[ssrc].upload;
  4920. delete self.ssrc2stats[jid].ssrc2bitrate[ssrc];
  4921. }
  4922. );
  4923. resolutions[jid] = self.ssrc2stats[jid].ssrc2resolution;
  4924. }
  4925. );
  4926. this.conferenceStats.bitrate = {"upload": bitrateUpload, "download": bitrateDownload};
  4927. this.conferenceStats.packetLoss = {
  4928. total:
  4929. calculatePacketLoss(lostPackets.download + lostPackets.upload,
  4930. totalPackets.download + totalPackets.upload),
  4931. download:
  4932. calculatePacketLoss(lostPackets.download, totalPackets.download),
  4933. upload:
  4934. calculatePacketLoss(lostPackets.upload, totalPackets.upload)
  4935. };
  4936. this.eventEmitter.emit(StatisticsEvents.CONNECTION_STATS,
  4937. {
  4938. "bitrate": this.conferenceStats.bitrate,
  4939. "packetLoss": this.conferenceStats.packetLoss,
  4940. "bandwidth": this.conferenceStats.bandwidth,
  4941. "resolution": resolutions,
  4942. "transport": this.conferenceStats.transport
  4943. });
  4944. this.conferenceStats.transport = [];
  4945. };
  4946. /**
  4947. * Stats processing logic.
  4948. */
  4949. StatsCollector.prototype.processAudioLevelReport = function () {
  4950. if (!this.baselineAudioLevelsReport) {
  4951. return;
  4952. }
  4953. for (var idx in this.currentAudioLevelsReport) {
  4954. var now = this.currentAudioLevelsReport[idx];
  4955. //if we don't have "packetsReceived" this is local stream
  4956. if (now.type != 'ssrc' || !getStatValue(now, 'packetsReceived')) {
  4957. continue;
  4958. }
  4959. var before = this.baselineAudioLevelsReport[idx];
  4960. if (!before) {
  4961. logger.warn(getStatValue(now, 'ssrc') + ' not enough data');
  4962. continue;
  4963. }
  4964. var ssrc = getStatValue(now, 'ssrc');
  4965. if (!ssrc) {
  4966. if((Date.now() - now.timestamp) < 3000)
  4967. logger.warn("No ssrc: ");
  4968. continue;
  4969. }
  4970. var ssrcStats = this.ssrc2stats[ssrc];
  4971. if (!ssrcStats) {
  4972. ssrcStats = new PeerStats();
  4973. this.ssrc2stats[ssrc] = ssrcStats;
  4974. }
  4975. // Audio level
  4976. var audioLevel = null;
  4977. try {
  4978. audioLevel = getStatValue(now, 'audioInputLevel');
  4979. if (!audioLevel)
  4980. audioLevel = getStatValue(now, 'audioOutputLevel');
  4981. }
  4982. catch(e) {/*not supported*/
  4983. logger.warn("Audio Levels are not available in the statistics.");
  4984. clearInterval(this.audioLevelsIntervalId);
  4985. return;
  4986. }
  4987. if (audioLevel) {
  4988. // TODO: can't find specs about what this value really is,
  4989. // but it seems to vary between 0 and around 32k.
  4990. audioLevel = audioLevel / 32767;
  4991. ssrcStats.setSsrcAudioLevel(ssrc, audioLevel);
  4992. this.eventEmitter.emit(
  4993. StatisticsEvents.AUDIO_LEVEL, ssrc, audioLevel);
  4994. }
  4995. }
  4996. };
  4997. }).call(this,"/modules/statistics/RTPStatsCollector.js")
  4998. },{"../../service/statistics/Events":83,"../RTC/RTCBrowserType":17,"jitsi-meet-logger":47}],24:[function(require,module,exports){
  4999. /* global require, APP */
  5000. var LocalStats = require("./LocalStatsCollector.js");
  5001. var RTPStats = require("./RTPStatsCollector.js");
  5002. var EventEmitter = require("events");
  5003. var StatisticsEvents = require("../../service/statistics/Events");
  5004. //var StreamEventTypes = require("../../service/RTC/StreamEventTypes.js");
  5005. //var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  5006. //var CallStats = require("./CallStats");
  5007. //var RTCEvents = require("../../service/RTC/RTCEvents");
  5008. //
  5009. //function onDisposeConference(onUnload) {
  5010. // CallStats.sendTerminateEvent();
  5011. // stopRemote();
  5012. // if(onUnload) {
  5013. // stopLocal();
  5014. // eventEmitter.removeAllListeners();
  5015. // }
  5016. //}
  5017. var eventEmitter = new EventEmitter();
  5018. function Statistics() {
  5019. this.rtpStats = null;
  5020. this.eventEmitter = new EventEmitter();
  5021. }
  5022. Statistics.prototype.startRemoteStats = function (peerconnection) {
  5023. if (this.rtpStats) {
  5024. this.rtpStats.stop();
  5025. }
  5026. this.rtpStats = new RTPStats(peerconnection, 200, 2000, this.eventEmitter);
  5027. this.rtpStats.start();
  5028. }
  5029. Statistics.localStats = [];
  5030. Statistics.startLocalStats = function (stream, callback) {
  5031. var localStats = new LocalStats(stream, 200, callback);
  5032. this.localStats.push(localStats);
  5033. localStats.start();
  5034. }
  5035. Statistics.prototype.addAudioLevelListener = function(listener)
  5036. {
  5037. this.eventEmitter.on(StatisticsEvents.AUDIO_LEVEL, listener);
  5038. }
  5039. Statistics.prototype.removeAudioLevelListener = function(listener)
  5040. {
  5041. this.eventEmitter.removeListener(StatisticsEvents.AUDIO_LEVEL, listener);
  5042. }
  5043. Statistics.prototype.dispose = function () {
  5044. Statistics.stopAllLocalStats();
  5045. this.stopRemote();
  5046. if(this.eventEmitter)
  5047. this.eventEmitter.removeAllListeners();
  5048. if(eventEmitter)
  5049. eventEmitter.removeAllListeners();
  5050. }
  5051. Statistics.stopAllLocalStats = function () {
  5052. for(var i = 0; i < this.localStats.length; i++)
  5053. this.localStats[i].stop();
  5054. this.localStats = [];
  5055. }
  5056. Statistics.stopLocalStats = function (stream) {
  5057. for(var i = 0; i < Statistics.localStats.length; i++)
  5058. if(Statistics.localStats[i].stream === stream){
  5059. var localStats = Statistics.localStats.splice(i, 1);
  5060. localStats.stop();
  5061. break;
  5062. }
  5063. }
  5064. Statistics.prototype.stopRemote = function () {
  5065. if (this.rtpStats) {
  5066. this.rtpStats.stop();
  5067. this.eventEmitter.emit(StatisticsEvents.STOP);
  5068. this.rtpStats = null;
  5069. }
  5070. };
  5071. /**
  5072. * Obtains audio level reported in the stats for specified peer.
  5073. * @param peerJid full MUC jid of the user for whom we want to obtain last
  5074. * audio level.
  5075. * @param ssrc the SSRC of audio stream for which we want to obtain audio
  5076. * level.
  5077. * @returns {*} a float form 0 to 1 that represents current audio level or
  5078. * <tt>null</tt> if for any reason the value is not available
  5079. * at this time.
  5080. */
  5081. Statistics.prototype.getPeerSSRCAudioLevel = function (peerJid, ssrc) {
  5082. var peerStats = this.rtpStats.jid2stats[peerJid];
  5083. return peerStats ? peerStats.ssrc2AudioLevel[ssrc] : null;
  5084. };
  5085. Statistics.LOCAL_JID = require("../../service/statistics/constants").LOCAL_JID;
  5086. //
  5087. //var statistics = {
  5088. // /**
  5089. // * Indicates that this audio level is for local jid.
  5090. // * @type {string}
  5091. // */
  5092. // LOCAL_JID: 'local',
  5093. //
  5094. // addConnectionStatsListener: function(listener)
  5095. // {
  5096. // eventEmitter.on("statistics.connectionstats", listener);
  5097. // },
  5098. //
  5099. // removeConnectionStatsListener: function(listener)
  5100. // {
  5101. // eventEmitter.removeListener("statistics.connectionstats", listener);
  5102. // },
  5103. //
  5104. //
  5105. // addRemoteStatsStopListener: function(listener)
  5106. // {
  5107. // eventEmitter.on("statistics.stop", listener);
  5108. // },
  5109. //
  5110. // removeRemoteStatsStopListener: function(listener)
  5111. // {
  5112. // eventEmitter.removeListener("statistics.stop", listener);
  5113. // },
  5114. //
  5115. //
  5116. // stopRemoteStatistics: function()
  5117. // {
  5118. // stopRemote();
  5119. // },
  5120. //
  5121. //// Already implemented with the constructor
  5122. // start: function () {
  5123. // APP.RTC.addStreamListener(onStreamCreated,
  5124. // StreamEventTypes.EVENT_TYPE_LOCAL_CREATED);
  5125. // APP.xmpp.addListener(XMPPEvents.DISPOSE_CONFERENCE, onDisposeConference);
  5126. // //FIXME: we may want to change CALL INCOMING event to onnegotiationneeded
  5127. // APP.xmpp.addListener(XMPPEvents.CALL_INCOMING, function (event) {
  5128. // startRemoteStats(event.peerconnection);
  5129. //// CallStats.init(event);
  5130. // });
  5131. //// APP.xmpp.addListener(XMPPEvents.PEERCONNECTION_READY, function (session) {
  5132. //// CallStats.init(session);
  5133. //// });
  5134. // //FIXME: that event is changed to TRACK_MUTE_CHANGED
  5135. //// APP.RTC.addListener(RTCEvents.AUDIO_MUTE, function (mute) {
  5136. //// CallStats.sendMuteEvent(mute, "audio");
  5137. //// });
  5138. //// APP.xmpp.addListener(XMPPEvents.CONFERENCE_SETUP_FAILED, function () {
  5139. //// CallStats.sendSetupFailedEvent();
  5140. //// });
  5141. // //FIXME: that event is changed to TRACK_MUTE_CHANGED
  5142. //// APP.RTC.addListener(RTCEvents.VIDEO_MUTE, function (mute) {
  5143. //// CallStats.sendMuteEvent(mute, "video");
  5144. //// });
  5145. // }
  5146. //};
  5147. module.exports = Statistics;
  5148. },{"../../service/statistics/Events":83,"../../service/statistics/constants":84,"./LocalStatsCollector.js":22,"./RTPStatsCollector.js":23,"events":43}],25:[function(require,module,exports){
  5149. /**
  5150. /**
  5151. * @const
  5152. */
  5153. var ALPHANUM = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
  5154. /**
  5155. * Hexadecimal digits.
  5156. * @const
  5157. */
  5158. var HEX_DIGITS = '0123456789abcdef';
  5159. /**
  5160. * Generates random int within the range [min, max]
  5161. * @param min the minimum value for the generated number
  5162. * @param max the maximum value for the generated number
  5163. * @returns random int number
  5164. */
  5165. function randomInt(min, max) {
  5166. return Math.floor(Math.random() * (max - min + 1)) + min;
  5167. }
  5168. /**
  5169. * Get random element from array or string.
  5170. * @param {Array|string} arr source
  5171. * @returns array element or string character
  5172. */
  5173. function randomElement(arr) {
  5174. return arr[randomInt(0, arr.length - 1)];
  5175. }
  5176. /**
  5177. * Generate random alphanumeric string.
  5178. * @param {number} length expected string length
  5179. * @returns {string} random string of specified length
  5180. */
  5181. function randomAlphanumStr(length) {
  5182. var result = '';
  5183. for (var i = 0; i < length; i += 1) {
  5184. result += randomElement(ALPHANUM);
  5185. }
  5186. return result;
  5187. }
  5188. /**
  5189. * Exported interface.
  5190. */
  5191. var RandomUtil = {
  5192. /**
  5193. * Returns a random hex digit.
  5194. * @returns {*}
  5195. */
  5196. randomHexDigit: function() {
  5197. return randomElement(HEX_DIGITS);
  5198. },
  5199. /**
  5200. * Returns a random string of hex digits with length 'len'.
  5201. * @param len the length.
  5202. */
  5203. randomHexString: function (len) {
  5204. var ret = '';
  5205. while (len--) {
  5206. ret += this.randomHexDigit();
  5207. }
  5208. return ret;
  5209. },
  5210. randomElement: randomElement,
  5211. randomAlphanumStr: randomAlphanumStr
  5212. };
  5213. module.exports = RandomUtil;
  5214. },{}],26:[function(require,module,exports){
  5215. (function (__filename){
  5216. /* global Strophe, $, $pres, $iq, $msg */
  5217. /* jshint -W101,-W069 */
  5218. var logger = require("jitsi-meet-logger").getLogger(__filename);
  5219. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  5220. var Moderator = require("./moderator");
  5221. var EventEmitter = require("events");
  5222. var parser = {
  5223. packet2JSON: function (packet, nodes) {
  5224. var self = this;
  5225. $(packet).children().each(function (index) {
  5226. var tagName = $(this).prop("tagName");
  5227. var node = {
  5228. tagName: tagName
  5229. };
  5230. node.attributes = {};
  5231. $($(this)[0].attributes).each(function( index, attr ) {
  5232. node.attributes[ attr.name ] = attr.value;
  5233. });
  5234. var text = Strophe.getText($(this)[0]);
  5235. if (text) {
  5236. node.value = text;
  5237. }
  5238. node.children = [];
  5239. nodes.push(node);
  5240. self.packet2JSON($(this), node.children);
  5241. });
  5242. },
  5243. JSON2packet: function (nodes, packet) {
  5244. for(var i = 0; i < nodes.length; i++) {
  5245. var node = nodes[i];
  5246. if(!node || node === null){
  5247. continue;
  5248. }
  5249. packet.c(node.tagName, node.attributes);
  5250. if(node.value)
  5251. packet.t(node.value);
  5252. if(node.children)
  5253. this.JSON2packet(node.children, packet);
  5254. packet.up();
  5255. }
  5256. // packet.up();
  5257. }
  5258. };
  5259. /**
  5260. * Returns array of JS objects from the presence JSON associated with the passed nodeName
  5261. * @param pres the presence JSON
  5262. * @param nodeName the name of the node (videomuted, audiomuted, etc)
  5263. */
  5264. function filterNodeFromPresenceJSON(pres, nodeName){
  5265. var res = [];
  5266. for(var i = 0; i < pres.length; i++)
  5267. if(pres[i].tagName === nodeName)
  5268. res.push(pres[i]);
  5269. return res;
  5270. }
  5271. function ChatRoom(connection, jid, password, XMPP, options) {
  5272. this.eventEmitter = new EventEmitter();
  5273. this.xmpp = XMPP;
  5274. this.connection = connection;
  5275. this.roomjid = Strophe.getBareJidFromJid(jid);
  5276. this.myroomjid = jid;
  5277. this.password = password;
  5278. logger.info("Joined MUC as " + this.myroomjid);
  5279. this.members = {};
  5280. this.presMap = {};
  5281. this.presHandlers = {};
  5282. this.joined = false;
  5283. this.role = 'none';
  5284. this.focusMucJid = null;
  5285. this.bridgeIsDown = false;
  5286. this.options = options || {};
  5287. this.moderator = new Moderator(this.roomjid, this.xmpp, this.eventEmitter);
  5288. this.initPresenceMap();
  5289. this.session = null;
  5290. var self = this;
  5291. this.lastPresences = {};
  5292. }
  5293. ChatRoom.prototype.initPresenceMap = function () {
  5294. this.presMap['to'] = this.myroomjid;
  5295. this.presMap['xns'] = 'http://jabber.org/protocol/muc';
  5296. this.presMap["nodes"] = [];
  5297. this.presMap["nodes"].push( {
  5298. "tagName": "user-agent",
  5299. "value": navigator.userAgent,
  5300. "attributes": {xmlns: 'http://jitsi.org/jitmeet/user-agent'}
  5301. });
  5302. };
  5303. ChatRoom.prototype.updateDeviceAvailability = function (devices) {
  5304. this.presMap["nodes"].push( {
  5305. "tagName": "devices",
  5306. "children": [
  5307. {
  5308. "tagName": "audio",
  5309. "value": devices.audio,
  5310. },
  5311. {
  5312. "tagName": "video",
  5313. "value": devices.video,
  5314. }
  5315. ]
  5316. });
  5317. };
  5318. ChatRoom.prototype.join = function (password, tokenPassword) {
  5319. if(password)
  5320. this.password = password;
  5321. var self = this;
  5322. this.moderator.allocateConferenceFocus(function()
  5323. {
  5324. self.sendPresence(tokenPassword);
  5325. }.bind(this));
  5326. };
  5327. ChatRoom.prototype.sendPresence = function (tokenPassword) {
  5328. if (!this.presMap['to']) {
  5329. // Too early to send presence - not initialized
  5330. return;
  5331. }
  5332. var pres = $pres({to: this.presMap['to'] });
  5333. pres.c('x', {xmlns: this.presMap['xns']});
  5334. if (this.password) {
  5335. pres.c('password').t(this.password).up();
  5336. }
  5337. pres.up();
  5338. // Send XEP-0115 'c' stanza that contains our capabilities info
  5339. if (this.connection.caps) {
  5340. this.connection.caps.node = this.xmpp.options.clientNode;
  5341. pres.c('c', this.connection.caps.generateCapsAttrs()).up();
  5342. }
  5343. if (tokenPassword) {
  5344. pres.c('token', { xmlns: 'http://jitsi.org/jitmeet/auth-token'})
  5345. .t(tokenPassword).up();
  5346. }
  5347. parser.JSON2packet(this.presMap.nodes, pres);
  5348. this.connection.send(pres);
  5349. };
  5350. ChatRoom.prototype.doLeave = function () {
  5351. logger.log("do leave", this.myroomjid);
  5352. var pres = $pres({to: this.myroomjid, type: 'unavailable' });
  5353. this.presMap.length = 0;
  5354. this.connection.send(pres);
  5355. };
  5356. ChatRoom.prototype.createNonAnonymousRoom = function () {
  5357. // http://xmpp.org/extensions/xep-0045.html#createroom-reserved
  5358. var getForm = $iq({type: 'get', to: this.roomjid})
  5359. .c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'})
  5360. .c('x', {xmlns: 'jabber:x:data', type: 'submit'});
  5361. var self = this;
  5362. this.connection.sendIQ(getForm, function (form) {
  5363. if (!$(form).find(
  5364. '>query>x[xmlns="jabber:x:data"]' +
  5365. '>field[var="muc#roomconfig_whois"]').length) {
  5366. logger.error('non-anonymous rooms not supported');
  5367. return;
  5368. }
  5369. var formSubmit = $iq({to: this.roomjid, type: 'set'})
  5370. .c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'});
  5371. formSubmit.c('x', {xmlns: 'jabber:x:data', type: 'submit'});
  5372. formSubmit.c('field', {'var': 'FORM_TYPE'})
  5373. .c('value')
  5374. .t('http://jabber.org/protocol/muc#roomconfig').up().up();
  5375. formSubmit.c('field', {'var': 'muc#roomconfig_whois'})
  5376. .c('value').t('anyone').up().up();
  5377. self.connection.sendIQ(formSubmit);
  5378. }, function (error) {
  5379. logger.error("Error getting room configuration form");
  5380. });
  5381. };
  5382. ChatRoom.prototype.onPresence = function (pres) {
  5383. var from = pres.getAttribute('from');
  5384. // Parse roles.
  5385. var member = {};
  5386. member.show = $(pres).find('>show').text();
  5387. member.status = $(pres).find('>status').text();
  5388. var tmp = $(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>item');
  5389. member.affiliation = tmp.attr('affiliation');
  5390. member.role = tmp.attr('role');
  5391. // Focus recognition
  5392. member.jid = tmp.attr('jid');
  5393. member.isFocus = false;
  5394. if (member.jid
  5395. && member.jid.indexOf(this.moderator.getFocusUserJid() + "/") === 0) {
  5396. member.isFocus = true;
  5397. }
  5398. $(pres).find(">x").remove();
  5399. var nodes = [];
  5400. parser.packet2JSON(pres, nodes);
  5401. this.lastPresences[from] = nodes;
  5402. for(var i = 0; i < nodes.length; i++)
  5403. {
  5404. var node = nodes[i];
  5405. switch(node.tagName)
  5406. {
  5407. case "nick":
  5408. member.nick = node.value;
  5409. if(!member.isFocus) {
  5410. var displayName = !this.xmpp.options.displayJids
  5411. ? member.nick : Strophe.getResourceFromJid(from);
  5412. if (displayName && displayName.length > 0) {
  5413. this.eventEmitter.emit(XMPPEvents.DISPLAY_NAME_CHANGED, from, displayName);
  5414. }
  5415. logger.info("Display name: " + displayName, pres);
  5416. }
  5417. break;
  5418. case "userId":
  5419. member.id = node.value;
  5420. break;
  5421. case "email":
  5422. member.email = node.value;
  5423. break;
  5424. case "bridgeIsDown":
  5425. if(!this.bridgeIsDown) {
  5426. this.bridgeIsDown = true;
  5427. this.eventEmitter.emit(XMPPEvents.BRIDGE_DOWN);
  5428. }
  5429. break;
  5430. default :
  5431. this.processNode(node, from);
  5432. }
  5433. }
  5434. if (from == this.myroomjid) {
  5435. if (member.affiliation == 'owner')
  5436. if (this.role !== member.role) {
  5437. this.role = member.role;
  5438. this.eventEmitter.emit(XMPPEvents.LOCAL_ROLE_CHANGED, this.role);
  5439. }
  5440. if (!this.joined) {
  5441. this.joined = true;
  5442. console.log("(TIME) MUC joined:\t", window.performance.now());
  5443. this.eventEmitter.emit(XMPPEvents.MUC_JOINED, from, member);
  5444. }
  5445. } else if (this.members[from] === undefined) {
  5446. // new participant
  5447. this.members[from] = member;
  5448. logger.log('entered', from, member);
  5449. if (member.isFocus) {
  5450. this.focusMucJid = from;
  5451. logger.info("Ignore focus: " + from + ", real JID: " + member.jid);
  5452. }
  5453. else {
  5454. this.eventEmitter.emit(XMPPEvents.MUC_MEMBER_JOINED, from, member.id || member.email, member.nick);
  5455. }
  5456. } else {
  5457. // Presence update for existing participant
  5458. // Watch role change:
  5459. if (this.members[from].role != member.role) {
  5460. this.members[from].role = member.role;
  5461. this.eventEmitter.emit(XMPPEvents.MUC_ROLE_CHANGED, from, member.role);
  5462. }
  5463. // store the new display name
  5464. if(member.displayName)
  5465. this.members[from].displayName = member.displayName;
  5466. }
  5467. if(!member.isFocus)
  5468. this.eventEmitter.emit(XMPPEvents.USER_ID_CHANGED, from, member.id || member.email);
  5469. // Trigger status message update
  5470. if (member.status) {
  5471. this.eventEmitter.emit(XMPPEvents.PRESENCE_STATUS, from, member);
  5472. }
  5473. };
  5474. ChatRoom.prototype.processNode = function (node, from) {
  5475. if(this.presHandlers[node.tagName])
  5476. this.presHandlers[node.tagName](node, from);
  5477. };
  5478. ChatRoom.prototype.sendMessage = function (body, nickname) {
  5479. var msg = $msg({to: this.roomjid, type: 'groupchat'});
  5480. msg.c('body', body).up();
  5481. if (nickname) {
  5482. msg.c('nick', {xmlns: 'http://jabber.org/protocol/nick'}).t(nickname).up().up();
  5483. }
  5484. this.connection.send(msg);
  5485. this.eventEmitter.emit(XMPPEvents.SENDING_CHAT_MESSAGE, body);
  5486. };
  5487. ChatRoom.prototype.setSubject = function (subject) {
  5488. var msg = $msg({to: this.roomjid, type: 'groupchat'});
  5489. msg.c('subject', subject);
  5490. this.connection.send(msg);
  5491. logger.log("topic changed to " + subject);
  5492. };
  5493. ChatRoom.prototype.onParticipantLeft = function (jid) {
  5494. delete this.lastPresences[jid];
  5495. this.eventEmitter.emit(XMPPEvents.MUC_MEMBER_LEFT, jid);
  5496. this.moderator.onMucMemberLeft(jid);
  5497. };
  5498. ChatRoom.prototype.onPresenceUnavailable = function (pres, from) {
  5499. // room destroyed ?
  5500. if ($(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]' +
  5501. '>destroy').length) {
  5502. var reason;
  5503. var reasonSelect = $(pres).find(
  5504. '>x[xmlns="http://jabber.org/protocol/muc#user"]' +
  5505. '>destroy>reason');
  5506. if (reasonSelect.length) {
  5507. reason = reasonSelect.text();
  5508. }
  5509. this.xmpp.disposeConference(false);
  5510. this.eventEmitter.emit(XMPPEvents.MUC_DESTROYED, reason);
  5511. delete this.connection.emuc.rooms[Strophe.getBareJidFromJid(from)];
  5512. return true;
  5513. }
  5514. // Status code 110 indicates that this notification is "self-presence".
  5515. if (!$(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>status[code="110"]').length) {
  5516. delete this.members[from];
  5517. this.onParticipantLeft(from);
  5518. }
  5519. // If the status code is 110 this means we're leaving and we would like
  5520. // to remove everyone else from our view, so we trigger the event.
  5521. else if (Object.keys(this.members).length > 1) {
  5522. for (var i in this.members) {
  5523. var member = this.members[i];
  5524. delete this.members[i];
  5525. this.onParticipantLeft(member);
  5526. }
  5527. }
  5528. if ($(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>status[code="307"]').length) {
  5529. if (this.myroomjid === from) {
  5530. this.xmpp.disposeConference(false);
  5531. this.eventEmitter.emit(XMPPEvents.KICKED);
  5532. }
  5533. }
  5534. };
  5535. ChatRoom.prototype.onMessage = function (msg, from) {
  5536. var nick =
  5537. $(msg).find('>nick[xmlns="http://jabber.org/protocol/nick"]')
  5538. .text() ||
  5539. Strophe.getResourceFromJid(from);
  5540. var txt = $(msg).find('>body').text();
  5541. var type = msg.getAttribute("type");
  5542. if (type == "error") {
  5543. this.eventEmitter.emit(XMPPEvents.CHAT_ERROR_RECEIVED,
  5544. $(msg).find('>text').text(), txt);
  5545. return true;
  5546. }
  5547. var subject = $(msg).find('>subject');
  5548. if (subject.length) {
  5549. var subjectText = subject.text();
  5550. if (subjectText || subjectText === "") {
  5551. this.eventEmitter.emit(XMPPEvents.SUBJECT_CHANGED, subjectText);
  5552. logger.log("Subject is changed to " + subjectText);
  5553. }
  5554. }
  5555. // xep-0203 delay
  5556. var stamp = $(msg).find('>delay').attr('stamp');
  5557. if (!stamp) {
  5558. // or xep-0091 delay, UTC timestamp
  5559. stamp = $(msg).find('>[xmlns="jabber:x:delay"]').attr('stamp');
  5560. if (stamp) {
  5561. // the format is CCYYMMDDThh:mm:ss
  5562. var dateParts = stamp.match(/(\d{4})(\d{2})(\d{2}T\d{2}:\d{2}:\d{2})/);
  5563. stamp = dateParts[1] + "-" + dateParts[2] + "-" + dateParts[3] + "Z";
  5564. }
  5565. }
  5566. if (txt) {
  5567. logger.log('chat', nick, txt);
  5568. this.eventEmitter.emit(XMPPEvents.MESSAGE_RECEIVED,
  5569. from, nick, txt, this.myroomjid, stamp);
  5570. }
  5571. };
  5572. ChatRoom.prototype.onPresenceError = function (pres, from) {
  5573. if ($(pres).find('>error[type="auth"]>not-authorized[xmlns="urn:ietf:params:xml:ns:xmpp-stanzas"]').length) {
  5574. logger.log('on password required', from);
  5575. this.eventEmitter.emit(XMPPEvents.PASSWORD_REQUIRED);
  5576. } else if ($(pres).find(
  5577. '>error[type="cancel"]>not-allowed[xmlns="urn:ietf:params:xml:ns:xmpp-stanzas"]').length) {
  5578. var toDomain = Strophe.getDomainFromJid(pres.getAttribute('to'));
  5579. if (toDomain === this.xmpp.options.hosts.anonymousdomain) {
  5580. // enter the room by replying with 'not-authorized'. This would
  5581. // result in reconnection from authorized domain.
  5582. // We're either missing Jicofo/Prosody config for anonymous
  5583. // domains or something is wrong.
  5584. this.eventEmitter.emit(XMPPEvents.ROOM_JOIN_ERROR, pres);
  5585. } else {
  5586. logger.warn('onPresError ', pres);
  5587. this.eventEmitter.emit(XMPPEvents.ROOM_CONNECT_ERROR, pres);
  5588. }
  5589. } else {
  5590. logger.warn('onPresError ', pres);
  5591. this.eventEmitter.emit(XMPPEvents.ROOM_CONNECT_ERROR, pres);
  5592. }
  5593. };
  5594. ChatRoom.prototype.kick = function (jid) {
  5595. var kickIQ = $iq({to: this.roomjid, type: 'set'})
  5596. .c('query', {xmlns: 'http://jabber.org/protocol/muc#admin'})
  5597. .c('item', {nick: Strophe.getResourceFromJid(jid), role: 'none'})
  5598. .c('reason').t('You have been kicked.').up().up().up();
  5599. this.connection.sendIQ(
  5600. kickIQ,
  5601. function (result) {
  5602. logger.log('Kick participant with jid: ', jid, result);
  5603. },
  5604. function (error) {
  5605. logger.log('Kick participant error: ', error);
  5606. });
  5607. };
  5608. ChatRoom.prototype.lockRoom = function (key, onSuccess, onError, onNotSupported) {
  5609. //http://xmpp.org/extensions/xep-0045.html#roomconfig
  5610. var ob = this;
  5611. this.connection.sendIQ($iq({to: this.roomjid, type: 'get'}).c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'}),
  5612. function (res) {
  5613. if ($(res).find('>query>x[xmlns="jabber:x:data"]>field[var="muc#roomconfig_roomsecret"]').length) {
  5614. var formsubmit = $iq({to: ob.roomjid, type: 'set'}).c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'});
  5615. formsubmit.c('x', {xmlns: 'jabber:x:data', type: 'submit'});
  5616. formsubmit.c('field', {'var': 'FORM_TYPE'}).c('value').t('http://jabber.org/protocol/muc#roomconfig').up().up();
  5617. formsubmit.c('field', {'var': 'muc#roomconfig_roomsecret'}).c('value').t(key).up().up();
  5618. // Fixes a bug in prosody 0.9.+ https://code.google.com/p/lxmppd/issues/detail?id=373
  5619. formsubmit.c('field', {'var': 'muc#roomconfig_whois'}).c('value').t('anyone').up().up();
  5620. // FIXME: is muc#roomconfig_passwordprotectedroom required?
  5621. ob.connection.sendIQ(formsubmit,
  5622. onSuccess,
  5623. onError);
  5624. } else {
  5625. onNotSupported();
  5626. }
  5627. }, onError);
  5628. };
  5629. ChatRoom.prototype.addToPresence = function (key, values) {
  5630. values.tagName = key;
  5631. this.presMap["nodes"].push(values);
  5632. };
  5633. ChatRoom.prototype.removeFromPresence = function (key) {
  5634. for(var i = 0; i < this.presMap.nodes.length; i++)
  5635. {
  5636. if(key === this.presMap.nodes[i].tagName)
  5637. this.presMap.nodes.splice(i, 1);
  5638. }
  5639. };
  5640. ChatRoom.prototype.addPresenceListener = function (name, handler) {
  5641. this.presHandlers[name] = handler;
  5642. };
  5643. ChatRoom.prototype.removePresenceListener = function (name) {
  5644. delete this.presHandlers[name];
  5645. };
  5646. ChatRoom.prototype.isModerator = function () {
  5647. return this.role === 'moderator';
  5648. };
  5649. ChatRoom.prototype.getMemberRole = function (peerJid) {
  5650. if (this.members[peerJid]) {
  5651. return this.members[peerJid].role;
  5652. }
  5653. return null;
  5654. };
  5655. ChatRoom.prototype.setJingleSession = function(session){
  5656. this.session = session;
  5657. this.session.room = this;
  5658. };
  5659. ChatRoom.prototype.removeStream = function (stream, callback) {
  5660. if(!this.session)
  5661. return;
  5662. this.session.removeStream(stream, callback);
  5663. };
  5664. ChatRoom.prototype.switchStreams = function (stream, oldStream, callback, isAudio) {
  5665. if(this.session) {
  5666. // FIXME: will block switchInProgress on true value in case of exception
  5667. this.session.switchStreams(stream, oldStream, callback, isAudio);
  5668. } else {
  5669. // We are done immediately
  5670. logger.warn("No conference handler or conference not started yet");
  5671. callback();
  5672. }
  5673. };
  5674. ChatRoom.prototype.addStream = function (stream, callback) {
  5675. if(this.session) {
  5676. // FIXME: will block switchInProgress on true value in case of exception
  5677. this.session.addStream(stream, callback);
  5678. } else {
  5679. // We are done immediately
  5680. logger.warn("No conference handler or conference not started yet");
  5681. callback();
  5682. }
  5683. };
  5684. ChatRoom.prototype.setVideoMute = function (mute, callback, options) {
  5685. var self = this;
  5686. var localCallback = function (mute) {
  5687. self.sendVideoInfoPresence(mute);
  5688. if(callback)
  5689. callback(mute);
  5690. };
  5691. if(this.session)
  5692. {
  5693. this.session.setVideoMute(
  5694. mute, localCallback, options);
  5695. }
  5696. else {
  5697. localCallback(mute);
  5698. }
  5699. };
  5700. ChatRoom.prototype.setAudioMute = function (mute, callback) {
  5701. //This will be for remote streams only
  5702. // if (this.forceMuted && !mute) {
  5703. // logger.info("Asking focus for unmute");
  5704. // this.connection.moderate.setMute(this.connection.emuc.myroomjid, mute);
  5705. // // FIXME: wait for result before resetting muted status
  5706. // this.forceMuted = false;
  5707. // }
  5708. return this.sendAudioInfoPresence(mute, callback);
  5709. };
  5710. ChatRoom.prototype.addAudioInfoToPresence = function (mute) {
  5711. this.removeFromPresence("audiomuted");
  5712. this.addToPresence("audiomuted",
  5713. {attributes:
  5714. {"audions": "http://jitsi.org/jitmeet/audio"},
  5715. value: mute.toString()});
  5716. };
  5717. ChatRoom.prototype.sendAudioInfoPresence = function(mute, callback) {
  5718. this.addAudioInfoToPresence(mute);
  5719. if(this.connection) {
  5720. this.sendPresence();
  5721. }
  5722. if(callback)
  5723. callback();
  5724. };
  5725. ChatRoom.prototype.addVideoInfoToPresence = function (mute) {
  5726. this.removeFromPresence("videomuted");
  5727. this.addToPresence("videomuted",
  5728. {attributes:
  5729. {"videons": "http://jitsi.org/jitmeet/video"},
  5730. value: mute.toString()});
  5731. };
  5732. ChatRoom.prototype.sendVideoInfoPresence = function (mute) {
  5733. this.addVideoInfoToPresence(mute);
  5734. if(!this.connection)
  5735. return;
  5736. this.sendPresence();
  5737. };
  5738. ChatRoom.prototype.addListener = function(type, listener) {
  5739. this.eventEmitter.on(type, listener);
  5740. };
  5741. ChatRoom.prototype.removeListener = function (type, listener) {
  5742. this.eventEmitter.removeListener(type, listener);
  5743. };
  5744. ChatRoom.prototype.remoteStreamAdded = function(data, sid, thessrc) {
  5745. if(this.lastPresences[data.peerjid])
  5746. {
  5747. var pres = this.lastPresences[data.peerjid];
  5748. var audiomuted = filterNodeFromPresenceJSON(pres, "audiomuted");
  5749. var videomuted = filterNodeFromPresenceJSON(pres, "videomuted");
  5750. data.videomuted = ((videomuted.length > 0
  5751. && videomuted[0]
  5752. && videomuted[0]["value"] === "true")? true : false);
  5753. data.audiomuted = ((audiomuted.length > 0
  5754. && audiomuted[0]
  5755. && audiomuted[0]["value"] === "true")? true : false);
  5756. }
  5757. this.eventEmitter.emit(XMPPEvents.REMOTE_STREAM_RECEIVED, data, sid, thessrc);
  5758. };
  5759. ChatRoom.prototype.getJidBySSRC = function (ssrc) {
  5760. if (!this.session)
  5761. return null;
  5762. return this.session.getSsrcOwner(ssrc);
  5763. };
  5764. module.exports = ChatRoom;
  5765. }).call(this,"/modules/xmpp/ChatRoom.js")
  5766. },{"../../service/xmpp/XMPPEvents":85,"./moderator":34,"events":43,"jitsi-meet-logger":47}],27:[function(require,module,exports){
  5767. (function (__filename){
  5768. /*
  5769. * JingleSession provides an API to manage a single Jingle session. We will
  5770. * have different implementations depending on the underlying interface used
  5771. * (i.e. WebRTC and ORTC) and here we hold the code common to all of them.
  5772. */
  5773. var logger = require("jitsi-meet-logger").getLogger(__filename);
  5774. function JingleSession(me, sid, connection, service, eventEmitter) {
  5775. /**
  5776. * Our JID.
  5777. */
  5778. this.me = me;
  5779. /**
  5780. * The Jingle session identifier.
  5781. */
  5782. this.sid = sid;
  5783. /**
  5784. * The XMPP connection.
  5785. */
  5786. this.connection = connection;
  5787. /**
  5788. * The XMPP service.
  5789. */
  5790. this.service = service;
  5791. /**
  5792. * The event emitter.
  5793. */
  5794. this.eventEmitter = eventEmitter;
  5795. /**
  5796. * Whether to use dripping or not. Dripping is sending trickle candidates
  5797. * not one-by-one.
  5798. * Note: currently we do not support 'false'.
  5799. */
  5800. this.usedrip = true;
  5801. /**
  5802. * When dripping is used, stores ICE candidates which are to be sent.
  5803. */
  5804. this.drip_container = [];
  5805. // Media constraints. Is this WebRTC only?
  5806. this.media_constraints = null;
  5807. // ICE servers config (RTCConfiguration?).
  5808. this.ice_config = {};
  5809. // The chat room instance associated with the session.
  5810. this.room = null;
  5811. }
  5812. /**
  5813. * Prepares this object to initiate a session.
  5814. * @param peerjid the JID of the remote peer.
  5815. * @param isInitiator whether we will be the Jingle initiator.
  5816. * @param media_constraints
  5817. * @param ice_config
  5818. */
  5819. JingleSession.prototype.initialize = function(peerjid, isInitiator,
  5820. media_constraints, ice_config) {
  5821. this.media_constraints = media_constraints;
  5822. this.ice_config = ice_config;
  5823. if (this.state !== null) {
  5824. logger.error('attempt to initiate on session ' + this.sid +
  5825. 'in state ' + this.state);
  5826. return;
  5827. }
  5828. this.state = 'pending';
  5829. this.initiator = isInitiator ? this.me : peerjid;
  5830. this.responder = !isInitiator ? this.me : peerjid;
  5831. this.peerjid = peerjid;
  5832. this.doInitialize();
  5833. };
  5834. /**
  5835. * Finishes initialization.
  5836. */
  5837. JingleSession.prototype.doInitialize = function() {};
  5838. /**
  5839. * Adds the ICE candidates found in the 'contents' array as remote candidates?
  5840. * Note: currently only used on transport-info
  5841. */
  5842. JingleSession.prototype.addIceCandidates = function(contents) {};
  5843. /**
  5844. * Handles an 'add-source' event.
  5845. *
  5846. * @param contents an array of Jingle 'content' elements.
  5847. */
  5848. JingleSession.prototype.addSources = function(contents) {};
  5849. /**
  5850. * Handles a 'remove-source' event.
  5851. *
  5852. * @param contents an array of Jingle 'content' elements.
  5853. */
  5854. JingleSession.prototype.removeSources = function(contents) {};
  5855. /**
  5856. * Terminates this Jingle session (stops sending media and closes the streams?)
  5857. */
  5858. JingleSession.prototype.terminate = function() {};
  5859. /**
  5860. * Sends a Jingle session-terminate message to the peer and terminates the
  5861. * session.
  5862. * @param reason
  5863. * @param text
  5864. */
  5865. JingleSession.prototype.sendTerminate = function(reason, text) {};
  5866. /**
  5867. * Handles an offer from the remote peer (prepares to accept a session).
  5868. * @param jingle the 'jingle' XML element.
  5869. */
  5870. JingleSession.prototype.setOffer = function(jingle) {};
  5871. /**
  5872. * Handles an answer from the remote peer (prepares to accept a session).
  5873. * @param jingle the 'jingle' XML element.
  5874. */
  5875. JingleSession.prototype.setAnswer = function(jingle) {};
  5876. module.exports = JingleSession;
  5877. }).call(this,"/modules/xmpp/JingleSession.js")
  5878. },{"jitsi-meet-logger":47}],28:[function(require,module,exports){
  5879. (function (__filename){
  5880. /* jshint -W117 */
  5881. var logger = require("jitsi-meet-logger").getLogger(__filename);
  5882. var JingleSession = require("./JingleSession");
  5883. var TraceablePeerConnection = require("./TraceablePeerConnection");
  5884. var SDPDiffer = require("./SDPDiffer");
  5885. var SDPUtil = require("./SDPUtil");
  5886. var SDP = require("./SDP");
  5887. var async = require("async");
  5888. var transform = require("sdp-transform");
  5889. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  5890. var RTCBrowserType = require("../RTC/RTCBrowserType");
  5891. var SSRCReplacement = require("./LocalSSRCReplacement");
  5892. var RTC = require("../RTC/RTC");
  5893. // Jingle stuff
  5894. function JingleSessionPC(me, sid, connection, service) {
  5895. JingleSession.call(this, me, sid, connection, service);
  5896. this.initiator = null;
  5897. this.responder = null;
  5898. this.peerjid = null;
  5899. this.state = null;
  5900. this.localSDP = null;
  5901. this.remoteSDP = null;
  5902. this.relayedStreams = [];
  5903. this.usetrickle = true;
  5904. this.usepranswer = false; // early transport warmup -- mind you, this might fail. depends on webrtc issue 1718
  5905. this.hadstuncandidate = false;
  5906. this.hadturncandidate = false;
  5907. this.lasticecandidate = false;
  5908. this.statsinterval = null;
  5909. this.reason = null;
  5910. this.addssrc = [];
  5911. this.removessrc = [];
  5912. this.pendingop = null;
  5913. this.switchstreams = false;
  5914. this.addingStreams = false;
  5915. this.wait = true;
  5916. /**
  5917. * A map that stores SSRCs of local streams
  5918. * @type {{}} maps media type('audio' or 'video') to SSRC number
  5919. */
  5920. this.localStreamsSSRC = {};
  5921. this.ssrcOwners = {};
  5922. this.ssrcVideoTypes = {};
  5923. this.webrtcIceUdpDisable = !!this.service.options.webrtcIceUdpDisable;
  5924. this.webrtcIceTcpDisable = !!this.service.options.webrtcIceTcpDisable;
  5925. /**
  5926. * The indicator which determines whether the (local) video has been muted
  5927. * in response to a user command in contrast to an automatic decision made
  5928. * by the application logic.
  5929. */
  5930. this.videoMuteByUser = false;
  5931. this.modifySourcesQueue = async.queue(this._modifySources.bind(this), 1);
  5932. // We start with the queue paused. We resume it when the signaling state is
  5933. // stable and the ice connection state is connected.
  5934. this.modifySourcesQueue.pause();
  5935. }
  5936. //XXX this is badly broken...
  5937. JingleSessionPC.prototype = JingleSession.prototype;
  5938. JingleSessionPC.prototype.constructor = JingleSessionPC;
  5939. JingleSessionPC.prototype.setOffer = function(offer) {
  5940. this.setRemoteDescription(offer, 'offer');
  5941. };
  5942. JingleSessionPC.prototype.setAnswer = function(answer) {
  5943. this.setRemoteDescription(answer, 'answer');
  5944. };
  5945. JingleSessionPC.prototype.updateModifySourcesQueue = function() {
  5946. var signalingState = this.peerconnection.signalingState;
  5947. var iceConnectionState = this.peerconnection.iceConnectionState;
  5948. if (signalingState === 'stable' && iceConnectionState === 'connected') {
  5949. this.modifySourcesQueue.resume();
  5950. } else {
  5951. this.modifySourcesQueue.pause();
  5952. }
  5953. };
  5954. JingleSessionPC.prototype.doInitialize = function () {
  5955. var self = this;
  5956. this.hadstuncandidate = false;
  5957. this.hadturncandidate = false;
  5958. this.lasticecandidate = false;
  5959. // True if reconnect is in progress
  5960. this.isreconnect = false;
  5961. // Set to true if the connection was ever stable
  5962. this.wasstable = false;
  5963. this.peerconnection = new TraceablePeerConnection(
  5964. this.connection.jingle.ice_config,
  5965. RTC.getPCConstraints(),
  5966. this);
  5967. this.peerconnection.onicecandidate = function (event) {
  5968. var protocol;
  5969. if (event && event.candidate) {
  5970. protocol = (typeof event.candidate.protocol === 'string')
  5971. ? event.candidate.protocol.toLowerCase() : '';
  5972. if ((self.webrtcIceTcpDisable && protocol == 'tcp') ||
  5973. (self.webrtcIceUdpDisable && protocol == 'udp')) {
  5974. return;
  5975. }
  5976. }
  5977. self.sendIceCandidate(event.candidate);
  5978. };
  5979. this.peerconnection.onaddstream = function (event) {
  5980. if (event.stream.id !== 'default') {
  5981. logger.log("REMOTE STREAM ADDED: ", event.stream , event.stream.id);
  5982. self.remoteStreamAdded(event);
  5983. } else {
  5984. // This is a recvonly stream. Clients that implement Unified Plan,
  5985. // such as Firefox use recvonly "streams/channels/tracks" for
  5986. // receiving remote stream/tracks, as opposed to Plan B where there
  5987. // are only 3 channels: audio, video and data.
  5988. logger.log("RECVONLY REMOTE STREAM IGNORED: " + event.stream + " - " + event.stream.id);
  5989. }
  5990. };
  5991. this.peerconnection.onremovestream = function (event) {
  5992. // Remove the stream from remoteStreams
  5993. // FIXME: remotestreamremoved.jingle not defined anywhere(unused)
  5994. $(document).trigger('remotestreamremoved.jingle', [event, self.sid]);
  5995. };
  5996. this.peerconnection.onsignalingstatechange = function (event) {
  5997. if (!(self && self.peerconnection)) return;
  5998. if (self.peerconnection.signalingState === 'stable') {
  5999. self.wasstable = true;
  6000. }
  6001. self.updateModifySourcesQueue();
  6002. };
  6003. /**
  6004. * The oniceconnectionstatechange event handler contains the code to execute when the iceconnectionstatechange event,
  6005. * of type Event, is received by this RTCPeerConnection. Such an event is sent when the value of
  6006. * RTCPeerConnection.iceConnectionState changes.
  6007. *
  6008. * @param event the event containing information about the change
  6009. */
  6010. this.peerconnection.oniceconnectionstatechange = function (event) {
  6011. if (!(self && self.peerconnection)) return;
  6012. logger.log("(TIME) ICE " + self.peerconnection.iceConnectionState +
  6013. ":\t", window.performance.now());
  6014. self.updateModifySourcesQueue();
  6015. switch (self.peerconnection.iceConnectionState) {
  6016. case 'connected':
  6017. // Informs interested parties that the connection has been restored.
  6018. if (self.peerconnection.signalingState === 'stable' && self.isreconnect)
  6019. self.room.eventEmitter.emit(XMPPEvents.CONNECTION_RESTORED);
  6020. self.isreconnect = false;
  6021. break;
  6022. case 'disconnected':
  6023. self.isreconnect = true;
  6024. // Informs interested parties that the connection has been interrupted.
  6025. if (self.wasstable)
  6026. self.room.eventEmitter.emit(XMPPEvents.CONNECTION_INTERRUPTED);
  6027. break;
  6028. case 'failed':
  6029. self.room.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  6030. break;
  6031. }
  6032. onIceConnectionStateChange(self.sid, self);
  6033. };
  6034. this.peerconnection.onnegotiationneeded = function (event) {
  6035. self.room.eventEmitter.emit(XMPPEvents.PEERCONNECTION_READY, self);
  6036. };
  6037. this.relayedStreams.forEach(function(stream) {
  6038. self.peerconnection.addStream(stream);
  6039. });
  6040. };
  6041. function onIceConnectionStateChange(sid, session) {
  6042. switch (session.peerconnection.iceConnectionState) {
  6043. case 'checking':
  6044. session.timeChecking = (new Date()).getTime();
  6045. session.firstconnect = true;
  6046. break;
  6047. case 'completed': // on caller side
  6048. case 'connected':
  6049. if (session.firstconnect) {
  6050. session.firstconnect = false;
  6051. var metadata = {};
  6052. metadata.setupTime
  6053. = (new Date()).getTime() - session.timeChecking;
  6054. session.peerconnection.getStats(function (res) {
  6055. if(res && res.result) {
  6056. res.result().forEach(function (report) {
  6057. if (report.type == 'googCandidatePair' &&
  6058. report.stat('googActiveConnection') == 'true') {
  6059. metadata.localCandidateType
  6060. = report.stat('googLocalCandidateType');
  6061. metadata.remoteCandidateType
  6062. = report.stat('googRemoteCandidateType');
  6063. // log pair as well so we can get nice pie
  6064. // charts
  6065. metadata.candidatePair
  6066. = report.stat('googLocalCandidateType') +
  6067. ';' +
  6068. report.stat('googRemoteCandidateType');
  6069. if (report.stat('googRemoteAddress').indexOf('[') === 0)
  6070. {
  6071. metadata.ipv6 = true;
  6072. }
  6073. }
  6074. });
  6075. }
  6076. });
  6077. }
  6078. break;
  6079. }
  6080. }
  6081. JingleSessionPC.prototype.accept = function () {
  6082. this.state = 'active';
  6083. var pranswer = this.peerconnection.localDescription;
  6084. if (!pranswer || pranswer.type != 'pranswer') {
  6085. return;
  6086. }
  6087. logger.log('going from pranswer to answer');
  6088. if (this.usetrickle) {
  6089. // remove candidates already sent from session-accept
  6090. var lines = SDPUtil.find_lines(pranswer.sdp, 'a=candidate:');
  6091. for (var i = 0; i < lines.length; i++) {
  6092. pranswer.sdp = pranswer.sdp.replace(lines[i] + '\r\n', '');
  6093. }
  6094. }
  6095. while (SDPUtil.find_line(pranswer.sdp, 'a=inactive')) {
  6096. // FIXME: change any inactive to sendrecv or whatever they were originally
  6097. pranswer.sdp = pranswer.sdp.replace('a=inactive', 'a=sendrecv');
  6098. }
  6099. var prsdp = new SDP(pranswer.sdp);
  6100. if (self.webrtcIceTcpDisable) {
  6101. prsdp.removeTcpCandidates = true;
  6102. }
  6103. if (self.webrtcIceUdpDisable) {
  6104. prsdp.removeUdpCandidates = true;
  6105. }
  6106. var accept = $iq({to: this.peerjid,
  6107. type: 'set'})
  6108. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  6109. action: 'session-accept',
  6110. initiator: this.initiator,
  6111. responder: this.responder,
  6112. sid: this.sid });
  6113. // FIXME why do we generate session-accept in 3 different places ?
  6114. prsdp.toJingle(
  6115. accept,
  6116. this.initiator == this.me ? 'initiator' : 'responder');
  6117. var sdp = this.peerconnection.localDescription.sdp;
  6118. while (SDPUtil.find_line(sdp, 'a=inactive')) {
  6119. // FIXME: change any inactive to sendrecv or whatever they were originally
  6120. sdp = sdp.replace('a=inactive', 'a=sendrecv');
  6121. }
  6122. var self = this;
  6123. this.peerconnection.setLocalDescription(new RTCSessionDescription({type: 'answer', sdp: sdp}),
  6124. function () {
  6125. //logger.log('setLocalDescription success');
  6126. self.setLocalDescription();
  6127. SSRCReplacement.processSessionInit(accept);
  6128. self.connection.sendIQ(accept,
  6129. function () {
  6130. var ack = {};
  6131. ack.source = 'answer';
  6132. $(document).trigger('ack.jingle', [self.sid, ack]);
  6133. },
  6134. function (stanza) {
  6135. var error = ($(stanza).find('error').length) ? {
  6136. code: $(stanza).find('error').attr('code'),
  6137. reason: $(stanza).find('error :first')[0].tagName
  6138. }:{};
  6139. error.source = 'answer';
  6140. JingleSessionPC.onJingleError(self.sid, error);
  6141. },
  6142. 10000);
  6143. },
  6144. function (e) {
  6145. logger.error('setLocalDescription failed', e);
  6146. self.room.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  6147. }
  6148. );
  6149. };
  6150. JingleSessionPC.prototype.terminate = function (reason) {
  6151. this.state = 'ended';
  6152. this.reason = reason;
  6153. this.peerconnection.close();
  6154. if (this.statsinterval !== null) {
  6155. window.clearInterval(this.statsinterval);
  6156. this.statsinterval = null;
  6157. }
  6158. };
  6159. JingleSessionPC.prototype.active = function () {
  6160. return this.state == 'active';
  6161. };
  6162. JingleSessionPC.prototype.sendIceCandidate = function (candidate) {
  6163. var self = this;
  6164. if (candidate && !this.lasticecandidate) {
  6165. var ice = SDPUtil.iceparams(this.localSDP.media[candidate.sdpMLineIndex], this.localSDP.session);
  6166. var jcand = SDPUtil.candidateToJingle(candidate.candidate);
  6167. if (!(ice && jcand)) {
  6168. logger.error('failed to get ice && jcand');
  6169. return;
  6170. }
  6171. ice.xmlns = 'urn:xmpp:jingle:transports:ice-udp:1';
  6172. if (jcand.type === 'srflx') {
  6173. this.hadstuncandidate = true;
  6174. } else if (jcand.type === 'relay') {
  6175. this.hadturncandidate = true;
  6176. }
  6177. if (this.usetrickle) {
  6178. if (this.usedrip) {
  6179. if (this.drip_container.length === 0) {
  6180. // start 20ms callout
  6181. window.setTimeout(function () {
  6182. if (self.drip_container.length === 0) return;
  6183. self.sendIceCandidates(self.drip_container);
  6184. self.drip_container = [];
  6185. }, 20);
  6186. }
  6187. this.drip_container.push(candidate);
  6188. return;
  6189. } else {
  6190. self.sendIceCandidate([candidate]);
  6191. }
  6192. }
  6193. } else {
  6194. //logger.log('sendIceCandidate: last candidate.');
  6195. if (!this.usetrickle) {
  6196. //logger.log('should send full offer now...');
  6197. //FIXME why do we generate session-accept in 3 different places ?
  6198. var init = $iq({to: this.peerjid,
  6199. type: 'set'})
  6200. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  6201. action: this.peerconnection.localDescription.type == 'offer' ? 'session-initiate' : 'session-accept',
  6202. initiator: this.initiator,
  6203. sid: this.sid});
  6204. this.localSDP = new SDP(this.peerconnection.localDescription.sdp);
  6205. if (self.webrtcIceTcpDisable) {
  6206. this.localSDP.removeTcpCandidates = true;
  6207. }
  6208. if (self.webrtcIceUdpDisable) {
  6209. this.localSDP.removeUdpCandidates = true;
  6210. }
  6211. var sendJingle = function (ssrc) {
  6212. if(!ssrc)
  6213. ssrc = {};
  6214. self.localSDP.toJingle(
  6215. init,
  6216. self.initiator == self.me ? 'initiator' : 'responder',
  6217. ssrc);
  6218. SSRCReplacement.processSessionInit(init);
  6219. self.connection.sendIQ(init,
  6220. function () {
  6221. //logger.log('session initiate ack');
  6222. var ack = {};
  6223. ack.source = 'offer';
  6224. $(document).trigger('ack.jingle', [self.sid, ack]);
  6225. },
  6226. function (stanza) {
  6227. self.state = 'error';
  6228. self.peerconnection.close();
  6229. var error = ($(stanza).find('error').length) ? {
  6230. code: $(stanza).find('error').attr('code'),
  6231. reason: $(stanza).find('error :first')[0].tagName,
  6232. }:{};
  6233. error.source = 'offer';
  6234. JingleSessionPC.onJingleError(self.sid, error);
  6235. },
  6236. 10000);
  6237. };
  6238. sendJingle();
  6239. }
  6240. this.lasticecandidate = true;
  6241. logger.log('Have we encountered any srflx candidates? ' + this.hadstuncandidate);
  6242. logger.log('Have we encountered any relay candidates? ' + this.hadturncandidate);
  6243. if (!(this.hadstuncandidate || this.hadturncandidate) && this.peerconnection.signalingState != 'closed') {
  6244. $(document).trigger('nostuncandidates.jingle', [this.sid]);
  6245. }
  6246. }
  6247. };
  6248. JingleSessionPC.prototype.sendIceCandidates = function (candidates) {
  6249. logger.log('sendIceCandidates', candidates);
  6250. var cand = $iq({to: this.peerjid, type: 'set'})
  6251. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  6252. action: 'transport-info',
  6253. initiator: this.initiator,
  6254. sid: this.sid});
  6255. for (var mid = 0; mid < this.localSDP.media.length; mid++) {
  6256. var cands = candidates.filter(function (el) { return el.sdpMLineIndex == mid; });
  6257. var mline = SDPUtil.parse_mline(this.localSDP.media[mid].split('\r\n')[0]);
  6258. if (cands.length > 0) {
  6259. var ice = SDPUtil.iceparams(this.localSDP.media[mid], this.localSDP.session);
  6260. ice.xmlns = 'urn:xmpp:jingle:transports:ice-udp:1';
  6261. cand.c('content', {creator: this.initiator == this.me ? 'initiator' : 'responder',
  6262. name: (cands[0].sdpMid? cands[0].sdpMid : mline.media)
  6263. }).c('transport', ice);
  6264. for (var i = 0; i < cands.length; i++) {
  6265. cand.c('candidate', SDPUtil.candidateToJingle(cands[i].candidate)).up();
  6266. }
  6267. // add fingerprint
  6268. if (SDPUtil.find_line(this.localSDP.media[mid], 'a=fingerprint:', this.localSDP.session)) {
  6269. var tmp = SDPUtil.parse_fingerprint(SDPUtil.find_line(this.localSDP.media[mid], 'a=fingerprint:', this.localSDP.session));
  6270. tmp.required = true;
  6271. cand.c(
  6272. 'fingerprint',
  6273. {xmlns: 'urn:xmpp:jingle:apps:dtls:0'})
  6274. .t(tmp.fingerprint);
  6275. delete tmp.fingerprint;
  6276. cand.attrs(tmp);
  6277. cand.up();
  6278. }
  6279. cand.up(); // transport
  6280. cand.up(); // content
  6281. }
  6282. }
  6283. // might merge last-candidate notification into this, but it is called alot later. See webrtc issue #2340
  6284. //logger.log('was this the last candidate', this.lasticecandidate);
  6285. this.connection.sendIQ(cand,
  6286. function () {
  6287. var ack = {};
  6288. ack.source = 'transportinfo';
  6289. $(document).trigger('ack.jingle', [this.sid, ack]);
  6290. },
  6291. function (stanza) {
  6292. var error = ($(stanza).find('error').length) ? {
  6293. code: $(stanza).find('error').attr('code'),
  6294. reason: $(stanza).find('error :first')[0].tagName,
  6295. }:{};
  6296. error.source = 'transportinfo';
  6297. JingleSessionPC.onJingleError(this.sid, error);
  6298. },
  6299. 10000);
  6300. };
  6301. JingleSessionPC.prototype.sendOffer = function () {
  6302. //logger.log('sendOffer...');
  6303. var self = this;
  6304. this.peerconnection.createOffer(function (sdp) {
  6305. self.createdOffer(sdp);
  6306. },
  6307. function (e) {
  6308. logger.error('createOffer failed', e);
  6309. },
  6310. this.media_constraints
  6311. );
  6312. };
  6313. // FIXME createdOffer is never used in jitsi-meet
  6314. JingleSessionPC.prototype.createdOffer = function (sdp) {
  6315. //logger.log('createdOffer', sdp);
  6316. var self = this;
  6317. this.localSDP = new SDP(sdp.sdp);
  6318. //this.localSDP.mangle();
  6319. var sendJingle = function () {
  6320. var init = $iq({to: this.peerjid,
  6321. type: 'set'})
  6322. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  6323. action: 'session-initiate',
  6324. initiator: this.initiator,
  6325. sid: this.sid});
  6326. self.localSDP.toJingle(
  6327. init,
  6328. this.initiator == this.me ? 'initiator' : 'responder');
  6329. SSRCReplacement.processSessionInit(init);
  6330. self.connection.sendIQ(init,
  6331. function () {
  6332. var ack = {};
  6333. ack.source = 'offer';
  6334. $(document).trigger('ack.jingle', [self.sid, ack]);
  6335. },
  6336. function (stanza) {
  6337. self.state = 'error';
  6338. self.peerconnection.close();
  6339. var error = ($(stanza).find('error').length) ? {
  6340. code: $(stanza).find('error').attr('code'),
  6341. reason: $(stanza).find('error :first')[0].tagName,
  6342. }:{};
  6343. error.source = 'offer';
  6344. JingleSessionPC.onJingleError(self.sid, error);
  6345. },
  6346. 10000);
  6347. }
  6348. sdp.sdp = this.localSDP.raw;
  6349. this.peerconnection.setLocalDescription(sdp,
  6350. function () {
  6351. if(self.usetrickle)
  6352. {
  6353. sendJingle();
  6354. }
  6355. self.setLocalDescription();
  6356. //logger.log('setLocalDescription success');
  6357. },
  6358. function (e) {
  6359. logger.error('setLocalDescription failed', e);
  6360. self.room.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  6361. }
  6362. );
  6363. var cands = SDPUtil.find_lines(this.localSDP.raw, 'a=candidate:');
  6364. for (var i = 0; i < cands.length; i++) {
  6365. var cand = SDPUtil.parse_icecandidate(cands[i]);
  6366. if (cand.type == 'srflx') {
  6367. this.hadstuncandidate = true;
  6368. } else if (cand.type == 'relay') {
  6369. this.hadturncandidate = true;
  6370. }
  6371. }
  6372. };
  6373. JingleSessionPC.prototype.readSsrcInfo = function (contents) {
  6374. var self = this;
  6375. $(contents).each(function (idx, content) {
  6376. var name = $(content).attr('name');
  6377. var mediaType = this.getAttribute('name');
  6378. var ssrcs = $(content).find('description>source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]');
  6379. ssrcs.each(function () {
  6380. var ssrc = this.getAttribute('ssrc');
  6381. $(this).find('>ssrc-info[xmlns="http://jitsi.org/jitmeet"]').each(
  6382. function () {
  6383. var owner = this.getAttribute('owner');
  6384. self.ssrcOwners[ssrc] = owner;
  6385. }
  6386. );
  6387. });
  6388. });
  6389. };
  6390. /**
  6391. * Returns the SSRC of local audio stream.
  6392. * @param mediaType 'audio' or 'video' media type
  6393. * @returns {*} the SSRC number of local audio or video stream.
  6394. */
  6395. JingleSessionPC.prototype.getLocalSSRC = function (mediaType) {
  6396. return this.localStreamsSSRC[mediaType];
  6397. };
  6398. JingleSessionPC.prototype.getSsrcOwner = function (ssrc) {
  6399. return this.ssrcOwners[ssrc];
  6400. };
  6401. JingleSessionPC.prototype.setRemoteDescription = function (elem, desctype) {
  6402. //logger.log('setting remote description... ', desctype);
  6403. this.remoteSDP = new SDP('');
  6404. if (self.webrtcIceTcpDisable) {
  6405. this.remoteSDP.removeTcpCandidates = true;
  6406. }
  6407. if (self.webrtcIceUdpDisable) {
  6408. this.remoteSDP.removeUdpCandidates = true;
  6409. }
  6410. this.remoteSDP.fromJingle(elem);
  6411. this.readSsrcInfo($(elem).find(">content"));
  6412. if (this.peerconnection.remoteDescription) {
  6413. logger.log('setRemoteDescription when remote description is not null, should be pranswer', this.peerconnection.remoteDescription);
  6414. if (this.peerconnection.remoteDescription.type == 'pranswer') {
  6415. var pranswer = new SDP(this.peerconnection.remoteDescription.sdp);
  6416. for (var i = 0; i < pranswer.media.length; i++) {
  6417. // make sure we have ice ufrag and pwd
  6418. if (!SDPUtil.find_line(this.remoteSDP.media[i], 'a=ice-ufrag:', this.remoteSDP.session)) {
  6419. if (SDPUtil.find_line(pranswer.media[i], 'a=ice-ufrag:', pranswer.session)) {
  6420. this.remoteSDP.media[i] += SDPUtil.find_line(pranswer.media[i], 'a=ice-ufrag:', pranswer.session) + '\r\n';
  6421. } else {
  6422. logger.warn('no ice ufrag?');
  6423. }
  6424. if (SDPUtil.find_line(pranswer.media[i], 'a=ice-pwd:', pranswer.session)) {
  6425. this.remoteSDP.media[i] += SDPUtil.find_line(pranswer.media[i], 'a=ice-pwd:', pranswer.session) + '\r\n';
  6426. } else {
  6427. logger.warn('no ice pwd?');
  6428. }
  6429. }
  6430. // copy over candidates
  6431. var lines = SDPUtil.find_lines(pranswer.media[i], 'a=candidate:');
  6432. for (var j = 0; j < lines.length; j++) {
  6433. this.remoteSDP.media[i] += lines[j] + '\r\n';
  6434. }
  6435. }
  6436. this.remoteSDP.raw = this.remoteSDP.session + this.remoteSDP.media.join('');
  6437. }
  6438. }
  6439. var remotedesc = new RTCSessionDescription({type: desctype, sdp: this.remoteSDP.raw});
  6440. this.peerconnection.setRemoteDescription(remotedesc,
  6441. function () {
  6442. //logger.log('setRemoteDescription success');
  6443. },
  6444. function (e) {
  6445. logger.error('setRemoteDescription error', e);
  6446. JingleSessionPC.onJingleFatalError(self, e);
  6447. }
  6448. );
  6449. };
  6450. /**
  6451. * Adds remote ICE candidates to this Jingle session.
  6452. * @param elem An array of Jingle "content" elements?
  6453. */
  6454. JingleSessionPC.prototype.addIceCandidate = function (elem) {
  6455. var self = this;
  6456. if (this.peerconnection.signalingState == 'closed') {
  6457. return;
  6458. }
  6459. if (!this.peerconnection.remoteDescription && this.peerconnection.signalingState == 'have-local-offer') {
  6460. logger.log('trickle ice candidate arriving before session accept...');
  6461. // create a PRANSWER for setRemoteDescription
  6462. if (!this.remoteSDP) {
  6463. var cobbled = 'v=0\r\n' +
  6464. 'o=- 1923518516 2 IN IP4 0.0.0.0\r\n' +// FIXME
  6465. 's=-\r\n' +
  6466. 't=0 0\r\n';
  6467. // first, take some things from the local description
  6468. for (var i = 0; i < this.localSDP.media.length; i++) {
  6469. cobbled += SDPUtil.find_line(this.localSDP.media[i], 'm=') + '\r\n';
  6470. cobbled += SDPUtil.find_lines(this.localSDP.media[i], 'a=rtpmap:').join('\r\n') + '\r\n';
  6471. if (SDPUtil.find_line(this.localSDP.media[i], 'a=mid:')) {
  6472. cobbled += SDPUtil.find_line(this.localSDP.media[i], 'a=mid:') + '\r\n';
  6473. }
  6474. cobbled += 'a=inactive\r\n';
  6475. }
  6476. this.remoteSDP = new SDP(cobbled);
  6477. }
  6478. // then add things like ice and dtls from remote candidate
  6479. elem.each(function () {
  6480. for (var i = 0; i < self.remoteSDP.media.length; i++) {
  6481. if (SDPUtil.find_line(self.remoteSDP.media[i], 'a=mid:' + $(this).attr('name')) ||
  6482. self.remoteSDP.media[i].indexOf('m=' + $(this).attr('name')) === 0) {
  6483. if (!SDPUtil.find_line(self.remoteSDP.media[i], 'a=ice-ufrag:')) {
  6484. var tmp = $(this).find('transport');
  6485. self.remoteSDP.media[i] += 'a=ice-ufrag:' + tmp.attr('ufrag') + '\r\n';
  6486. self.remoteSDP.media[i] += 'a=ice-pwd:' + tmp.attr('pwd') + '\r\n';
  6487. tmp = $(this).find('transport>fingerprint');
  6488. if (tmp.length) {
  6489. self.remoteSDP.media[i] += 'a=fingerprint:' + tmp.attr('hash') + ' ' + tmp.text() + '\r\n';
  6490. } else {
  6491. logger.log('no dtls fingerprint (webrtc issue #1718?)');
  6492. self.remoteSDP.media[i] += 'a=crypto:1 AES_CM_128_HMAC_SHA1_80 inline:BAADBAADBAADBAADBAADBAADBAADBAADBAADBAAD\r\n';
  6493. }
  6494. break;
  6495. }
  6496. }
  6497. }
  6498. });
  6499. this.remoteSDP.raw = this.remoteSDP.session + this.remoteSDP.media.join('');
  6500. // we need a complete SDP with ice-ufrag/ice-pwd in all parts
  6501. // this makes the assumption that the PRANSWER is constructed such that the ice-ufrag is in all mediaparts
  6502. // but it could be in the session part as well. since the code above constructs this sdp this can't happen however
  6503. var iscomplete = this.remoteSDP.media.filter(function (mediapart) {
  6504. return SDPUtil.find_line(mediapart, 'a=ice-ufrag:');
  6505. }).length == this.remoteSDP.media.length;
  6506. if (iscomplete) {
  6507. logger.log('setting pranswer');
  6508. try {
  6509. this.peerconnection.setRemoteDescription(new RTCSessionDescription({type: 'pranswer', sdp: this.remoteSDP.raw }),
  6510. function() {
  6511. },
  6512. function(e) {
  6513. logger.log('setRemoteDescription pranswer failed', e.toString());
  6514. });
  6515. } catch (e) {
  6516. logger.error('setting pranswer failed', e);
  6517. }
  6518. } else {
  6519. //logger.log('not yet setting pranswer');
  6520. }
  6521. }
  6522. // operate on each content element
  6523. elem.each(function () {
  6524. // would love to deactivate this, but firefox still requires it
  6525. var idx = -1;
  6526. var i;
  6527. for (i = 0; i < self.remoteSDP.media.length; i++) {
  6528. if (SDPUtil.find_line(self.remoteSDP.media[i], 'a=mid:' + $(this).attr('name')) ||
  6529. self.remoteSDP.media[i].indexOf('m=' + $(this).attr('name')) === 0) {
  6530. idx = i;
  6531. break;
  6532. }
  6533. }
  6534. if (idx == -1) { // fall back to localdescription
  6535. for (i = 0; i < self.localSDP.media.length; i++) {
  6536. if (SDPUtil.find_line(self.localSDP.media[i], 'a=mid:' + $(this).attr('name')) ||
  6537. self.localSDP.media[i].indexOf('m=' + $(this).attr('name')) === 0) {
  6538. idx = i;
  6539. break;
  6540. }
  6541. }
  6542. }
  6543. var name = $(this).attr('name');
  6544. // TODO: check ice-pwd and ice-ufrag?
  6545. $(this).find('transport>candidate').each(function () {
  6546. var line, candidate;
  6547. var protocol = this.getAttribute('protocol');
  6548. protocol =
  6549. (typeof protocol === 'string') ? protocol.toLowerCase() : '';
  6550. if ((self.webrtcIceTcpDisable && protocol == 'tcp') ||
  6551. (self.webrtcIceUdpDisable && protocol == 'udp')) {
  6552. return;
  6553. }
  6554. line = SDPUtil.candidateFromJingle(this);
  6555. candidate = new RTCIceCandidate({sdpMLineIndex: idx,
  6556. sdpMid: name,
  6557. candidate: line});
  6558. try {
  6559. self.peerconnection.addIceCandidate(candidate);
  6560. } catch (e) {
  6561. logger.error('addIceCandidate failed', e.toString(), line);
  6562. }
  6563. });
  6564. });
  6565. };
  6566. JingleSessionPC.prototype.sendAnswer = function (provisional) {
  6567. //logger.log('createAnswer', provisional);
  6568. var self = this;
  6569. this.peerconnection.createAnswer(
  6570. function (sdp) {
  6571. self.createdAnswer(sdp, provisional);
  6572. },
  6573. function (e) {
  6574. logger.error('createAnswer failed', e);
  6575. self.room.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  6576. },
  6577. this.media_constraints
  6578. );
  6579. };
  6580. JingleSessionPC.prototype.createdAnswer = function (sdp, provisional) {
  6581. //logger.log('createAnswer callback');
  6582. var self = this;
  6583. this.localSDP = new SDP(sdp.sdp);
  6584. //this.localSDP.mangle();
  6585. this.usepranswer = provisional === true;
  6586. if (this.usetrickle) {
  6587. if (this.usepranswer) {
  6588. sdp.type = 'pranswer';
  6589. for (var i = 0; i < this.localSDP.media.length; i++) {
  6590. this.localSDP.media[i] = this.localSDP.media[i].replace('a=sendrecv\r\n', 'a=inactive\r\n');
  6591. }
  6592. this.localSDP.raw = this.localSDP.session + '\r\n' + this.localSDP.media.join('');
  6593. }
  6594. }
  6595. var self = this;
  6596. var sendJingle = function (ssrcs) {
  6597. // FIXME why do we generate session-accept in 3 different places ?
  6598. var accept = $iq({to: self.peerjid,
  6599. type: 'set'})
  6600. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  6601. action: 'session-accept',
  6602. initiator: self.initiator,
  6603. responder: self.responder,
  6604. sid: self.sid });
  6605. if (self.webrtcIceTcpDisable) {
  6606. self.localSDP.removeTcpCandidates = true;
  6607. }
  6608. if (self.webrtcIceUdpDisable) {
  6609. self.localSDP.removeUdpCandidates = true;
  6610. }
  6611. self.localSDP.toJingle(
  6612. accept,
  6613. self.initiator == self.me ? 'initiator' : 'responder',
  6614. ssrcs);
  6615. SSRCReplacement.processSessionInit(accept);
  6616. self.connection.sendIQ(accept,
  6617. function () {
  6618. var ack = {};
  6619. ack.source = 'answer';
  6620. $(document).trigger('ack.jingle', [self.sid, ack]);
  6621. },
  6622. function (stanza) {
  6623. var error = ($(stanza).find('error').length) ? {
  6624. code: $(stanza).find('error').attr('code'),
  6625. reason: $(stanza).find('error :first')[0].tagName,
  6626. }:{};
  6627. error.source = 'answer';
  6628. JingleSessionPC.onJingleError(self.sid, error);
  6629. },
  6630. 10000);
  6631. }
  6632. sdp.sdp = this.localSDP.raw;
  6633. this.peerconnection.setLocalDescription(sdp,
  6634. function () {
  6635. //logger.log('setLocalDescription success');
  6636. if (self.usetrickle && !self.usepranswer) {
  6637. sendJingle();
  6638. }
  6639. self.setLocalDescription();
  6640. },
  6641. function (e) {
  6642. logger.error('setLocalDescription failed', e);
  6643. self.room.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  6644. }
  6645. );
  6646. var cands = SDPUtil.find_lines(this.localSDP.raw, 'a=candidate:');
  6647. for (var j = 0; j < cands.length; j++) {
  6648. var cand = SDPUtil.parse_icecandidate(cands[j]);
  6649. if (cand.type == 'srflx') {
  6650. this.hadstuncandidate = true;
  6651. } else if (cand.type == 'relay') {
  6652. this.hadturncandidate = true;
  6653. }
  6654. }
  6655. };
  6656. JingleSessionPC.prototype.sendTerminate = function (reason, text) {
  6657. var self = this,
  6658. term = $iq({to: this.peerjid,
  6659. type: 'set'})
  6660. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  6661. action: 'session-terminate',
  6662. initiator: this.initiator,
  6663. sid: this.sid})
  6664. .c('reason')
  6665. .c(reason || 'success');
  6666. if (text) {
  6667. term.up().c('text').t(text);
  6668. }
  6669. this.connection.sendIQ(term,
  6670. function () {
  6671. self.peerconnection.close();
  6672. self.peerconnection = null;
  6673. self.terminate();
  6674. var ack = {};
  6675. ack.source = 'terminate';
  6676. $(document).trigger('ack.jingle', [self.sid, ack]);
  6677. },
  6678. function (stanza) {
  6679. var error = ($(stanza).find('error').length) ? {
  6680. code: $(stanza).find('error').attr('code'),
  6681. reason: $(stanza).find('error :first')[0].tagName,
  6682. }:{};
  6683. $(document).trigger('ack.jingle', [self.sid, error]);
  6684. },
  6685. 10000);
  6686. if (this.statsinterval !== null) {
  6687. window.clearInterval(this.statsinterval);
  6688. this.statsinterval = null;
  6689. }
  6690. };
  6691. /**
  6692. * Handles a Jingle source-add message for this Jingle session.
  6693. * @param elem An array of Jingle "content" elements.
  6694. */
  6695. JingleSessionPC.prototype.addSource = function (elem) {
  6696. var self = this;
  6697. // FIXME: dirty waiting
  6698. if (!this.peerconnection.localDescription)
  6699. {
  6700. logger.warn("addSource - localDescription not ready yet")
  6701. setTimeout(function()
  6702. {
  6703. self.addSource(elem);
  6704. },
  6705. 200
  6706. );
  6707. return;
  6708. }
  6709. logger.log('addssrc', new Date().getTime());
  6710. logger.log('ice', this.peerconnection.iceConnectionState);
  6711. this.readSsrcInfo(elem);
  6712. var sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  6713. var mySdp = new SDP(this.peerconnection.localDescription.sdp);
  6714. $(elem).each(function (idx, content) {
  6715. var name = $(content).attr('name');
  6716. var lines = '';
  6717. $(content).find('ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]').each(function() {
  6718. var semantics = this.getAttribute('semantics');
  6719. var ssrcs = $(this).find('>source').map(function () {
  6720. return this.getAttribute('ssrc');
  6721. }).get();
  6722. if (ssrcs.length) {
  6723. lines += 'a=ssrc-group:' + semantics + ' ' + ssrcs.join(' ') + '\r\n';
  6724. }
  6725. });
  6726. var tmp = $(content).find('source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]'); // can handle both >source and >description>source
  6727. tmp.each(function () {
  6728. var ssrc = $(this).attr('ssrc');
  6729. if(mySdp.containsSSRC(ssrc)){
  6730. /**
  6731. * This happens when multiple participants change their streams at the same time and
  6732. * ColibriFocus.modifySources have to wait for stable state. In the meantime multiple
  6733. * addssrc are scheduled for update IQ. See
  6734. */
  6735. logger.warn("Got add stream request for my own ssrc: "+ssrc);
  6736. return;
  6737. }
  6738. if (sdp.containsSSRC(ssrc)) {
  6739. logger.warn("Source-add request for existing SSRC: " + ssrc);
  6740. return;
  6741. }
  6742. $(this).find('>parameter').each(function () {
  6743. lines += 'a=ssrc:' + ssrc + ' ' + $(this).attr('name');
  6744. if ($(this).attr('value') && $(this).attr('value').length)
  6745. lines += ':' + $(this).attr('value');
  6746. lines += '\r\n';
  6747. });
  6748. });
  6749. sdp.media.forEach(function(media, idx) {
  6750. if (!SDPUtil.find_line(media, 'a=mid:' + name))
  6751. return;
  6752. sdp.media[idx] += lines;
  6753. if (!self.addssrc[idx]) self.addssrc[idx] = '';
  6754. self.addssrc[idx] += lines;
  6755. });
  6756. sdp.raw = sdp.session + sdp.media.join('');
  6757. });
  6758. this.modifySourcesQueue.push(function() {
  6759. // When a source is added and if this is FF, a new channel is allocated
  6760. // for receiving the added source. We need to diffuse the SSRC of this
  6761. // new recvonly channel to the rest of the peers.
  6762. logger.log('modify sources done');
  6763. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  6764. logger.log("SDPs", mySdp, newSdp);
  6765. self.notifyMySSRCUpdate(mySdp, newSdp);
  6766. });
  6767. };
  6768. /**
  6769. * Handles a Jingle source-remove message for this Jingle session.
  6770. * @param elem An array of Jingle "content" elements.
  6771. */
  6772. JingleSessionPC.prototype.removeSource = function (elem) {
  6773. var self = this;
  6774. // FIXME: dirty waiting
  6775. if (!this.peerconnection.localDescription) {
  6776. logger.warn("removeSource - localDescription not ready yet");
  6777. setTimeout(function() {
  6778. self.removeSource(elem);
  6779. },
  6780. 200
  6781. );
  6782. return;
  6783. }
  6784. logger.log('removessrc', new Date().getTime());
  6785. logger.log('ice', this.peerconnection.iceConnectionState);
  6786. var sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  6787. var mySdp = new SDP(this.peerconnection.localDescription.sdp);
  6788. $(elem).each(function (idx, content) {
  6789. var name = $(content).attr('name');
  6790. var lines = '';
  6791. $(content).find('ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]').each(function() {
  6792. var semantics = this.getAttribute('semantics');
  6793. var ssrcs = $(this).find('>source').map(function () {
  6794. return this.getAttribute('ssrc');
  6795. }).get();
  6796. if (ssrcs.length) {
  6797. lines += 'a=ssrc-group:' + semantics + ' ' + ssrcs.join(' ') + '\r\n';
  6798. }
  6799. });
  6800. var tmp = $(content).find('source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]'); // can handle both >source and >description>source
  6801. tmp.each(function () {
  6802. var ssrc = $(this).attr('ssrc');
  6803. // This should never happen, but can be useful for bug detection
  6804. if(mySdp.containsSSRC(ssrc)){
  6805. logger.error("Got remove stream request for my own ssrc: "+ssrc);
  6806. return;
  6807. }
  6808. $(this).find('>parameter').each(function () {
  6809. lines += 'a=ssrc:' + ssrc + ' ' + $(this).attr('name');
  6810. if ($(this).attr('value') && $(this).attr('value').length)
  6811. lines += ':' + $(this).attr('value');
  6812. lines += '\r\n';
  6813. });
  6814. });
  6815. sdp.media.forEach(function(media, idx) {
  6816. if (!SDPUtil.find_line(media, 'a=mid:' + name))
  6817. return;
  6818. sdp.media[idx] += lines;
  6819. if (!self.removessrc[idx]) self.removessrc[idx] = '';
  6820. self.removessrc[idx] += lines;
  6821. });
  6822. sdp.raw = sdp.session + sdp.media.join('');
  6823. });
  6824. this.modifySourcesQueue.push(function() {
  6825. // When a source is removed and if this is FF, the recvonly channel that
  6826. // receives the remote stream is deactivated . We need to diffuse the
  6827. // recvonly SSRC removal to the rest of the peers.
  6828. logger.log('modify sources done');
  6829. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  6830. logger.log("SDPs", mySdp, newSdp);
  6831. self.notifyMySSRCUpdate(mySdp, newSdp);
  6832. });
  6833. };
  6834. JingleSessionPC.prototype._modifySources = function (successCallback, queueCallback) {
  6835. var self = this;
  6836. if (this.peerconnection.signalingState == 'closed') return;
  6837. if (!(this.addssrc.length || this.removessrc.length || this.pendingop !== null
  6838. || this.switchstreams || this.addingStreams)){
  6839. // There is nothing to do since scheduled job might have been executed by another succeeding call
  6840. this.setLocalDescription();
  6841. if(successCallback){
  6842. successCallback();
  6843. }
  6844. queueCallback();
  6845. return;
  6846. }
  6847. // Reset switch streams flags
  6848. this.switchstreams = false;
  6849. this.addingStreams = false;
  6850. var sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  6851. // add sources
  6852. this.addssrc.forEach(function(lines, idx) {
  6853. sdp.media[idx] += lines;
  6854. });
  6855. this.addssrc = [];
  6856. // remove sources
  6857. this.removessrc.forEach(function(lines, idx) {
  6858. lines = lines.split('\r\n');
  6859. lines.pop(); // remove empty last element;
  6860. lines.forEach(function(line) {
  6861. sdp.media[idx] = sdp.media[idx].replace(line + '\r\n', '');
  6862. });
  6863. });
  6864. this.removessrc = [];
  6865. sdp.raw = sdp.session + sdp.media.join('');
  6866. this.peerconnection.setRemoteDescription(new RTCSessionDescription({type: 'offer', sdp: sdp.raw}),
  6867. function() {
  6868. if(self.signalingState == 'closed') {
  6869. logger.error("createAnswer attempt on closed state");
  6870. queueCallback("createAnswer attempt on closed state");
  6871. return;
  6872. }
  6873. self.peerconnection.createAnswer(
  6874. function(modifiedAnswer) {
  6875. // change video direction, see https://github.com/jitsi/jitmeet/issues/41
  6876. if (self.pendingop !== null) {
  6877. var sdp = new SDP(modifiedAnswer.sdp);
  6878. if (sdp.media.length > 1) {
  6879. switch(self.pendingop) {
  6880. case 'mute':
  6881. sdp.media[1] = sdp.media[1].replace('a=sendrecv', 'a=recvonly');
  6882. break;
  6883. case 'unmute':
  6884. sdp.media[1] = sdp.media[1].replace('a=recvonly', 'a=sendrecv');
  6885. break;
  6886. }
  6887. sdp.raw = sdp.session + sdp.media.join('');
  6888. modifiedAnswer.sdp = sdp.raw;
  6889. }
  6890. self.pendingop = null;
  6891. }
  6892. // FIXME: pushing down an answer while ice connection state
  6893. // is still checking is bad...
  6894. //logger.log(self.peerconnection.iceConnectionState);
  6895. // trying to work around another chrome bug
  6896. //modifiedAnswer.sdp = modifiedAnswer.sdp.replace(/a=setup:active/g, 'a=setup:actpass');
  6897. self.peerconnection.setLocalDescription(modifiedAnswer,
  6898. function() {
  6899. //logger.log('modified setLocalDescription ok');
  6900. self.setLocalDescription();
  6901. if(successCallback){
  6902. successCallback();
  6903. }
  6904. queueCallback();
  6905. },
  6906. function(error) {
  6907. logger.error('modified setLocalDescription failed', error);
  6908. queueCallback(error);
  6909. }
  6910. );
  6911. },
  6912. function(error) {
  6913. logger.error('modified answer failed', error);
  6914. queueCallback(error);
  6915. }
  6916. );
  6917. },
  6918. function(error) {
  6919. logger.error('modify failed', error);
  6920. queueCallback(error);
  6921. }
  6922. );
  6923. };
  6924. /**
  6925. * Switches video streams.
  6926. * @param newStream new stream that will be used as video of this session.
  6927. * @param oldStream old video stream of this session.
  6928. * @param successCallback callback executed after successful stream switch.
  6929. * @param isAudio whether the streams are audio (if true) or video (if false).
  6930. */
  6931. JingleSessionPC.prototype.switchStreams =
  6932. function (newStream, oldStream, successCallback, isAudio) {
  6933. var self = this;
  6934. var sender, newTrack;
  6935. var senderKind = isAudio ? 'audio' : 'video';
  6936. // Remember SDP to figure out added/removed SSRCs
  6937. var oldSdp = null;
  6938. if (self.peerconnection) {
  6939. if (self.peerconnection.localDescription) {
  6940. oldSdp = new SDP(self.peerconnection.localDescription.sdp);
  6941. }
  6942. if (RTCBrowserType.getBrowserType() ===
  6943. RTCBrowserType.RTC_BROWSER_FIREFOX) {
  6944. // On Firefox we don't replace MediaStreams as this messes up the
  6945. // m-lines (which can't be removed in Plan Unified) and brings a lot
  6946. // of complications. Instead, we use the RTPSender and replace just
  6947. // the track.
  6948. // Find the right sender (for audio or video)
  6949. self.peerconnection.peerconnection.getSenders().some(function (s) {
  6950. if (s.track && s.track.kind === senderKind) {
  6951. sender = s;
  6952. return true;
  6953. }
  6954. });
  6955. if (sender) {
  6956. // We assume that our streams have a single track, either audio
  6957. // or video.
  6958. newTrack = isAudio ? newStream.getAudioTracks()[0] :
  6959. newStream.getVideoTracks()[0];
  6960. sender.replaceTrack(newTrack)
  6961. .then(function() {
  6962. console.log("Replaced a track, isAudio=" + isAudio);
  6963. })
  6964. .catch(function(err) {
  6965. console.log("Failed to replace a track: " + err);
  6966. });
  6967. } else {
  6968. console.log("Cannot switch tracks: no RTPSender.");
  6969. }
  6970. } else {
  6971. self.peerconnection.removeStream(oldStream, true);
  6972. if (newStream) {
  6973. self.peerconnection.addStream(newStream);
  6974. }
  6975. }
  6976. }
  6977. // Conference is not active
  6978. if (!oldSdp) {
  6979. successCallback();
  6980. return;
  6981. }
  6982. self.switchstreams = true;
  6983. self.modifySourcesQueue.push(function() {
  6984. logger.log('modify sources done');
  6985. successCallback();
  6986. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  6987. logger.log("SDPs", oldSdp, newSdp);
  6988. self.notifyMySSRCUpdate(oldSdp, newSdp);
  6989. });
  6990. };
  6991. /**
  6992. * Adds streams.
  6993. * @param stream new stream that will be added.
  6994. * @param success_callback callback executed after successful stream addition.
  6995. */
  6996. JingleSessionPC.prototype.addStream = function (stream, callback) {
  6997. var self = this;
  6998. // Remember SDP to figure out added/removed SSRCs
  6999. var oldSdp = null;
  7000. if(this.peerconnection) {
  7001. if(this.peerconnection.localDescription) {
  7002. oldSdp = new SDP(this.peerconnection.localDescription.sdp);
  7003. }
  7004. if(stream)
  7005. this.peerconnection.addStream(stream);
  7006. }
  7007. // Conference is not active
  7008. if(!oldSdp || !this.peerconnection) {
  7009. callback();
  7010. return;
  7011. }
  7012. this.addingStreams = true;
  7013. this.modifySourcesQueue.push(function() {
  7014. logger.log('modify sources done');
  7015. callback();
  7016. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  7017. logger.log("SDPs", oldSdp, newSdp);
  7018. self.notifyMySSRCUpdate(oldSdp, newSdp);
  7019. });
  7020. }
  7021. /**
  7022. * Remove streams.
  7023. * @param stream stream that will be removed.
  7024. * @param success_callback callback executed after successful stream addition.
  7025. */
  7026. JingleSessionPC.prototype.removeStream = function (stream, callback) {
  7027. var self = this;
  7028. // Remember SDP to figure out added/removed SSRCs
  7029. var oldSdp = null;
  7030. if(this.peerconnection) {
  7031. if(this.peerconnection.localDescription) {
  7032. oldSdp = new SDP(this.peerconnection.localDescription.sdp);
  7033. }
  7034. if(stream)
  7035. this.peerconnection.removeStream(stream);
  7036. }
  7037. // Conference is not active
  7038. if(!oldSdp || !this.peerconnection) {
  7039. callback();
  7040. return;
  7041. }
  7042. this.addingStreams = true;
  7043. this.modifySourcesQueue.push(function() {
  7044. logger.log('modify sources done');
  7045. callback();
  7046. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  7047. logger.log("SDPs", oldSdp, newSdp);
  7048. self.notifyMySSRCUpdate(oldSdp, newSdp);
  7049. });
  7050. }
  7051. /**
  7052. * Figures out added/removed ssrcs and send update IQs.
  7053. * @param old_sdp SDP object for old description.
  7054. * @param new_sdp SDP object for new description.
  7055. */
  7056. JingleSessionPC.prototype.notifyMySSRCUpdate = function (old_sdp, new_sdp) {
  7057. if (!(this.peerconnection.signalingState == 'stable' &&
  7058. this.peerconnection.iceConnectionState == 'connected')){
  7059. logger.log("Too early to send updates");
  7060. return;
  7061. }
  7062. // send source-remove IQ.
  7063. sdpDiffer = new SDPDiffer(new_sdp, old_sdp);
  7064. var remove = $iq({to: this.peerjid, type: 'set'})
  7065. .c('jingle', {
  7066. xmlns: 'urn:xmpp:jingle:1',
  7067. action: 'source-remove',
  7068. initiator: this.initiator,
  7069. sid: this.sid
  7070. }
  7071. );
  7072. var removed = sdpDiffer.toJingle(remove);
  7073. // Let 'source-remove' IQ through the hack and see if we're allowed to send
  7074. // it in the current form
  7075. if (removed)
  7076. remove = SSRCReplacement.processSourceRemove(remove);
  7077. if (removed && remove) {
  7078. logger.info("Sending source-remove", remove);
  7079. this.connection.sendIQ(remove,
  7080. function (res) {
  7081. logger.info('got remove result', res);
  7082. },
  7083. function (err) {
  7084. logger.error('got remove error', err);
  7085. }
  7086. );
  7087. } else {
  7088. logger.log('removal not necessary');
  7089. }
  7090. // send source-add IQ.
  7091. var sdpDiffer = new SDPDiffer(old_sdp, new_sdp);
  7092. var add = $iq({to: this.peerjid, type: 'set'})
  7093. .c('jingle', {
  7094. xmlns: 'urn:xmpp:jingle:1',
  7095. action: 'source-add',
  7096. initiator: this.initiator,
  7097. sid: this.sid
  7098. }
  7099. );
  7100. var added = sdpDiffer.toJingle(add);
  7101. // Let 'source-add' IQ through the hack and see if we're allowed to send
  7102. // it in the current form
  7103. if (added)
  7104. add = SSRCReplacement.processSourceAdd(add);
  7105. if (added && add) {
  7106. logger.info("Sending source-add", add);
  7107. this.connection.sendIQ(add,
  7108. function (res) {
  7109. logger.info('got add result', res);
  7110. },
  7111. function (err) {
  7112. logger.error('got add error', err);
  7113. }
  7114. );
  7115. } else {
  7116. logger.log('addition not necessary');
  7117. }
  7118. };
  7119. /**
  7120. * Mutes/unmutes the (local) video i.e. enables/disables all video tracks.
  7121. *
  7122. * @param mute <tt>true</tt> to mute the (local) video i.e. to disable all video
  7123. * tracks; otherwise, <tt>false</tt>
  7124. * @param callback a function to be invoked with <tt>mute</tt> after all video
  7125. * tracks have been enabled/disabled. The function may, optionally, return
  7126. * another function which is to be invoked after the whole mute/unmute operation
  7127. * has completed successfully.
  7128. * @param options an object which specifies optional arguments such as the
  7129. * <tt>boolean</tt> key <tt>byUser</tt> with default value <tt>true</tt> which
  7130. * specifies whether the method was initiated in response to a user command (in
  7131. * contrast to an automatic decision made by the application logic)
  7132. */
  7133. JingleSessionPC.prototype.setVideoMute = function (mute, callback, options) {
  7134. var byUser;
  7135. if (options) {
  7136. byUser = options.byUser;
  7137. if (typeof byUser === 'undefined') {
  7138. byUser = true;
  7139. }
  7140. } else {
  7141. byUser = true;
  7142. }
  7143. // The user's command to mute the (local) video takes precedence over any
  7144. // automatic decision made by the application logic.
  7145. if (byUser) {
  7146. this.videoMuteByUser = mute;
  7147. } else if (this.videoMuteByUser) {
  7148. return;
  7149. }
  7150. this.hardMuteVideo(mute);
  7151. var self = this;
  7152. var oldSdp = null;
  7153. if(self.peerconnection) {
  7154. if(self.peerconnection.localDescription) {
  7155. oldSdp = new SDP(self.peerconnection.localDescription.sdp);
  7156. }
  7157. }
  7158. this.modifySourcesQueue.push(function() {
  7159. logger.log('modify sources done');
  7160. callback(mute);
  7161. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  7162. logger.log("SDPs", oldSdp, newSdp);
  7163. self.notifyMySSRCUpdate(oldSdp, newSdp);
  7164. });
  7165. };
  7166. JingleSessionPC.prototype.hardMuteVideo = function (muted) {
  7167. this.pendingop = muted ? 'mute' : 'unmute';
  7168. };
  7169. JingleSessionPC.prototype.sendMute = function (muted, content) {
  7170. var info = $iq({to: this.peerjid,
  7171. type: 'set'})
  7172. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  7173. action: 'session-info',
  7174. initiator: this.initiator,
  7175. sid: this.sid });
  7176. info.c(muted ? 'mute' : 'unmute', {xmlns: 'urn:xmpp:jingle:apps:rtp:info:1'});
  7177. info.attrs({'creator': this.me == this.initiator ? 'creator' : 'responder'});
  7178. if (content) {
  7179. info.attrs({'name': content});
  7180. }
  7181. this.connection.send(info);
  7182. };
  7183. JingleSessionPC.prototype.sendRinging = function () {
  7184. var info = $iq({to: this.peerjid,
  7185. type: 'set'})
  7186. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  7187. action: 'session-info',
  7188. initiator: this.initiator,
  7189. sid: this.sid });
  7190. info.c('ringing', {xmlns: 'urn:xmpp:jingle:apps:rtp:info:1'});
  7191. this.connection.send(info);
  7192. };
  7193. JingleSessionPC.prototype.getStats = function (interval) {
  7194. var self = this;
  7195. var recv = {audio: 0, video: 0};
  7196. var lost = {audio: 0, video: 0};
  7197. var lastrecv = {audio: 0, video: 0};
  7198. var lastlost = {audio: 0, video: 0};
  7199. var loss = {audio: 0, video: 0};
  7200. var delta = {audio: 0, video: 0};
  7201. this.statsinterval = window.setInterval(function () {
  7202. if (self && self.peerconnection && self.peerconnection.getStats) {
  7203. self.peerconnection.getStats(function (stats) {
  7204. var results = stats.result();
  7205. // TODO: there are so much statistics you can get from this..
  7206. for (var i = 0; i < results.length; ++i) {
  7207. if (results[i].type == 'ssrc') {
  7208. var packetsrecv = results[i].stat('packetsReceived');
  7209. var packetslost = results[i].stat('packetsLost');
  7210. if (packetsrecv && packetslost) {
  7211. packetsrecv = parseInt(packetsrecv, 10);
  7212. packetslost = parseInt(packetslost, 10);
  7213. if (results[i].stat('googFrameRateReceived')) {
  7214. lastlost.video = lost.video;
  7215. lastrecv.video = recv.video;
  7216. recv.video = packetsrecv;
  7217. lost.video = packetslost;
  7218. } else {
  7219. lastlost.audio = lost.audio;
  7220. lastrecv.audio = recv.audio;
  7221. recv.audio = packetsrecv;
  7222. lost.audio = packetslost;
  7223. }
  7224. }
  7225. }
  7226. }
  7227. delta.audio = recv.audio - lastrecv.audio;
  7228. delta.video = recv.video - lastrecv.video;
  7229. loss.audio = (delta.audio > 0) ? Math.ceil(100 * (lost.audio - lastlost.audio) / delta.audio) : 0;
  7230. loss.video = (delta.video > 0) ? Math.ceil(100 * (lost.video - lastlost.video) / delta.video) : 0;
  7231. $(document).trigger('packetloss.jingle', [self.sid, loss]);
  7232. });
  7233. }
  7234. }, interval || 3000);
  7235. return this.statsinterval;
  7236. };
  7237. JingleSessionPC.onJingleError = function (session, error)
  7238. {
  7239. logger.error("Jingle error", error);
  7240. }
  7241. JingleSessionPC.onJingleFatalError = function (session, error)
  7242. {
  7243. this.room.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  7244. this.room.eventEmitter.emit(XMPPEvents.JINGLE_FATAL_ERROR, session, error);
  7245. }
  7246. JingleSessionPC.prototype.setLocalDescription = function () {
  7247. var self = this;
  7248. var newssrcs = [];
  7249. if(!this.peerconnection.localDescription)
  7250. return;
  7251. var session = transform.parse(this.peerconnection.localDescription.sdp);
  7252. var i;
  7253. session.media.forEach(function (media) {
  7254. if (media.ssrcs && media.ssrcs.length > 0) {
  7255. // TODO(gp) maybe exclude FID streams?
  7256. media.ssrcs.forEach(function (ssrc) {
  7257. if (ssrc.attribute !== 'cname') {
  7258. return;
  7259. }
  7260. newssrcs.push({
  7261. 'ssrc': ssrc.id,
  7262. 'type': media.type
  7263. });
  7264. // FIXME allows for only one SSRC per media type
  7265. self.localStreamsSSRC[media.type] = ssrc.id;
  7266. });
  7267. }
  7268. });
  7269. logger.log('new ssrcs', newssrcs);
  7270. // Bind us as local SSRCs owner
  7271. if (newssrcs.length > 0) {
  7272. for (i = 0; i < newssrcs.length; i++) {
  7273. var ssrc = newssrcs[i].ssrc;
  7274. var myJid = self.connection.emuc.myroomjid;
  7275. self.ssrcOwners[ssrc] = myJid;
  7276. }
  7277. }
  7278. }
  7279. // an attempt to work around https://github.com/jitsi/jitmeet/issues/32
  7280. JingleSessionPC.prototype.sendKeyframe = function () {
  7281. var pc = this.peerconnection;
  7282. logger.log('sendkeyframe', pc.iceConnectionState);
  7283. if (pc.iceConnectionState !== 'connected') return; // safe...
  7284. var self = this;
  7285. pc.setRemoteDescription(
  7286. pc.remoteDescription,
  7287. function () {
  7288. pc.createAnswer(
  7289. function (modifiedAnswer) {
  7290. pc.setLocalDescription(
  7291. modifiedAnswer,
  7292. function () {
  7293. // noop
  7294. },
  7295. function (error) {
  7296. logger.log('triggerKeyframe setLocalDescription failed', error);
  7297. self.room.eventEmitter.emit(XMPPEvents.SET_LOCAL_DESCRIPTION_ERROR);
  7298. }
  7299. );
  7300. },
  7301. function (error) {
  7302. logger.log('triggerKeyframe createAnswer failed', error);
  7303. self.room.eventEmitter.emit(XMPPEvents.CREATE_ANSWER_ERROR);
  7304. }
  7305. );
  7306. },
  7307. function (error) {
  7308. logger.log('triggerKeyframe setRemoteDescription failed', error);
  7309. eventEmitter.emit(XMPPEvents.SET_REMOTE_DESCRIPTION_ERROR);
  7310. }
  7311. );
  7312. }
  7313. JingleSessionPC.prototype.remoteStreamAdded = function (data, times) {
  7314. var self = this;
  7315. var thessrc;
  7316. var streamId = RTC.getStreamID(data.stream);
  7317. // look up an associated JID for a stream id
  7318. if (!streamId) {
  7319. logger.error("No stream ID for", data.stream);
  7320. } else if (streamId && streamId.indexOf('mixedmslabel') === -1) {
  7321. // look only at a=ssrc: and _not_ at a=ssrc-group: lines
  7322. var ssrclines = this.peerconnection.remoteDescription?
  7323. SDPUtil.find_lines(this.peerconnection.remoteDescription.sdp, 'a=ssrc:') : [];
  7324. ssrclines = ssrclines.filter(function (line) {
  7325. // NOTE(gp) previously we filtered on the mslabel, but that property
  7326. // is not always present.
  7327. // return line.indexOf('mslabel:' + data.stream.label) !== -1;
  7328. if (RTCBrowserType.isTemasysPluginUsed()) {
  7329. return ((line.indexOf('mslabel:' + streamId) !== -1));
  7330. } else {
  7331. return ((line.indexOf('msid:' + streamId) !== -1));
  7332. }
  7333. });
  7334. if (ssrclines.length) {
  7335. thessrc = ssrclines[0].substring(7).split(' ')[0];
  7336. if (!self.ssrcOwners[thessrc]) {
  7337. logger.error("No SSRC owner known for: " + thessrc);
  7338. return;
  7339. }
  7340. data.peerjid = self.ssrcOwners[thessrc];
  7341. logger.log('associated jid', self.ssrcOwners[thessrc]);
  7342. } else {
  7343. logger.error("No SSRC lines for ", streamId);
  7344. }
  7345. }
  7346. this.room.remoteStreamAdded(data, this.sid, thessrc);
  7347. var isVideo = data.stream.getVideoTracks().length > 0;
  7348. // an attempt to work around https://github.com/jitsi/jitmeet/issues/32
  7349. if (isVideo &&
  7350. data.peerjid && this.peerjid === data.peerjid &&
  7351. data.stream.getVideoTracks().length === 0 &&
  7352. RTC.localVideo.getTracks().length > 0) {
  7353. window.setTimeout(function () {
  7354. self.sendKeyframe();
  7355. }, 3000);
  7356. }
  7357. }
  7358. module.exports = JingleSessionPC;
  7359. }).call(this,"/modules/xmpp/JingleSessionPC.js")
  7360. },{"../../service/xmpp/XMPPEvents":85,"../RTC/RTC":16,"../RTC/RTCBrowserType":17,"./JingleSession":27,"./LocalSSRCReplacement":29,"./SDP":30,"./SDPDiffer":31,"./SDPUtil":32,"./TraceablePeerConnection":33,"async":42,"jitsi-meet-logger":47,"sdp-transform":75}],29:[function(require,module,exports){
  7361. (function (__filename){
  7362. /* global $ */
  7363. var logger = require("jitsi-meet-logger").getLogger(__filename);
  7364. /*
  7365. Here we do modifications of local video SSRCs. There are 2 situations we have
  7366. to handle:
  7367. 1. We generate SSRC for local recvonly video stream. This is the case when we
  7368. have no local camera and it is not generated automatically, but SSRC=1 is
  7369. used implicitly. If that happens RTCP packets will be dropped by the JVB
  7370. and we won't be able to request video key frames correctly.
  7371. 2. A hack to re-use SSRC of the first video stream for any new stream created
  7372. in future. It turned out that Chrome may keep on using the SSRC of removed
  7373. video stream in RTCP even though a new one has been created. So we just
  7374. want to avoid that by re-using it. Jingle 'source-remove'/'source-add'
  7375. notifications are blocked once first video SSRC is advertised to the focus.
  7376. What this hack does:
  7377. 1. Stores the SSRC of the first video stream created by
  7378. a) scanning Jingle session-accept/session-invite for existing video SSRC
  7379. b) watching for 'source-add' for new video stream if it has not been
  7380. created in step a)
  7381. 2. Exposes method 'mungeLocalVideoSSRC' which replaces any new video SSRC with
  7382. the stored one. It is called by 'TracablePeerConnection' before local SDP is
  7383. returned to the other parts of the application.
  7384. 3. Scans 'source-remove'/'source-add' notifications for stored video SSRC and
  7385. blocks those notifications. This makes Jicofo and all participants think
  7386. that it exists all the time even if the video stream has been removed or
  7387. replaced locally. Thanks to that there is no additional signaling activity
  7388. on video mute or when switching to the desktop stream.
  7389. */
  7390. var SDP = require('./SDP');
  7391. var RandomUtil = require('../util/RandomUtil');
  7392. var RTCBrowserType = require('../RTC/RTCBrowserType');
  7393. /**
  7394. * The hack is enabled on all browsers except FF by default
  7395. * FIXME finish the hack once removeStream method is implemented in FF
  7396. * @type {boolean}
  7397. */
  7398. var isEnabled = !RTCBrowserType.isFirefox();
  7399. /**
  7400. * Stored SSRC of local video stream.
  7401. */
  7402. var localVideoSSRC;
  7403. /**
  7404. * SSRC used for recvonly video stream when we have no local camera.
  7405. * This is in order to tell Chrome what SSRC should be used in RTCP requests
  7406. * instead of 1.
  7407. */
  7408. var localRecvOnlySSRC;
  7409. /**
  7410. * cname for <tt>localRecvOnlySSRC</tt>
  7411. */
  7412. var localRecvOnlyCName;
  7413. /**
  7414. * Method removes <source> element which describes <tt>localVideoSSRC</tt>
  7415. * from given Jingle IQ.
  7416. * @param modifyIq 'source-add' or 'source-remove' Jingle IQ.
  7417. * @param actionName display name of the action which will be printed in log
  7418. * messages.
  7419. * @returns {*} modified Jingle IQ, so that it does not contain <source> element
  7420. * corresponding to <tt>localVideoSSRC</tt> or <tt>null</tt> if no
  7421. * other SSRCs left to be signaled after removing it.
  7422. */
  7423. var filterOutSource = function (modifyIq, actionName) {
  7424. var modifyIqTree = $(modifyIq.tree());
  7425. if (!localVideoSSRC)
  7426. return modifyIqTree[0];
  7427. var videoSSRC = modifyIqTree.find(
  7428. '>jingle>content[name="video"]' +
  7429. '>description>source[ssrc="' + localVideoSSRC + '"]');
  7430. if (!videoSSRC.length) {
  7431. return modifyIqTree[0];
  7432. }
  7433. logger.info(
  7434. 'Blocking ' + actionName + ' for local video SSRC: ' + localVideoSSRC);
  7435. videoSSRC.remove();
  7436. // Check if any sources still left to be added/removed
  7437. if (modifyIqTree.find('>jingle>content>description>source').length) {
  7438. return modifyIqTree[0];
  7439. } else {
  7440. return null;
  7441. }
  7442. };
  7443. /**
  7444. * Scans given Jingle IQ for video SSRC and stores it.
  7445. * @param jingleIq the Jingle IQ to be scanned for video SSRC.
  7446. */
  7447. var storeLocalVideoSSRC = function (jingleIq) {
  7448. var videoSSRCs =
  7449. $(jingleIq.tree())
  7450. .find('>jingle>content[name="video"]>description>source');
  7451. videoSSRCs.each(function (idx, ssrcElem) {
  7452. if (localVideoSSRC)
  7453. return;
  7454. // We consider SSRC real only if it has msid attribute
  7455. // recvonly streams in FF do not have it as well as local SSRCs
  7456. // we generate for recvonly streams in Chrome
  7457. var ssrSel = $(ssrcElem);
  7458. var msid = ssrSel.find('>parameter[name="msid"]');
  7459. if (msid.length) {
  7460. var ssrcVal = ssrSel.attr('ssrc');
  7461. if (ssrcVal) {
  7462. localVideoSSRC = ssrcVal;
  7463. logger.info('Stored local video SSRC' +
  7464. ' for future re-use: ' + localVideoSSRC);
  7465. }
  7466. }
  7467. });
  7468. };
  7469. /**
  7470. * Generates new SSRC for local video recvonly stream.
  7471. * FIXME what about eventual SSRC collision ?
  7472. */
  7473. function generateRecvonlySSRC() {
  7474. localRecvOnlySSRC =
  7475. localVideoSSRC ?
  7476. localVideoSSRC : Math.random().toString(10).substring(2, 11);
  7477. localRecvOnlyCName =
  7478. Math.random().toString(36).substring(2);
  7479. logger.info(
  7480. "Generated local recvonly SSRC: " + localRecvOnlySSRC +
  7481. ", cname: " + localRecvOnlyCName);
  7482. }
  7483. var LocalSSRCReplacement = {
  7484. /**
  7485. * Method must be called before 'session-initiate' or 'session-invite' is
  7486. * sent. Scans the IQ for local video SSRC and stores it if detected.
  7487. *
  7488. * @param sessionInit our 'session-initiate' or 'session-accept' Jingle IQ
  7489. * which will be scanned for local video SSRC.
  7490. */
  7491. processSessionInit: function (sessionInit) {
  7492. if (!isEnabled)
  7493. return;
  7494. if (localVideoSSRC) {
  7495. logger.error("Local SSRC stored already: " + localVideoSSRC);
  7496. return;
  7497. }
  7498. storeLocalVideoSSRC(sessionInit);
  7499. },
  7500. /**
  7501. * If we have local video SSRC stored searched given
  7502. * <tt>localDescription</tt> for video SSRC and makes sure it is replaced
  7503. * with the stored one.
  7504. * @param localDescription local description object that will have local
  7505. * video SSRC replaced with the stored one
  7506. * @returns modified <tt>localDescription</tt> object.
  7507. */
  7508. mungeLocalVideoSSRC: function (localDescription) {
  7509. if (!isEnabled)
  7510. return localDescription;
  7511. if (!localDescription) {
  7512. logger.warn("localDescription is null or undefined");
  7513. return localDescription;
  7514. }
  7515. // IF we have local video SSRC stored make sure it is replaced
  7516. // with old SSRC
  7517. var sdp = new SDP(localDescription.sdp);
  7518. if (sdp.media.length < 2)
  7519. return;
  7520. if (localVideoSSRC && sdp.media[1].indexOf("a=ssrc:") !== -1 &&
  7521. !sdp.containsSSRC(localVideoSSRC)) {
  7522. // Get new video SSRC
  7523. var map = sdp.getMediaSsrcMap();
  7524. var videoPart = map[1];
  7525. var videoSSRCs = videoPart.ssrcs;
  7526. var newSSRC = Object.keys(videoSSRCs)[0];
  7527. logger.info(
  7528. "Replacing new video SSRC: " + newSSRC +
  7529. " with " + localVideoSSRC);
  7530. localDescription.sdp =
  7531. sdp.raw.replace(
  7532. new RegExp('a=ssrc:' + newSSRC, 'g'),
  7533. 'a=ssrc:' + localVideoSSRC);
  7534. }
  7535. else if (sdp.media[1].indexOf('a=ssrc:') === -1 &&
  7536. sdp.media[1].indexOf('a=recvonly') !== -1) {
  7537. // Make sure we have any SSRC for recvonly video stream
  7538. if (!localRecvOnlySSRC) {
  7539. generateRecvonlySSRC();
  7540. }
  7541. logger.info('No SSRC in video recvonly stream' +
  7542. ' - adding SSRC: ' + localRecvOnlySSRC);
  7543. sdp.media[1] += 'a=ssrc:' + localRecvOnlySSRC +
  7544. ' cname:' + localRecvOnlyCName + '\r\n';
  7545. localDescription.sdp = sdp.session + sdp.media.join('');
  7546. }
  7547. return localDescription;
  7548. },
  7549. /**
  7550. * Method must be called before 'source-add' notification is sent. In case
  7551. * we have local video SSRC advertised already it will be removed from the
  7552. * notification. If no other SSRCs are described by given IQ null will be
  7553. * returned which means that there is no point in sending the notification.
  7554. * @param sourceAdd 'source-add' Jingle IQ to be processed
  7555. * @returns modified 'source-add' IQ which can be sent to the focus or
  7556. * <tt>null</tt> if no notification shall be sent. It is no longer
  7557. * a Strophe IQ Builder instance, but DOM element tree.
  7558. */
  7559. processSourceAdd: function (sourceAdd) {
  7560. if (!isEnabled)
  7561. return sourceAdd;
  7562. if (!localVideoSSRC) {
  7563. // Store local SSRC if available
  7564. storeLocalVideoSSRC(sourceAdd);
  7565. return sourceAdd;
  7566. } else {
  7567. return filterOutSource(sourceAdd, 'source-add');
  7568. }
  7569. },
  7570. /**
  7571. * Method must be called before 'source-remove' notification is sent.
  7572. * Removes local video SSRC from the notification. If there are no other
  7573. * SSRCs described in the given IQ <tt>null</tt> will be returned which
  7574. * means that there is no point in sending the notification.
  7575. * @param sourceRemove 'source-remove' Jingle IQ to be processed
  7576. * @returns modified 'source-remove' IQ which can be sent to the focus or
  7577. * <tt>null</tt> if no notification shall be sent. It is no longer
  7578. * a Strophe IQ Builder instance, but DOM element tree.
  7579. */
  7580. processSourceRemove: function (sourceRemove) {
  7581. if (!isEnabled)
  7582. return sourceRemove;
  7583. return filterOutSource(sourceRemove, 'source-remove');
  7584. },
  7585. /**
  7586. * Turns the hack on or off
  7587. * @param enabled <tt>true</tt> to enable the hack or <tt>false</tt>
  7588. * to disable it
  7589. */
  7590. setEnabled: function (enabled) {
  7591. isEnabled = enabled;
  7592. }
  7593. };
  7594. module.exports = LocalSSRCReplacement;
  7595. }).call(this,"/modules/xmpp/LocalSSRCReplacement.js")
  7596. },{"../RTC/RTCBrowserType":17,"../util/RandomUtil":25,"./SDP":30,"jitsi-meet-logger":47}],30:[function(require,module,exports){
  7597. (function (__filename){
  7598. /* jshint -W117 */
  7599. var logger = require("jitsi-meet-logger").getLogger(__filename);
  7600. var SDPUtil = require("./SDPUtil");
  7601. // SDP STUFF
  7602. function SDP(sdp) {
  7603. /**
  7604. * Whether or not to remove TCP ice candidates when translating from/to jingle.
  7605. * @type {boolean}
  7606. */
  7607. this.removeTcpCandidates = false;
  7608. /**
  7609. * Whether or not to remove UDP ice candidates when translating from/to jingle.
  7610. * @type {boolean}
  7611. */
  7612. this.removeUdpCandidates = false;
  7613. this.media = sdp.split('\r\nm=');
  7614. for (var i = 1; i < this.media.length; i++) {
  7615. this.media[i] = 'm=' + this.media[i];
  7616. if (i != this.media.length - 1) {
  7617. this.media[i] += '\r\n';
  7618. }
  7619. }
  7620. this.session = this.media.shift() + '\r\n';
  7621. this.raw = this.session + this.media.join('');
  7622. }
  7623. /**
  7624. * Returns map of MediaChannel mapped per channel idx.
  7625. */
  7626. SDP.prototype.getMediaSsrcMap = function() {
  7627. var self = this;
  7628. var media_ssrcs = {};
  7629. var tmp;
  7630. for (var mediaindex = 0; mediaindex < self.media.length; mediaindex++) {
  7631. tmp = SDPUtil.find_lines(self.media[mediaindex], 'a=ssrc:');
  7632. var mid = SDPUtil.parse_mid(SDPUtil.find_line(self.media[mediaindex], 'a=mid:'));
  7633. var media = {
  7634. mediaindex: mediaindex,
  7635. mid: mid,
  7636. ssrcs: {},
  7637. ssrcGroups: []
  7638. };
  7639. media_ssrcs[mediaindex] = media;
  7640. tmp.forEach(function (line) {
  7641. var linessrc = line.substring(7).split(' ')[0];
  7642. // allocate new ChannelSsrc
  7643. if(!media.ssrcs[linessrc]) {
  7644. media.ssrcs[linessrc] = {
  7645. ssrc: linessrc,
  7646. lines: []
  7647. };
  7648. }
  7649. media.ssrcs[linessrc].lines.push(line);
  7650. });
  7651. tmp = SDPUtil.find_lines(self.media[mediaindex], 'a=ssrc-group:');
  7652. tmp.forEach(function(line){
  7653. var idx = line.indexOf(' ');
  7654. var semantics = line.substr(0, idx).substr(13);
  7655. var ssrcs = line.substr(14 + semantics.length).split(' ');
  7656. if (ssrcs.length) {
  7657. media.ssrcGroups.push({
  7658. semantics: semantics,
  7659. ssrcs: ssrcs
  7660. });
  7661. }
  7662. });
  7663. }
  7664. return media_ssrcs;
  7665. };
  7666. /**
  7667. * Returns <tt>true</tt> if this SDP contains given SSRC.
  7668. * @param ssrc the ssrc to check.
  7669. * @returns {boolean} <tt>true</tt> if this SDP contains given SSRC.
  7670. */
  7671. SDP.prototype.containsSSRC = function (ssrc) {
  7672. // FIXME this code is really strange - improve it if you can
  7673. var medias = this.getMediaSsrcMap();
  7674. var result = false;
  7675. Object.keys(medias).forEach(function (mediaindex) {
  7676. if (result)
  7677. return;
  7678. if (medias[mediaindex].ssrcs[ssrc]) {
  7679. result = true;
  7680. }
  7681. });
  7682. return result;
  7683. };
  7684. // remove iSAC and CN from SDP
  7685. SDP.prototype.mangle = function () {
  7686. var i, j, mline, lines, rtpmap, newdesc;
  7687. for (i = 0; i < this.media.length; i++) {
  7688. lines = this.media[i].split('\r\n');
  7689. lines.pop(); // remove empty last element
  7690. mline = SDPUtil.parse_mline(lines.shift());
  7691. if (mline.media != 'audio')
  7692. continue;
  7693. newdesc = '';
  7694. mline.fmt.length = 0;
  7695. for (j = 0; j < lines.length; j++) {
  7696. if (lines[j].substr(0, 9) == 'a=rtpmap:') {
  7697. rtpmap = SDPUtil.parse_rtpmap(lines[j]);
  7698. if (rtpmap.name == 'CN' || rtpmap.name == 'ISAC')
  7699. continue;
  7700. mline.fmt.push(rtpmap.id);
  7701. newdesc += lines[j] + '\r\n';
  7702. } else {
  7703. newdesc += lines[j] + '\r\n';
  7704. }
  7705. }
  7706. this.media[i] = SDPUtil.build_mline(mline) + '\r\n';
  7707. this.media[i] += newdesc;
  7708. }
  7709. this.raw = this.session + this.media.join('');
  7710. };
  7711. // remove lines matching prefix from session section
  7712. SDP.prototype.removeSessionLines = function(prefix) {
  7713. var self = this;
  7714. var lines = SDPUtil.find_lines(this.session, prefix);
  7715. lines.forEach(function(line) {
  7716. self.session = self.session.replace(line + '\r\n', '');
  7717. });
  7718. this.raw = this.session + this.media.join('');
  7719. return lines;
  7720. }
  7721. // remove lines matching prefix from a media section specified by mediaindex
  7722. // TODO: non-numeric mediaindex could match mid
  7723. SDP.prototype.removeMediaLines = function(mediaindex, prefix) {
  7724. var self = this;
  7725. var lines = SDPUtil.find_lines(this.media[mediaindex], prefix);
  7726. lines.forEach(function(line) {
  7727. self.media[mediaindex] = self.media[mediaindex].replace(line + '\r\n', '');
  7728. });
  7729. this.raw = this.session + this.media.join('');
  7730. return lines;
  7731. }
  7732. // add content's to a jingle element
  7733. SDP.prototype.toJingle = function (elem, thecreator) {
  7734. // logger.log("SSRC" + ssrcs["audio"] + " - " + ssrcs["video"]);
  7735. var self = this;
  7736. var i, j, k, mline, ssrc, rtpmap, tmp, lines;
  7737. // new bundle plan
  7738. if (SDPUtil.find_line(this.session, 'a=group:')) {
  7739. lines = SDPUtil.find_lines(this.session, 'a=group:');
  7740. for (i = 0; i < lines.length; i++) {
  7741. tmp = lines[i].split(' ');
  7742. var semantics = tmp.shift().substr(8);
  7743. elem.c('group', {xmlns: 'urn:xmpp:jingle:apps:grouping:0', semantics:semantics});
  7744. for (j = 0; j < tmp.length; j++) {
  7745. elem.c('content', {name: tmp[j]}).up();
  7746. }
  7747. elem.up();
  7748. }
  7749. }
  7750. for (i = 0; i < this.media.length; i++) {
  7751. mline = SDPUtil.parse_mline(this.media[i].split('\r\n')[0]);
  7752. if (!(mline.media === 'audio' ||
  7753. mline.media === 'video' ||
  7754. mline.media === 'application'))
  7755. {
  7756. continue;
  7757. }
  7758. if (SDPUtil.find_line(this.media[i], 'a=ssrc:')) {
  7759. ssrc = SDPUtil.find_line(this.media[i], 'a=ssrc:').substring(7).split(' ')[0]; // take the first
  7760. } else {
  7761. ssrc = false;
  7762. }
  7763. elem.c('content', {creator: thecreator, name: mline.media});
  7764. if (SDPUtil.find_line(this.media[i], 'a=mid:')) {
  7765. // prefer identifier from a=mid if present
  7766. var mid = SDPUtil.parse_mid(SDPUtil.find_line(this.media[i], 'a=mid:'));
  7767. elem.attrs({ name: mid });
  7768. }
  7769. if (SDPUtil.find_line(this.media[i], 'a=rtpmap:').length) {
  7770. elem.c('description',
  7771. {xmlns: 'urn:xmpp:jingle:apps:rtp:1',
  7772. media: mline.media });
  7773. if (ssrc) {
  7774. elem.attrs({ssrc: ssrc});
  7775. }
  7776. for (j = 0; j < mline.fmt.length; j++) {
  7777. rtpmap = SDPUtil.find_line(this.media[i], 'a=rtpmap:' + mline.fmt[j]);
  7778. elem.c('payload-type', SDPUtil.parse_rtpmap(rtpmap));
  7779. // put any 'a=fmtp:' + mline.fmt[j] lines into <param name=foo value=bar/>
  7780. if (SDPUtil.find_line(this.media[i], 'a=fmtp:' + mline.fmt[j])) {
  7781. tmp = SDPUtil.parse_fmtp(SDPUtil.find_line(this.media[i], 'a=fmtp:' + mline.fmt[j]));
  7782. for (k = 0; k < tmp.length; k++) {
  7783. elem.c('parameter', tmp[k]).up();
  7784. }
  7785. }
  7786. this.rtcpFbToJingle(i, elem, mline.fmt[j]); // XEP-0293 -- map a=rtcp-fb
  7787. elem.up();
  7788. }
  7789. if (SDPUtil.find_line(this.media[i], 'a=crypto:', this.session)) {
  7790. elem.c('encryption', {required: 1});
  7791. var crypto = SDPUtil.find_lines(this.media[i], 'a=crypto:', this.session);
  7792. crypto.forEach(function(line) {
  7793. elem.c('crypto', SDPUtil.parse_crypto(line)).up();
  7794. });
  7795. elem.up(); // end of encryption
  7796. }
  7797. if (ssrc) {
  7798. // new style mapping
  7799. elem.c('source', { ssrc: ssrc, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  7800. // FIXME: group by ssrc and support multiple different ssrcs
  7801. var ssrclines = SDPUtil.find_lines(this.media[i], 'a=ssrc:');
  7802. if(ssrclines.length > 0) {
  7803. ssrclines.forEach(function (line) {
  7804. var idx = line.indexOf(' ');
  7805. var linessrc = line.substr(0, idx).substr(7);
  7806. if (linessrc != ssrc) {
  7807. elem.up();
  7808. ssrc = linessrc;
  7809. elem.c('source', { ssrc: ssrc, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  7810. }
  7811. var kv = line.substr(idx + 1);
  7812. elem.c('parameter');
  7813. if (kv.indexOf(':') == -1) {
  7814. elem.attrs({ name: kv });
  7815. } else {
  7816. var k = kv.split(':', 2)[0];
  7817. elem.attrs({ name: k });
  7818. var v = kv.split(':', 2)[1];
  7819. v = SDPUtil.filter_special_chars(v);
  7820. elem.attrs({ value: v });
  7821. }
  7822. elem.up();
  7823. });
  7824. } else {
  7825. elem.up();
  7826. elem.c('source', { ssrc: ssrc, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  7827. elem.c('parameter');
  7828. elem.attrs({name: "cname", value:Math.random().toString(36).substring(7)});
  7829. elem.up();
  7830. var msid = null;
  7831. if(mline.media == "audio")
  7832. {
  7833. msid = APP.RTC.localAudio.getId();
  7834. }
  7835. else
  7836. {
  7837. msid = APP.RTC.localVideo.getId();
  7838. }
  7839. if(msid != null)
  7840. {
  7841. msid = SDPUtil.filter_special_chars(msid);
  7842. elem.c('parameter');
  7843. elem.attrs({name: "msid", value:msid});
  7844. elem.up();
  7845. elem.c('parameter');
  7846. elem.attrs({name: "mslabel", value:msid});
  7847. elem.up();
  7848. elem.c('parameter');
  7849. elem.attrs({name: "label", value:msid});
  7850. elem.up();
  7851. }
  7852. }
  7853. elem.up();
  7854. // XEP-0339 handle ssrc-group attributes
  7855. var ssrc_group_lines = SDPUtil.find_lines(this.media[i], 'a=ssrc-group:');
  7856. ssrc_group_lines.forEach(function(line) {
  7857. var idx = line.indexOf(' ');
  7858. var semantics = line.substr(0, idx).substr(13);
  7859. var ssrcs = line.substr(14 + semantics.length).split(' ');
  7860. if (ssrcs.length) {
  7861. elem.c('ssrc-group', { semantics: semantics, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  7862. ssrcs.forEach(function(ssrc) {
  7863. elem.c('source', { ssrc: ssrc })
  7864. .up();
  7865. });
  7866. elem.up();
  7867. }
  7868. });
  7869. }
  7870. if (SDPUtil.find_line(this.media[i], 'a=rtcp-mux')) {
  7871. elem.c('rtcp-mux').up();
  7872. }
  7873. // XEP-0293 -- map a=rtcp-fb:*
  7874. this.rtcpFbToJingle(i, elem, '*');
  7875. // XEP-0294
  7876. if (SDPUtil.find_line(this.media[i], 'a=extmap:')) {
  7877. lines = SDPUtil.find_lines(this.media[i], 'a=extmap:');
  7878. for (j = 0; j < lines.length; j++) {
  7879. tmp = SDPUtil.parse_extmap(lines[j]);
  7880. elem.c('rtp-hdrext', { xmlns: 'urn:xmpp:jingle:apps:rtp:rtp-hdrext:0',
  7881. uri: tmp.uri,
  7882. id: tmp.value });
  7883. if (tmp.hasOwnProperty('direction')) {
  7884. switch (tmp.direction) {
  7885. case 'sendonly':
  7886. elem.attrs({senders: 'responder'});
  7887. break;
  7888. case 'recvonly':
  7889. elem.attrs({senders: 'initiator'});
  7890. break;
  7891. case 'sendrecv':
  7892. elem.attrs({senders: 'both'});
  7893. break;
  7894. case 'inactive':
  7895. elem.attrs({senders: 'none'});
  7896. break;
  7897. }
  7898. }
  7899. // TODO: handle params
  7900. elem.up();
  7901. }
  7902. }
  7903. elem.up(); // end of description
  7904. }
  7905. // map ice-ufrag/pwd, dtls fingerprint, candidates
  7906. this.transportToJingle(i, elem);
  7907. if (SDPUtil.find_line(this.media[i], 'a=sendrecv', this.session)) {
  7908. elem.attrs({senders: 'both'});
  7909. } else if (SDPUtil.find_line(this.media[i], 'a=sendonly', this.session)) {
  7910. elem.attrs({senders: 'initiator'});
  7911. } else if (SDPUtil.find_line(this.media[i], 'a=recvonly', this.session)) {
  7912. elem.attrs({senders: 'responder'});
  7913. } else if (SDPUtil.find_line(this.media[i], 'a=inactive', this.session)) {
  7914. elem.attrs({senders: 'none'});
  7915. }
  7916. if (mline.port == '0') {
  7917. // estos hack to reject an m-line
  7918. elem.attrs({senders: 'rejected'});
  7919. }
  7920. elem.up(); // end of content
  7921. }
  7922. elem.up();
  7923. return elem;
  7924. };
  7925. SDP.prototype.transportToJingle = function (mediaindex, elem) {
  7926. var tmp, sctpmap, sctpAttrs, fingerprints;
  7927. var self = this;
  7928. elem.c('transport');
  7929. // XEP-0343 DTLS/SCTP
  7930. if (SDPUtil.find_line(this.media[mediaindex], 'a=sctpmap:').length)
  7931. {
  7932. sctpmap = SDPUtil.find_line(
  7933. this.media[mediaindex], 'a=sctpmap:', self.session);
  7934. if (sctpmap)
  7935. {
  7936. sctpAttrs = SDPUtil.parse_sctpmap(sctpmap);
  7937. elem.c('sctpmap',
  7938. {
  7939. xmlns: 'urn:xmpp:jingle:transports:dtls-sctp:1',
  7940. number: sctpAttrs[0], /* SCTP port */
  7941. protocol: sctpAttrs[1] /* protocol */
  7942. });
  7943. // Optional stream count attribute
  7944. if (sctpAttrs.length > 2)
  7945. elem.attrs({ streams: sctpAttrs[2]});
  7946. elem.up();
  7947. }
  7948. }
  7949. // XEP-0320
  7950. fingerprints = SDPUtil.find_lines(this.media[mediaindex], 'a=fingerprint:', this.session);
  7951. fingerprints.forEach(function(line) {
  7952. tmp = SDPUtil.parse_fingerprint(line);
  7953. tmp.xmlns = 'urn:xmpp:jingle:apps:dtls:0';
  7954. elem.c('fingerprint').t(tmp.fingerprint);
  7955. delete tmp.fingerprint;
  7956. line = SDPUtil.find_line(self.media[mediaindex], 'a=setup:', self.session);
  7957. if (line) {
  7958. tmp.setup = line.substr(8);
  7959. }
  7960. elem.attrs(tmp);
  7961. elem.up(); // end of fingerprint
  7962. });
  7963. tmp = SDPUtil.iceparams(this.media[mediaindex], this.session);
  7964. if (tmp) {
  7965. tmp.xmlns = 'urn:xmpp:jingle:transports:ice-udp:1';
  7966. elem.attrs(tmp);
  7967. // XEP-0176
  7968. if (SDPUtil.find_line(this.media[mediaindex], 'a=candidate:', this.session)) { // add any a=candidate lines
  7969. var lines = SDPUtil.find_lines(this.media[mediaindex], 'a=candidate:', this.session);
  7970. lines.forEach(function (line) {
  7971. var candidate = SDPUtil.candidateToJingle(line);
  7972. var protocol = (candidate &&
  7973. typeof candidate.protocol === 'string')
  7974. ? candidate.protocol.toLowerCase() : '';
  7975. if ((self.removeTcpCandidates && protocol === 'tcp') ||
  7976. (self.removeUdpCandidates && protocol === 'udp')) {
  7977. return;
  7978. }
  7979. elem.c('candidate', candidate).up();
  7980. });
  7981. }
  7982. }
  7983. elem.up(); // end of transport
  7984. }
  7985. SDP.prototype.rtcpFbToJingle = function (mediaindex, elem, payloadtype) { // XEP-0293
  7986. var lines = SDPUtil.find_lines(this.media[mediaindex], 'a=rtcp-fb:' + payloadtype);
  7987. lines.forEach(function (line) {
  7988. var tmp = SDPUtil.parse_rtcpfb(line);
  7989. if (tmp.type == 'trr-int') {
  7990. elem.c('rtcp-fb-trr-int', {xmlns: 'urn:xmpp:jingle:apps:rtp:rtcp-fb:0', value: tmp.params[0]});
  7991. elem.up();
  7992. } else {
  7993. elem.c('rtcp-fb', {xmlns: 'urn:xmpp:jingle:apps:rtp:rtcp-fb:0', type: tmp.type});
  7994. if (tmp.params.length > 0) {
  7995. elem.attrs({'subtype': tmp.params[0]});
  7996. }
  7997. elem.up();
  7998. }
  7999. });
  8000. };
  8001. SDP.prototype.rtcpFbFromJingle = function (elem, payloadtype) { // XEP-0293
  8002. var media = '';
  8003. var tmp = elem.find('>rtcp-fb-trr-int[xmlns="urn:xmpp:jingle:apps:rtp:rtcp-fb:0"]');
  8004. if (tmp.length) {
  8005. media += 'a=rtcp-fb:' + '*' + ' ' + 'trr-int' + ' ';
  8006. if (tmp.attr('value')) {
  8007. media += tmp.attr('value');
  8008. } else {
  8009. media += '0';
  8010. }
  8011. media += '\r\n';
  8012. }
  8013. tmp = elem.find('>rtcp-fb[xmlns="urn:xmpp:jingle:apps:rtp:rtcp-fb:0"]');
  8014. tmp.each(function () {
  8015. media += 'a=rtcp-fb:' + payloadtype + ' ' + $(this).attr('type');
  8016. if ($(this).attr('subtype')) {
  8017. media += ' ' + $(this).attr('subtype');
  8018. }
  8019. media += '\r\n';
  8020. });
  8021. return media;
  8022. };
  8023. // construct an SDP from a jingle stanza
  8024. SDP.prototype.fromJingle = function (jingle) {
  8025. var self = this;
  8026. this.raw = 'v=0\r\n' +
  8027. 'o=- 1923518516 2 IN IP4 0.0.0.0\r\n' +// FIXME
  8028. 's=-\r\n' +
  8029. 't=0 0\r\n';
  8030. // http://tools.ietf.org/html/draft-ietf-mmusic-sdp-bundle-negotiation-04#section-8
  8031. if ($(jingle).find('>group[xmlns="urn:xmpp:jingle:apps:grouping:0"]').length) {
  8032. $(jingle).find('>group[xmlns="urn:xmpp:jingle:apps:grouping:0"]').each(function (idx, group) {
  8033. var contents = $(group).find('>content').map(function (idx, content) {
  8034. return content.getAttribute('name');
  8035. }).get();
  8036. if (contents.length > 0) {
  8037. self.raw += 'a=group:' + (group.getAttribute('semantics') || group.getAttribute('type')) + ' ' + contents.join(' ') + '\r\n';
  8038. }
  8039. });
  8040. }
  8041. this.session = this.raw;
  8042. jingle.find('>content').each(function () {
  8043. var m = self.jingle2media($(this));
  8044. self.media.push(m);
  8045. });
  8046. // reconstruct msid-semantic -- apparently not necessary
  8047. /*
  8048. var msid = SDPUtil.parse_ssrc(this.raw);
  8049. if (msid.hasOwnProperty('mslabel')) {
  8050. this.session += "a=msid-semantic: WMS " + msid.mslabel + "\r\n";
  8051. }
  8052. */
  8053. this.raw = this.session + this.media.join('');
  8054. };
  8055. // translate a jingle content element into an an SDP media part
  8056. SDP.prototype.jingle2media = function (content) {
  8057. var media = '',
  8058. desc = content.find('description'),
  8059. ssrc = desc.attr('ssrc'),
  8060. self = this,
  8061. tmp;
  8062. var sctp = content.find(
  8063. '>transport>sctpmap[xmlns="urn:xmpp:jingle:transports:dtls-sctp:1"]');
  8064. tmp = { media: desc.attr('media') };
  8065. tmp.port = '1';
  8066. if (content.attr('senders') == 'rejected') {
  8067. // estos hack to reject an m-line.
  8068. tmp.port = '0';
  8069. }
  8070. if (content.find('>transport>fingerprint').length || desc.find('encryption').length) {
  8071. if (sctp.length)
  8072. tmp.proto = 'DTLS/SCTP';
  8073. else
  8074. tmp.proto = 'RTP/SAVPF';
  8075. } else {
  8076. tmp.proto = 'RTP/AVPF';
  8077. }
  8078. if (!sctp.length) {
  8079. tmp.fmt = desc.find('payload-type').map(
  8080. function () { return this.getAttribute('id'); }).get();
  8081. media += SDPUtil.build_mline(tmp) + '\r\n';
  8082. } else {
  8083. media += 'm=application 1 DTLS/SCTP ' + sctp.attr('number') + '\r\n';
  8084. media += 'a=sctpmap:' + sctp.attr('number') +
  8085. ' ' + sctp.attr('protocol');
  8086. var streamCount = sctp.attr('streams');
  8087. if (streamCount)
  8088. media += ' ' + streamCount + '\r\n';
  8089. else
  8090. media += '\r\n';
  8091. }
  8092. media += 'c=IN IP4 0.0.0.0\r\n';
  8093. if (!sctp.length)
  8094. media += 'a=rtcp:1 IN IP4 0.0.0.0\r\n';
  8095. tmp = content.find('>transport[xmlns="urn:xmpp:jingle:transports:ice-udp:1"]');
  8096. if (tmp.length) {
  8097. if (tmp.attr('ufrag')) {
  8098. media += SDPUtil.build_iceufrag(tmp.attr('ufrag')) + '\r\n';
  8099. }
  8100. if (tmp.attr('pwd')) {
  8101. media += SDPUtil.build_icepwd(tmp.attr('pwd')) + '\r\n';
  8102. }
  8103. tmp.find('>fingerprint').each(function () {
  8104. // FIXME: check namespace at some point
  8105. media += 'a=fingerprint:' + this.getAttribute('hash');
  8106. media += ' ' + $(this).text();
  8107. media += '\r\n';
  8108. if (this.getAttribute('setup')) {
  8109. media += 'a=setup:' + this.getAttribute('setup') + '\r\n';
  8110. }
  8111. });
  8112. }
  8113. switch (content.attr('senders')) {
  8114. case 'initiator':
  8115. media += 'a=sendonly\r\n';
  8116. break;
  8117. case 'responder':
  8118. media += 'a=recvonly\r\n';
  8119. break;
  8120. case 'none':
  8121. media += 'a=inactive\r\n';
  8122. break;
  8123. case 'both':
  8124. media += 'a=sendrecv\r\n';
  8125. break;
  8126. }
  8127. media += 'a=mid:' + content.attr('name') + '\r\n';
  8128. // <description><rtcp-mux/></description>
  8129. // see http://code.google.com/p/libjingle/issues/detail?id=309 -- no spec though
  8130. // and http://mail.jabber.org/pipermail/jingle/2011-December/001761.html
  8131. if (desc.find('rtcp-mux').length) {
  8132. media += 'a=rtcp-mux\r\n';
  8133. }
  8134. if (desc.find('encryption').length) {
  8135. desc.find('encryption>crypto').each(function () {
  8136. media += 'a=crypto:' + this.getAttribute('tag');
  8137. media += ' ' + this.getAttribute('crypto-suite');
  8138. media += ' ' + this.getAttribute('key-params');
  8139. if (this.getAttribute('session-params')) {
  8140. media += ' ' + this.getAttribute('session-params');
  8141. }
  8142. media += '\r\n';
  8143. });
  8144. }
  8145. desc.find('payload-type').each(function () {
  8146. media += SDPUtil.build_rtpmap(this) + '\r\n';
  8147. if ($(this).find('>parameter').length) {
  8148. media += 'a=fmtp:' + this.getAttribute('id') + ' ';
  8149. media += $(this).find('parameter').map(function () {
  8150. return (this.getAttribute('name')
  8151. ? (this.getAttribute('name') + '=') : '') +
  8152. this.getAttribute('value');
  8153. }).get().join('; ');
  8154. media += '\r\n';
  8155. }
  8156. // xep-0293
  8157. media += self.rtcpFbFromJingle($(this), this.getAttribute('id'));
  8158. });
  8159. // xep-0293
  8160. media += self.rtcpFbFromJingle(desc, '*');
  8161. // xep-0294
  8162. tmp = desc.find('>rtp-hdrext[xmlns="urn:xmpp:jingle:apps:rtp:rtp-hdrext:0"]');
  8163. tmp.each(function () {
  8164. media += 'a=extmap:' + this.getAttribute('id') + ' ' + this.getAttribute('uri') + '\r\n';
  8165. });
  8166. content.find('>transport[xmlns="urn:xmpp:jingle:transports:ice-udp:1"]>candidate').each(function () {
  8167. var protocol = this.getAttribute('protocol');
  8168. protocol = (typeof protocol === 'string') ? protocol.toLowerCase(): '';
  8169. if ((self.removeTcpCandidates && protocol === 'tcp') ||
  8170. (self.removeUdpCandidates && protocol === 'udp')) {
  8171. return;
  8172. }
  8173. media += SDPUtil.candidateFromJingle(this);
  8174. });
  8175. // XEP-0339 handle ssrc-group attributes
  8176. content.find('description>ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]').each(function() {
  8177. var semantics = this.getAttribute('semantics');
  8178. var ssrcs = $(this).find('>source').map(function() {
  8179. return this.getAttribute('ssrc');
  8180. }).get();
  8181. if (ssrcs.length) {
  8182. media += 'a=ssrc-group:' + semantics + ' ' + ssrcs.join(' ') + '\r\n';
  8183. }
  8184. });
  8185. tmp = content.find('description>source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]');
  8186. tmp.each(function () {
  8187. var ssrc = this.getAttribute('ssrc');
  8188. $(this).find('>parameter').each(function () {
  8189. var name = this.getAttribute('name');
  8190. var value = this.getAttribute('value');
  8191. value = SDPUtil.filter_special_chars(value);
  8192. media += 'a=ssrc:' + ssrc + ' ' + name;
  8193. if (value && value.length)
  8194. media += ':' + value;
  8195. media += '\r\n';
  8196. });
  8197. });
  8198. return media;
  8199. };
  8200. module.exports = SDP;
  8201. }).call(this,"/modules/xmpp/SDP.js")
  8202. },{"./SDPUtil":32,"jitsi-meet-logger":47}],31:[function(require,module,exports){
  8203. var SDPUtil = require("./SDPUtil");
  8204. function SDPDiffer(mySDP, otherSDP)
  8205. {
  8206. this.mySDP = mySDP;
  8207. this.otherSDP = otherSDP;
  8208. }
  8209. /**
  8210. * Returns map of MediaChannel that contains media contained in
  8211. * 'mySDP', but not contained in 'otherSdp'. Mapped by channel idx.
  8212. */
  8213. SDPDiffer.prototype.getNewMedia = function() {
  8214. // this could be useful in Array.prototype.
  8215. function arrayEquals(array) {
  8216. // if the other array is a falsy value, return
  8217. if (!array)
  8218. return false;
  8219. // compare lengths - can save a lot of time
  8220. if (this.length != array.length)
  8221. return false;
  8222. for (var i = 0, l=this.length; i < l; i++) {
  8223. // Check if we have nested arrays
  8224. if (this[i] instanceof Array && array[i] instanceof Array) {
  8225. // recurse into the nested arrays
  8226. if (!this[i].equals(array[i]))
  8227. return false;
  8228. }
  8229. else if (this[i] != array[i]) {
  8230. // Warning - two different object instances will never be
  8231. // equal: {x:20} != {x:20}
  8232. return false;
  8233. }
  8234. }
  8235. return true;
  8236. }
  8237. var myMedias = this.mySDP.getMediaSsrcMap();
  8238. var othersMedias = this.otherSDP.getMediaSsrcMap();
  8239. var newMedia = {};
  8240. Object.keys(othersMedias).forEach(function(othersMediaIdx) {
  8241. var myMedia = myMedias[othersMediaIdx];
  8242. var othersMedia = othersMedias[othersMediaIdx];
  8243. if(!myMedia && othersMedia) {
  8244. // Add whole channel
  8245. newMedia[othersMediaIdx] = othersMedia;
  8246. return;
  8247. }
  8248. // Look for new ssrcs across the channel
  8249. Object.keys(othersMedia.ssrcs).forEach(function(ssrc) {
  8250. if(Object.keys(myMedia.ssrcs).indexOf(ssrc) === -1) {
  8251. // Allocate channel if we've found ssrc that doesn't exist in
  8252. // our channel
  8253. if(!newMedia[othersMediaIdx]){
  8254. newMedia[othersMediaIdx] = {
  8255. mediaindex: othersMedia.mediaindex,
  8256. mid: othersMedia.mid,
  8257. ssrcs: {},
  8258. ssrcGroups: []
  8259. };
  8260. }
  8261. newMedia[othersMediaIdx].ssrcs[ssrc] = othersMedia.ssrcs[ssrc];
  8262. }
  8263. });
  8264. // Look for new ssrc groups across the channels
  8265. othersMedia.ssrcGroups.forEach(function(otherSsrcGroup){
  8266. // try to match the other ssrc-group with an ssrc-group of ours
  8267. var matched = false;
  8268. for (var i = 0; i < myMedia.ssrcGroups.length; i++) {
  8269. var mySsrcGroup = myMedia.ssrcGroups[i];
  8270. if (otherSsrcGroup.semantics == mySsrcGroup.semantics &&
  8271. arrayEquals.apply(otherSsrcGroup.ssrcs,
  8272. [mySsrcGroup.ssrcs])) {
  8273. matched = true;
  8274. break;
  8275. }
  8276. }
  8277. if (!matched) {
  8278. // Allocate channel if we've found an ssrc-group that doesn't
  8279. // exist in our channel
  8280. if(!newMedia[othersMediaIdx]){
  8281. newMedia[othersMediaIdx] = {
  8282. mediaindex: othersMedia.mediaindex,
  8283. mid: othersMedia.mid,
  8284. ssrcs: {},
  8285. ssrcGroups: []
  8286. };
  8287. }
  8288. newMedia[othersMediaIdx].ssrcGroups.push(otherSsrcGroup);
  8289. }
  8290. });
  8291. });
  8292. return newMedia;
  8293. };
  8294. /**
  8295. * TODO: document!
  8296. */
  8297. SDPDiffer.prototype.toJingle = function(modify) {
  8298. var sdpMediaSsrcs = this.getNewMedia();
  8299. var modified = false;
  8300. Object.keys(sdpMediaSsrcs).forEach(function(mediaindex){
  8301. modified = true;
  8302. var media = sdpMediaSsrcs[mediaindex];
  8303. modify.c('content', {name: media.mid});
  8304. modify.c('description',
  8305. {xmlns:'urn:xmpp:jingle:apps:rtp:1', media: media.mid});
  8306. // FIXME: not completely sure this operates on blocks and / or handles
  8307. // different ssrcs correctly
  8308. // generate sources from lines
  8309. Object.keys(media.ssrcs).forEach(function(ssrcNum) {
  8310. var mediaSsrc = media.ssrcs[ssrcNum];
  8311. modify.c('source', { xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  8312. modify.attrs({ssrc: mediaSsrc.ssrc});
  8313. // iterate over ssrc lines
  8314. mediaSsrc.lines.forEach(function (line) {
  8315. var idx = line.indexOf(' ');
  8316. var kv = line.substr(idx + 1);
  8317. modify.c('parameter');
  8318. if (kv.indexOf(':') == -1) {
  8319. modify.attrs({ name: kv });
  8320. } else {
  8321. var nv = kv.split(':', 2);
  8322. var name = nv[0];
  8323. var value = SDPUtil.filter_special_chars(nv[1]);
  8324. modify.attrs({ name: name });
  8325. modify.attrs({ value: value });
  8326. }
  8327. modify.up(); // end of parameter
  8328. });
  8329. modify.up(); // end of source
  8330. });
  8331. // generate source groups from lines
  8332. media.ssrcGroups.forEach(function(ssrcGroup) {
  8333. if (ssrcGroup.ssrcs.length) {
  8334. modify.c('ssrc-group', {
  8335. semantics: ssrcGroup.semantics,
  8336. xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0'
  8337. });
  8338. ssrcGroup.ssrcs.forEach(function (ssrc) {
  8339. modify.c('source', { ssrc: ssrc })
  8340. .up(); // end of source
  8341. });
  8342. modify.up(); // end of ssrc-group
  8343. }
  8344. });
  8345. modify.up(); // end of description
  8346. modify.up(); // end of content
  8347. });
  8348. return modified;
  8349. };
  8350. module.exports = SDPDiffer;
  8351. },{"./SDPUtil":32}],32:[function(require,module,exports){
  8352. (function (__filename){
  8353. var logger = require("jitsi-meet-logger").getLogger(__filename);
  8354. var RTCBrowserType = require("../RTC/RTCBrowserType");
  8355. SDPUtil = {
  8356. filter_special_chars: function (text) {
  8357. return text.replace(/[\\\/\{,\}\+]/g, "");
  8358. },
  8359. iceparams: function (mediadesc, sessiondesc) {
  8360. var data = null;
  8361. if (SDPUtil.find_line(mediadesc, 'a=ice-ufrag:', sessiondesc) &&
  8362. SDPUtil.find_line(mediadesc, 'a=ice-pwd:', sessiondesc)) {
  8363. data = {
  8364. ufrag: SDPUtil.parse_iceufrag(SDPUtil.find_line(mediadesc, 'a=ice-ufrag:', sessiondesc)),
  8365. pwd: SDPUtil.parse_icepwd(SDPUtil.find_line(mediadesc, 'a=ice-pwd:', sessiondesc))
  8366. };
  8367. }
  8368. return data;
  8369. },
  8370. parse_iceufrag: function (line) {
  8371. return line.substring(12);
  8372. },
  8373. build_iceufrag: function (frag) {
  8374. return 'a=ice-ufrag:' + frag;
  8375. },
  8376. parse_icepwd: function (line) {
  8377. return line.substring(10);
  8378. },
  8379. build_icepwd: function (pwd) {
  8380. return 'a=ice-pwd:' + pwd;
  8381. },
  8382. parse_mid: function (line) {
  8383. return line.substring(6);
  8384. },
  8385. parse_mline: function (line) {
  8386. var parts = line.substring(2).split(' '),
  8387. data = {};
  8388. data.media = parts.shift();
  8389. data.port = parts.shift();
  8390. data.proto = parts.shift();
  8391. if (parts[parts.length - 1] === '') { // trailing whitespace
  8392. parts.pop();
  8393. }
  8394. data.fmt = parts;
  8395. return data;
  8396. },
  8397. build_mline: function (mline) {
  8398. return 'm=' + mline.media + ' ' + mline.port + ' ' + mline.proto + ' ' + mline.fmt.join(' ');
  8399. },
  8400. parse_rtpmap: function (line) {
  8401. var parts = line.substring(9).split(' '),
  8402. data = {};
  8403. data.id = parts.shift();
  8404. parts = parts[0].split('/');
  8405. data.name = parts.shift();
  8406. data.clockrate = parts.shift();
  8407. data.channels = parts.length ? parts.shift() : '1';
  8408. return data;
  8409. },
  8410. /**
  8411. * Parses SDP line "a=sctpmap:..." and extracts SCTP port from it.
  8412. * @param line eg. "a=sctpmap:5000 webrtc-datachannel"
  8413. * @returns [SCTP port number, protocol, streams]
  8414. */
  8415. parse_sctpmap: function (line)
  8416. {
  8417. var parts = line.substring(10).split(' ');
  8418. var sctpPort = parts[0];
  8419. var protocol = parts[1];
  8420. // Stream count is optional
  8421. var streamCount = parts.length > 2 ? parts[2] : null;
  8422. return [sctpPort, protocol, streamCount];// SCTP port
  8423. },
  8424. build_rtpmap: function (el) {
  8425. var line = 'a=rtpmap:' + el.getAttribute('id') + ' ' + el.getAttribute('name') + '/' + el.getAttribute('clockrate');
  8426. if (el.getAttribute('channels') && el.getAttribute('channels') != '1') {
  8427. line += '/' + el.getAttribute('channels');
  8428. }
  8429. return line;
  8430. },
  8431. parse_crypto: function (line) {
  8432. var parts = line.substring(9).split(' '),
  8433. data = {};
  8434. data.tag = parts.shift();
  8435. data['crypto-suite'] = parts.shift();
  8436. data['key-params'] = parts.shift();
  8437. if (parts.length) {
  8438. data['session-params'] = parts.join(' ');
  8439. }
  8440. return data;
  8441. },
  8442. parse_fingerprint: function (line) { // RFC 4572
  8443. var parts = line.substring(14).split(' '),
  8444. data = {};
  8445. data.hash = parts.shift();
  8446. data.fingerprint = parts.shift();
  8447. // TODO assert that fingerprint satisfies 2UHEX *(":" 2UHEX) ?
  8448. return data;
  8449. },
  8450. parse_fmtp: function (line) {
  8451. var parts = line.split(' '),
  8452. i, key, value,
  8453. data = [];
  8454. parts.shift();
  8455. parts = parts.join(' ').split(';');
  8456. for (i = 0; i < parts.length; i++) {
  8457. key = parts[i].split('=')[0];
  8458. while (key.length && key[0] == ' ') {
  8459. key = key.substring(1);
  8460. }
  8461. value = parts[i].split('=')[1];
  8462. if (key && value) {
  8463. data.push({name: key, value: value});
  8464. } else if (key) {
  8465. // rfc 4733 (DTMF) style stuff
  8466. data.push({name: '', value: key});
  8467. }
  8468. }
  8469. return data;
  8470. },
  8471. parse_icecandidate: function (line) {
  8472. var candidate = {},
  8473. elems = line.split(' ');
  8474. candidate.foundation = elems[0].substring(12);
  8475. candidate.component = elems[1];
  8476. candidate.protocol = elems[2].toLowerCase();
  8477. candidate.priority = elems[3];
  8478. candidate.ip = elems[4];
  8479. candidate.port = elems[5];
  8480. // elems[6] => "typ"
  8481. candidate.type = elems[7];
  8482. candidate.generation = 0; // default value, may be overwritten below
  8483. for (var i = 8; i < elems.length; i += 2) {
  8484. switch (elems[i]) {
  8485. case 'raddr':
  8486. candidate['rel-addr'] = elems[i + 1];
  8487. break;
  8488. case 'rport':
  8489. candidate['rel-port'] = elems[i + 1];
  8490. break;
  8491. case 'generation':
  8492. candidate.generation = elems[i + 1];
  8493. break;
  8494. case 'tcptype':
  8495. candidate.tcptype = elems[i + 1];
  8496. break;
  8497. default: // TODO
  8498. logger.log('parse_icecandidate not translating "' + elems[i] + '" = "' + elems[i + 1] + '"');
  8499. }
  8500. }
  8501. candidate.network = '1';
  8502. candidate.id = Math.random().toString(36).substr(2, 10); // not applicable to SDP -- FIXME: should be unique, not just random
  8503. return candidate;
  8504. },
  8505. build_icecandidate: function (cand) {
  8506. var line = ['a=candidate:' + cand.foundation, cand.component, cand.protocol, cand.priority, cand.ip, cand.port, 'typ', cand.type].join(' ');
  8507. line += ' ';
  8508. switch (cand.type) {
  8509. case 'srflx':
  8510. case 'prflx':
  8511. case 'relay':
  8512. if (cand.hasOwnAttribute('rel-addr') && cand.hasOwnAttribute('rel-port')) {
  8513. line += 'raddr';
  8514. line += ' ';
  8515. line += cand['rel-addr'];
  8516. line += ' ';
  8517. line += 'rport';
  8518. line += ' ';
  8519. line += cand['rel-port'];
  8520. line += ' ';
  8521. }
  8522. break;
  8523. }
  8524. if (cand.hasOwnAttribute('tcptype')) {
  8525. line += 'tcptype';
  8526. line += ' ';
  8527. line += cand.tcptype;
  8528. line += ' ';
  8529. }
  8530. line += 'generation';
  8531. line += ' ';
  8532. line += cand.hasOwnAttribute('generation') ? cand.generation : '0';
  8533. return line;
  8534. },
  8535. parse_ssrc: function (desc) {
  8536. // proprietary mapping of a=ssrc lines
  8537. // TODO: see "Jingle RTP Source Description" by Juberti and P. Thatcher on google docs
  8538. // and parse according to that
  8539. var lines = desc.split('\r\n'),
  8540. data = {};
  8541. for (var i = 0; i < lines.length; i++) {
  8542. if (lines[i].substring(0, 7) == 'a=ssrc:') {
  8543. var idx = lines[i].indexOf(' ');
  8544. data[lines[i].substr(idx + 1).split(':', 2)[0]] = lines[i].substr(idx + 1).split(':', 2)[1];
  8545. }
  8546. }
  8547. return data;
  8548. },
  8549. parse_rtcpfb: function (line) {
  8550. var parts = line.substr(10).split(' ');
  8551. var data = {};
  8552. data.pt = parts.shift();
  8553. data.type = parts.shift();
  8554. data.params = parts;
  8555. return data;
  8556. },
  8557. parse_extmap: function (line) {
  8558. var parts = line.substr(9).split(' ');
  8559. var data = {};
  8560. data.value = parts.shift();
  8561. if (data.value.indexOf('/') != -1) {
  8562. data.direction = data.value.substr(data.value.indexOf('/') + 1);
  8563. data.value = data.value.substr(0, data.value.indexOf('/'));
  8564. } else {
  8565. data.direction = 'both';
  8566. }
  8567. data.uri = parts.shift();
  8568. data.params = parts;
  8569. return data;
  8570. },
  8571. find_line: function (haystack, needle, sessionpart) {
  8572. var lines = haystack.split('\r\n');
  8573. for (var i = 0; i < lines.length; i++) {
  8574. if (lines[i].substring(0, needle.length) == needle) {
  8575. return lines[i];
  8576. }
  8577. }
  8578. if (!sessionpart) {
  8579. return false;
  8580. }
  8581. // search session part
  8582. lines = sessionpart.split('\r\n');
  8583. for (var j = 0; j < lines.length; j++) {
  8584. if (lines[j].substring(0, needle.length) == needle) {
  8585. return lines[j];
  8586. }
  8587. }
  8588. return false;
  8589. },
  8590. find_lines: function (haystack, needle, sessionpart) {
  8591. var lines = haystack.split('\r\n'),
  8592. needles = [];
  8593. for (var i = 0; i < lines.length; i++) {
  8594. if (lines[i].substring(0, needle.length) == needle)
  8595. needles.push(lines[i]);
  8596. }
  8597. if (needles.length || !sessionpart) {
  8598. return needles;
  8599. }
  8600. // search session part
  8601. lines = sessionpart.split('\r\n');
  8602. for (var j = 0; j < lines.length; j++) {
  8603. if (lines[j].substring(0, needle.length) == needle) {
  8604. needles.push(lines[j]);
  8605. }
  8606. }
  8607. return needles;
  8608. },
  8609. candidateToJingle: function (line) {
  8610. // a=candidate:2979166662 1 udp 2113937151 192.168.2.100 57698 typ host generation 0
  8611. // <candidate component=... foundation=... generation=... id=... ip=... network=... port=... priority=... protocol=... type=.../>
  8612. if (line.indexOf('candidate:') === 0) {
  8613. line = 'a=' + line;
  8614. } else if (line.substring(0, 12) != 'a=candidate:') {
  8615. logger.log('parseCandidate called with a line that is not a candidate line');
  8616. logger.log(line);
  8617. return null;
  8618. }
  8619. if (line.substring(line.length - 2) == '\r\n') // chomp it
  8620. line = line.substring(0, line.length - 2);
  8621. var candidate = {},
  8622. elems = line.split(' '),
  8623. i;
  8624. if (elems[6] != 'typ') {
  8625. logger.log('did not find typ in the right place');
  8626. logger.log(line);
  8627. return null;
  8628. }
  8629. candidate.foundation = elems[0].substring(12);
  8630. candidate.component = elems[1];
  8631. candidate.protocol = elems[2].toLowerCase();
  8632. candidate.priority = elems[3];
  8633. candidate.ip = elems[4];
  8634. candidate.port = elems[5];
  8635. // elems[6] => "typ"
  8636. candidate.type = elems[7];
  8637. candidate.generation = '0'; // default, may be overwritten below
  8638. for (i = 8; i < elems.length; i += 2) {
  8639. switch (elems[i]) {
  8640. case 'raddr':
  8641. candidate['rel-addr'] = elems[i + 1];
  8642. break;
  8643. case 'rport':
  8644. candidate['rel-port'] = elems[i + 1];
  8645. break;
  8646. case 'generation':
  8647. candidate.generation = elems[i + 1];
  8648. break;
  8649. case 'tcptype':
  8650. candidate.tcptype = elems[i + 1];
  8651. break;
  8652. default: // TODO
  8653. logger.log('not translating "' + elems[i] + '" = "' + elems[i + 1] + '"');
  8654. }
  8655. }
  8656. candidate.network = '1';
  8657. candidate.id = Math.random().toString(36).substr(2, 10); // not applicable to SDP -- FIXME: should be unique, not just random
  8658. return candidate;
  8659. },
  8660. candidateFromJingle: function (cand) {
  8661. var line = 'a=candidate:';
  8662. line += cand.getAttribute('foundation');
  8663. line += ' ';
  8664. line += cand.getAttribute('component');
  8665. line += ' ';
  8666. var protocol = cand.getAttribute('protocol');
  8667. // use tcp candidates for FF
  8668. if (RTCBrowserType.isFirefox() && protocol.toLowerCase() == 'ssltcp') {
  8669. protocol = 'tcp';
  8670. }
  8671. line += protocol; //.toUpperCase(); // chrome M23 doesn't like this
  8672. line += ' ';
  8673. line += cand.getAttribute('priority');
  8674. line += ' ';
  8675. line += cand.getAttribute('ip');
  8676. line += ' ';
  8677. line += cand.getAttribute('port');
  8678. line += ' ';
  8679. line += 'typ';
  8680. line += ' ' + cand.getAttribute('type');
  8681. line += ' ';
  8682. switch (cand.getAttribute('type')) {
  8683. case 'srflx':
  8684. case 'prflx':
  8685. case 'relay':
  8686. if (cand.getAttribute('rel-addr') && cand.getAttribute('rel-port')) {
  8687. line += 'raddr';
  8688. line += ' ';
  8689. line += cand.getAttribute('rel-addr');
  8690. line += ' ';
  8691. line += 'rport';
  8692. line += ' ';
  8693. line += cand.getAttribute('rel-port');
  8694. line += ' ';
  8695. }
  8696. break;
  8697. }
  8698. if (protocol.toLowerCase() == 'tcp') {
  8699. line += 'tcptype';
  8700. line += ' ';
  8701. line += cand.getAttribute('tcptype');
  8702. line += ' ';
  8703. }
  8704. line += 'generation';
  8705. line += ' ';
  8706. line += cand.getAttribute('generation') || '0';
  8707. return line + '\r\n';
  8708. }
  8709. };
  8710. module.exports = SDPUtil;
  8711. }).call(this,"/modules/xmpp/SDPUtil.js")
  8712. },{"../RTC/RTCBrowserType":17,"jitsi-meet-logger":47}],33:[function(require,module,exports){
  8713. (function (__filename){
  8714. /* global $ */
  8715. var RTC = require('../RTC/RTC');
  8716. var logger = require("jitsi-meet-logger").getLogger(__filename);
  8717. var RTCBrowserType = require("../RTC/RTCBrowserType.js");
  8718. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  8719. var SSRCReplacement = require("./LocalSSRCReplacement");
  8720. function TraceablePeerConnection(ice_config, constraints, session) {
  8721. var self = this;
  8722. this.session = session;
  8723. var RTCPeerConnectionType = null;
  8724. if (RTCBrowserType.isFirefox()) {
  8725. RTCPeerConnectionType = mozRTCPeerConnection;
  8726. } else if (RTCBrowserType.isTemasysPluginUsed()) {
  8727. RTCPeerConnectionType = RTCPeerConnection;
  8728. } else {
  8729. RTCPeerConnectionType = webkitRTCPeerConnection;
  8730. }
  8731. this.peerconnection = new RTCPeerConnectionType(ice_config, constraints);
  8732. this.updateLog = [];
  8733. this.stats = {};
  8734. this.statsinterval = null;
  8735. this.maxstats = 0; // limit to 300 values, i.e. 5 minutes; set to 0 to disable
  8736. var Interop = require('sdp-interop').Interop;
  8737. this.interop = new Interop();
  8738. var Simulcast = require('sdp-simulcast');
  8739. this.simulcast = new Simulcast({numOfLayers: 3, explodeRemoteSimulcast: false});
  8740. // override as desired
  8741. this.trace = function (what, info) {
  8742. /*logger.warn('WTRACE', what, info);
  8743. if (info && RTCBrowserType.isIExplorer()) {
  8744. if (info.length > 1024) {
  8745. logger.warn('WTRACE', what, info.substr(1024));
  8746. }
  8747. if (info.length > 2048) {
  8748. logger.warn('WTRACE', what, info.substr(2048));
  8749. }
  8750. }*/
  8751. self.updateLog.push({
  8752. time: new Date(),
  8753. type: what,
  8754. value: info || ""
  8755. });
  8756. };
  8757. this.onicecandidate = null;
  8758. this.peerconnection.onicecandidate = function (event) {
  8759. // FIXME: this causes stack overflow with Temasys Plugin
  8760. if (!RTCBrowserType.isTemasysPluginUsed())
  8761. self.trace('onicecandidate', JSON.stringify(event.candidate, null, ' '));
  8762. if (self.onicecandidate !== null) {
  8763. self.onicecandidate(event);
  8764. }
  8765. };
  8766. this.onaddstream = null;
  8767. this.peerconnection.onaddstream = function (event) {
  8768. self.trace('onaddstream', event.stream.id);
  8769. if (self.onaddstream !== null) {
  8770. self.onaddstream(event);
  8771. }
  8772. };
  8773. this.onremovestream = null;
  8774. this.peerconnection.onremovestream = function (event) {
  8775. self.trace('onremovestream', event.stream.id);
  8776. if (self.onremovestream !== null) {
  8777. self.onremovestream(event);
  8778. }
  8779. };
  8780. this.onsignalingstatechange = null;
  8781. this.peerconnection.onsignalingstatechange = function (event) {
  8782. self.trace('onsignalingstatechange', self.signalingState);
  8783. if (self.onsignalingstatechange !== null) {
  8784. self.onsignalingstatechange(event);
  8785. }
  8786. };
  8787. this.oniceconnectionstatechange = null;
  8788. this.peerconnection.oniceconnectionstatechange = function (event) {
  8789. self.trace('oniceconnectionstatechange', self.iceConnectionState);
  8790. if (self.oniceconnectionstatechange !== null) {
  8791. self.oniceconnectionstatechange(event);
  8792. }
  8793. };
  8794. this.onnegotiationneeded = null;
  8795. this.peerconnection.onnegotiationneeded = function (event) {
  8796. self.trace('onnegotiationneeded');
  8797. if (self.onnegotiationneeded !== null) {
  8798. self.onnegotiationneeded(event);
  8799. }
  8800. };
  8801. self.ondatachannel = null;
  8802. this.peerconnection.ondatachannel = function (event) {
  8803. self.trace('ondatachannel', event);
  8804. if (self.ondatachannel !== null) {
  8805. self.ondatachannel(event);
  8806. }
  8807. };
  8808. // XXX: do all non-firefox browsers which we support also support this?
  8809. if (!RTCBrowserType.isFirefox() && this.maxstats) {
  8810. this.statsinterval = window.setInterval(function() {
  8811. self.peerconnection.getStats(function(stats) {
  8812. var results = stats.result();
  8813. var now = new Date();
  8814. for (var i = 0; i < results.length; ++i) {
  8815. results[i].names().forEach(function (name) {
  8816. var id = results[i].id + '-' + name;
  8817. if (!self.stats[id]) {
  8818. self.stats[id] = {
  8819. startTime: now,
  8820. endTime: now,
  8821. values: [],
  8822. times: []
  8823. };
  8824. }
  8825. self.stats[id].values.push(results[i].stat(name));
  8826. self.stats[id].times.push(now.getTime());
  8827. if (self.stats[id].values.length > self.maxstats) {
  8828. self.stats[id].values.shift();
  8829. self.stats[id].times.shift();
  8830. }
  8831. self.stats[id].endTime = now;
  8832. });
  8833. }
  8834. });
  8835. }, 1000);
  8836. }
  8837. }
  8838. /**
  8839. * Returns a string representation of a SessionDescription object.
  8840. */
  8841. var dumpSDP = function(description) {
  8842. if (typeof description === 'undefined' || description == null) {
  8843. return '';
  8844. }
  8845. return 'type: ' + description.type + '\r\n' + description.sdp;
  8846. };
  8847. /**
  8848. * Takes a SessionDescription object and returns a "normalized" version.
  8849. * Currently it only takes care of ordering the a=ssrc lines.
  8850. */
  8851. var normalizePlanB = function(desc) {
  8852. if (typeof desc !== 'object' || desc === null ||
  8853. typeof desc.sdp !== 'string') {
  8854. logger.warn('An empty description was passed as an argument.');
  8855. return desc;
  8856. }
  8857. var transform = require('sdp-transform');
  8858. var session = transform.parse(desc.sdp);
  8859. if (typeof session !== 'undefined' && typeof session.media !== 'undefined' &&
  8860. Array.isArray(session.media)) {
  8861. session.media.forEach(function (mLine) {
  8862. // Chrome appears to be picky about the order in which a=ssrc lines
  8863. // are listed in an m-line when rtx is enabled (and thus there are
  8864. // a=ssrc-group lines with FID semantics). Specifically if we have
  8865. // "a=ssrc-group:FID S1 S2" and the "a=ssrc:S2" lines appear before
  8866. // the "a=ssrc:S1" lines, SRD fails.
  8867. // So, put SSRC which appear as the first SSRC in an FID ssrc-group
  8868. // first.
  8869. var firstSsrcs = [];
  8870. var newSsrcLines = [];
  8871. if (typeof mLine.ssrcGroups !== 'undefined' && Array.isArray(mLine.ssrcGroups)) {
  8872. mLine.ssrcGroups.forEach(function (group) {
  8873. if (typeof group.semantics !== 'undefined' &&
  8874. group.semantics === 'FID') {
  8875. if (typeof group.ssrcs !== 'undefined') {
  8876. firstSsrcs.push(Number(group.ssrcs.split(' ')[0]));
  8877. }
  8878. }
  8879. });
  8880. }
  8881. if (typeof mLine.ssrcs !== 'undefined' && Array.isArray(mLine.ssrcs)) {
  8882. var i;
  8883. for (i = 0; i<mLine.ssrcs.length; i++){
  8884. if (typeof mLine.ssrcs[i] === 'object'
  8885. && typeof mLine.ssrcs[i].id !== 'undefined'
  8886. && !$.inArray(mLine.ssrcs[i].id, firstSsrcs)) {
  8887. newSsrcLines.push(mLine.ssrcs[i]);
  8888. delete mLine.ssrcs[i];
  8889. }
  8890. }
  8891. for (i = 0; i<mLine.ssrcs.length; i++){
  8892. if (typeof mLine.ssrcs[i] !== 'undefined') {
  8893. newSsrcLines.push(mLine.ssrcs[i]);
  8894. }
  8895. }
  8896. mLine.ssrcs = newSsrcLines;
  8897. }
  8898. });
  8899. }
  8900. var resStr = transform.write(session);
  8901. return new RTCSessionDescription({
  8902. type: desc.type,
  8903. sdp: resStr
  8904. });
  8905. };
  8906. var getters = {
  8907. signalingState: function () {
  8908. return this.peerconnection.signalingState;
  8909. },
  8910. iceConnectionState: function () {
  8911. return this.peerconnection.iceConnectionState;
  8912. },
  8913. localDescription: function() {
  8914. var desc = this.peerconnection.localDescription;
  8915. // FIXME this should probably be after the Unified Plan -> Plan B
  8916. // transformation.
  8917. desc = SSRCReplacement.mungeLocalVideoSSRC(desc);
  8918. this.trace('getLocalDescription::preTransform', dumpSDP(desc));
  8919. // if we're running on FF, transform to Plan B first.
  8920. if (RTCBrowserType.usesUnifiedPlan()) {
  8921. desc = this.interop.toPlanB(desc);
  8922. this.trace('getLocalDescription::postTransform (Plan B)', dumpSDP(desc));
  8923. }
  8924. return desc;
  8925. },
  8926. remoteDescription: function() {
  8927. var desc = this.peerconnection.remoteDescription;
  8928. this.trace('getRemoteDescription::preTransform', dumpSDP(desc));
  8929. // if we're running on FF, transform to Plan B first.
  8930. if (RTCBrowserType.usesUnifiedPlan()) {
  8931. desc = this.interop.toPlanB(desc);
  8932. this.trace('getRemoteDescription::postTransform (Plan B)', dumpSDP(desc));
  8933. }
  8934. return desc;
  8935. }
  8936. };
  8937. Object.keys(getters).forEach(function (prop) {
  8938. Object.defineProperty(
  8939. TraceablePeerConnection.prototype,
  8940. prop, {
  8941. get: getters[prop]
  8942. }
  8943. );
  8944. });
  8945. TraceablePeerConnection.prototype.addStream = function (stream) {
  8946. this.trace('addStream', stream.id);
  8947. try
  8948. {
  8949. this.peerconnection.addStream(stream);
  8950. }
  8951. catch (e)
  8952. {
  8953. logger.error(e);
  8954. }
  8955. };
  8956. TraceablePeerConnection.prototype.removeStream = function (stream, stopStreams) {
  8957. this.trace('removeStream', stream.id);
  8958. if(stopStreams) {
  8959. RTC.stopMediaStream(stream);
  8960. }
  8961. try {
  8962. // FF doesn't support this yet.
  8963. if (this.peerconnection.removeStream)
  8964. this.peerconnection.removeStream(stream);
  8965. } catch (e) {
  8966. logger.error(e);
  8967. }
  8968. };
  8969. TraceablePeerConnection.prototype.createDataChannel = function (label, opts) {
  8970. this.trace('createDataChannel', label, opts);
  8971. return this.peerconnection.createDataChannel(label, opts);
  8972. };
  8973. TraceablePeerConnection.prototype.setLocalDescription
  8974. = function (description, successCallback, failureCallback) {
  8975. this.trace('setLocalDescription::preTransform', dumpSDP(description));
  8976. // if we're running on FF, transform to Plan A first.
  8977. if (RTCBrowserType.usesUnifiedPlan()) {
  8978. description = this.interop.toUnifiedPlan(description);
  8979. this.trace('setLocalDescription::postTransform (Plan A)', dumpSDP(description));
  8980. }
  8981. var self = this;
  8982. this.peerconnection.setLocalDescription(description,
  8983. function () {
  8984. self.trace('setLocalDescriptionOnSuccess');
  8985. successCallback();
  8986. },
  8987. function (err) {
  8988. self.trace('setLocalDescriptionOnFailure', err);
  8989. failureCallback(err);
  8990. }
  8991. );
  8992. /*
  8993. if (this.statsinterval === null && this.maxstats > 0) {
  8994. // start gathering stats
  8995. }
  8996. */
  8997. };
  8998. TraceablePeerConnection.prototype.setRemoteDescription
  8999. = function (description, successCallback, failureCallback) {
  9000. this.trace('setRemoteDescription::preTransform', dumpSDP(description));
  9001. // TODO the focus should squeze or explode the remote simulcast
  9002. description = this.simulcast.mungeRemoteDescription(description);
  9003. this.trace('setRemoteDescription::postTransform (simulcast)', dumpSDP(description));
  9004. // if we're running on FF, transform to Plan A first.
  9005. if (RTCBrowserType.usesUnifiedPlan()) {
  9006. description = this.interop.toUnifiedPlan(description);
  9007. this.trace('setRemoteDescription::postTransform (Plan A)', dumpSDP(description));
  9008. }
  9009. if (RTCBrowserType.usesPlanB()) {
  9010. description = normalizePlanB(description);
  9011. }
  9012. var self = this;
  9013. this.peerconnection.setRemoteDescription(description,
  9014. function () {
  9015. self.trace('setRemoteDescriptionOnSuccess');
  9016. successCallback();
  9017. },
  9018. function (err) {
  9019. self.trace('setRemoteDescriptionOnFailure', err);
  9020. failureCallback(err);
  9021. }
  9022. );
  9023. /*
  9024. if (this.statsinterval === null && this.maxstats > 0) {
  9025. // start gathering stats
  9026. }
  9027. */
  9028. };
  9029. TraceablePeerConnection.prototype.close = function () {
  9030. this.trace('stop');
  9031. if (this.statsinterval !== null) {
  9032. window.clearInterval(this.statsinterval);
  9033. this.statsinterval = null;
  9034. }
  9035. this.peerconnection.close();
  9036. };
  9037. TraceablePeerConnection.prototype.createOffer
  9038. = function (successCallback, failureCallback, constraints) {
  9039. var self = this;
  9040. this.trace('createOffer', JSON.stringify(constraints, null, ' '));
  9041. this.peerconnection.createOffer(
  9042. function (offer) {
  9043. self.trace('createOfferOnSuccess::preTransform', dumpSDP(offer));
  9044. // NOTE this is not tested because in meet the focus generates the
  9045. // offer.
  9046. // if we're running on FF, transform to Plan B first.
  9047. if (RTCBrowserType.usesUnifiedPlan()) {
  9048. offer = self.interop.toPlanB(offer);
  9049. self.trace('createOfferOnSuccess::postTransform (Plan B)', dumpSDP(offer));
  9050. }
  9051. offer = SSRCReplacement.mungeLocalVideoSSRC(offer);
  9052. if (self.session.room.options.enableSimulcast && self.simulcast.isSupported()) {
  9053. offer = self.simulcast.mungeLocalDescription(offer);
  9054. self.trace('createOfferOnSuccess::postTransform (simulcast)', dumpSDP(offer));
  9055. }
  9056. successCallback(offer);
  9057. },
  9058. function(err) {
  9059. self.trace('createOfferOnFailure', err);
  9060. failureCallback(err);
  9061. },
  9062. constraints
  9063. );
  9064. };
  9065. TraceablePeerConnection.prototype.createAnswer
  9066. = function (successCallback, failureCallback, constraints) {
  9067. var self = this;
  9068. this.trace('createAnswer', JSON.stringify(constraints, null, ' '));
  9069. this.peerconnection.createAnswer(
  9070. function (answer) {
  9071. self.trace('createAnswerOnSuccess::preTransform', dumpSDP(answer));
  9072. // if we're running on FF, transform to Plan A first.
  9073. if (RTCBrowserType.usesUnifiedPlan()) {
  9074. answer = self.interop.toPlanB(answer);
  9075. self.trace('createAnswerOnSuccess::postTransform (Plan B)', dumpSDP(answer));
  9076. }
  9077. // munge local video SSRC
  9078. answer = SSRCReplacement.mungeLocalVideoSSRC(answer);
  9079. if (self.session.room.options.enableSimulcast && self.simulcast.isSupported()) {
  9080. answer = self.simulcast.mungeLocalDescription(answer);
  9081. self.trace('createAnswerOnSuccess::postTransform (simulcast)', dumpSDP(answer));
  9082. }
  9083. successCallback(answer);
  9084. },
  9085. function(err) {
  9086. self.trace('createAnswerOnFailure', err);
  9087. failureCallback(err);
  9088. },
  9089. constraints
  9090. );
  9091. };
  9092. TraceablePeerConnection.prototype.addIceCandidate
  9093. = function (candidate, successCallback, failureCallback) {
  9094. //var self = this;
  9095. this.trace('addIceCandidate', JSON.stringify(candidate, null, ' '));
  9096. this.peerconnection.addIceCandidate(candidate);
  9097. /* maybe later
  9098. this.peerconnection.addIceCandidate(candidate,
  9099. function () {
  9100. self.trace('addIceCandidateOnSuccess');
  9101. successCallback();
  9102. },
  9103. function (err) {
  9104. self.trace('addIceCandidateOnFailure', err);
  9105. failureCallback(err);
  9106. }
  9107. );
  9108. */
  9109. };
  9110. TraceablePeerConnection.prototype.getStats = function(callback, errback) {
  9111. // TODO: Is this the correct way to handle Opera, Temasys?
  9112. if (RTCBrowserType.isFirefox()) {
  9113. // ignore for now...
  9114. if(!errback)
  9115. errback = function () {};
  9116. this.peerconnection.getStats(null, callback, errback);
  9117. } else {
  9118. this.peerconnection.getStats(callback);
  9119. }
  9120. };
  9121. module.exports = TraceablePeerConnection;
  9122. }).call(this,"/modules/xmpp/TraceablePeerConnection.js")
  9123. },{"../../service/xmpp/XMPPEvents":85,"../RTC/RTC":16,"../RTC/RTCBrowserType.js":17,"./LocalSSRCReplacement":29,"jitsi-meet-logger":47,"sdp-interop":65,"sdp-simulcast":68,"sdp-transform":75}],34:[function(require,module,exports){
  9124. (function (__filename){
  9125. /* global $, $iq, APP, config, messageHandler,
  9126. roomName, sessionTerminated, Strophe, Util */
  9127. var logger = require("jitsi-meet-logger").getLogger(__filename);
  9128. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  9129. var Settings = require("../settings/Settings");
  9130. var AuthenticationEvents
  9131. = require("../../service/authentication/AuthenticationEvents");
  9132. function createExpBackoffTimer(step) {
  9133. var count = 1;
  9134. return function (reset) {
  9135. // Reset call
  9136. if (reset) {
  9137. count = 1;
  9138. return;
  9139. }
  9140. // Calculate next timeout
  9141. var timeout = Math.pow(2, count - 1);
  9142. count += 1;
  9143. return timeout * step;
  9144. };
  9145. }
  9146. function Moderator(roomName, xmpp, emitter) {
  9147. this.roomName = roomName;
  9148. this.xmppService = xmpp;
  9149. this.getNextTimeout = createExpBackoffTimer(1000);
  9150. this.getNextErrorTimeout = createExpBackoffTimer(1000);
  9151. // External authentication stuff
  9152. this.externalAuthEnabled = false;
  9153. this.settings = new Settings(roomName);
  9154. // Sip gateway can be enabled by configuring Jigasi host in config.js or
  9155. // it will be enabled automatically if focus detects the component through
  9156. // service discovery.
  9157. this.sipGatewayEnabled =
  9158. this.xmppService.options.hosts.call_control !== undefined;
  9159. this.eventEmitter = emitter;
  9160. this.connection = this.xmppService.connection;
  9161. this.focusUserJid;
  9162. //FIXME:
  9163. // Message listener that talks to POPUP window
  9164. function listener(event) {
  9165. if (event.data && event.data.sessionId) {
  9166. if (event.origin !== window.location.origin) {
  9167. logger.warn("Ignoring sessionId from different origin: " +
  9168. event.origin);
  9169. return;
  9170. }
  9171. localStorage.setItem('sessionId', event.data.sessionId);
  9172. // After popup is closed we will authenticate
  9173. }
  9174. }
  9175. // Register
  9176. if (window.addEventListener) {
  9177. window.addEventListener("message", listener, false);
  9178. } else {
  9179. window.attachEvent("onmessage", listener);
  9180. }
  9181. }
  9182. Moderator.prototype.isExternalAuthEnabled = function () {
  9183. return this.externalAuthEnabled;
  9184. };
  9185. Moderator.prototype.isSipGatewayEnabled = function () {
  9186. return this.sipGatewayEnabled;
  9187. };
  9188. Moderator.prototype.onMucMemberLeft = function (jid) {
  9189. logger.info("Someone left is it focus ? " + jid);
  9190. var resource = Strophe.getResourceFromJid(jid);
  9191. if (resource === 'focus' && !this.xmppService.sessionTerminated) {
  9192. logger.info(
  9193. "Focus has left the room - leaving conference");
  9194. //hangUp();
  9195. // We'd rather reload to have everything re-initialized
  9196. //FIXME: show some message before reload
  9197. this.eventEmitter.emit(XMPPEvents.FOCUS_LEFT);
  9198. }
  9199. };
  9200. Moderator.prototype.setFocusUserJid = function (focusJid) {
  9201. if (!this.focusUserJid) {
  9202. this.focusUserJid = focusJid;
  9203. logger.info("Focus jid set to: " + this.focusUserJid);
  9204. }
  9205. };
  9206. Moderator.prototype.getFocusUserJid = function () {
  9207. return this.focusUserJid;
  9208. };
  9209. Moderator.prototype.getFocusComponent = function () {
  9210. // Get focus component address
  9211. var focusComponent = this.xmppService.options.hosts.focus;
  9212. // If not specified use default: 'focus.domain'
  9213. if (!focusComponent) {
  9214. focusComponent = 'focus.' + this.xmppService.options.hosts.domain;
  9215. }
  9216. return focusComponent;
  9217. };
  9218. Moderator.prototype.createConferenceIq = function () {
  9219. // Generate create conference IQ
  9220. var elem = $iq({to: this.getFocusComponent(), type: 'set'});
  9221. // Session Id used for authentication
  9222. var sessionId = localStorage.getItem('sessionId');
  9223. var machineUID = this.settings.getSettings().uid;
  9224. logger.info(
  9225. "Session ID: " + sessionId + " machine UID: " + machineUID);
  9226. elem.c('conference', {
  9227. xmlns: 'http://jitsi.org/protocol/focus',
  9228. room: this.roomName,
  9229. 'machine-uid': machineUID
  9230. });
  9231. if (sessionId) {
  9232. elem.attrs({ 'session-id': sessionId});
  9233. }
  9234. if (this.xmppService.options.hosts.bridge !== undefined) {
  9235. elem.c(
  9236. 'property', {
  9237. name: 'bridge',
  9238. value: this.xmppService.options.hosts.bridge
  9239. }).up();
  9240. }
  9241. if (this.xmppService.options.enforcedBridge !== undefined) {
  9242. elem.c(
  9243. 'property', {
  9244. name: 'enforcedBridge',
  9245. value: this.xmppService.options.enforcedBridge
  9246. }).up();
  9247. }
  9248. // Tell the focus we have Jigasi configured
  9249. if (this.xmppService.options.hosts.call_control !== undefined) {
  9250. elem.c(
  9251. 'property', {
  9252. name: 'call_control',
  9253. value: this.xmppService.options.hosts.call_control
  9254. }).up();
  9255. }
  9256. if (this.xmppService.options.channelLastN !== undefined) {
  9257. elem.c(
  9258. 'property', {
  9259. name: 'channelLastN',
  9260. value: this.xmppService.options.channelLastN
  9261. }).up();
  9262. }
  9263. if (this.xmppService.options.adaptiveLastN !== undefined) {
  9264. elem.c(
  9265. 'property', {
  9266. name: 'adaptiveLastN',
  9267. value: this.xmppService.options.adaptiveLastN
  9268. }).up();
  9269. }
  9270. if (this.xmppService.options.adaptiveSimulcast !== undefined) {
  9271. elem.c(
  9272. 'property', {
  9273. name: 'adaptiveSimulcast',
  9274. value: this.xmppService.options.adaptiveSimulcast
  9275. }).up();
  9276. }
  9277. if (this.xmppService.options.openSctp !== undefined) {
  9278. elem.c(
  9279. 'property', {
  9280. name: 'openSctp',
  9281. value: this.xmppService.options.openSctp
  9282. }).up();
  9283. }
  9284. if (this.xmppService.options.startAudioMuted !== undefined)
  9285. {
  9286. elem.c(
  9287. 'property', {
  9288. name: 'startAudioMuted',
  9289. value: this.xmppService.options.startAudioMuted
  9290. }).up();
  9291. }
  9292. if (this.xmppService.options.startVideoMuted !== undefined)
  9293. {
  9294. elem.c(
  9295. 'property', {
  9296. name: 'startVideoMuted',
  9297. value: this.xmppService.options.startVideoMuted
  9298. }).up();
  9299. }
  9300. elem.c(
  9301. 'property', {
  9302. name: 'simulcastMode',
  9303. value: 'rewriting'
  9304. }).up();
  9305. elem.up();
  9306. return elem;
  9307. };
  9308. Moderator.prototype.parseSessionId = function (resultIq) {
  9309. var sessionId = $(resultIq).find('conference').attr('session-id');
  9310. if (sessionId) {
  9311. logger.info('Received sessionId: ' + sessionId);
  9312. localStorage.setItem('sessionId', sessionId);
  9313. }
  9314. };
  9315. Moderator.prototype.parseConfigOptions = function (resultIq) {
  9316. this.setFocusUserJid(
  9317. $(resultIq).find('conference').attr('focusjid'));
  9318. var authenticationEnabled
  9319. = $(resultIq).find(
  9320. '>conference>property' +
  9321. '[name=\'authentication\'][value=\'true\']').length > 0;
  9322. logger.info("Authentication enabled: " + authenticationEnabled);
  9323. this.externalAuthEnabled = $(resultIq).find(
  9324. '>conference>property' +
  9325. '[name=\'externalAuth\'][value=\'true\']').length > 0;
  9326. console.info(
  9327. 'External authentication enabled: ' + this.externalAuthEnabled);
  9328. if (!this.externalAuthEnabled) {
  9329. // We expect to receive sessionId in 'internal' authentication mode
  9330. this.parseSessionId(resultIq);
  9331. }
  9332. var authIdentity = $(resultIq).find('>conference').attr('identity');
  9333. this.eventEmitter.emit(AuthenticationEvents.IDENTITY_UPDATED,
  9334. authenticationEnabled, authIdentity);
  9335. // Check if focus has auto-detected Jigasi component(this will be also
  9336. // included if we have passed our host from the config)
  9337. if ($(resultIq).find(
  9338. '>conference>property' +
  9339. '[name=\'sipGatewayEnabled\'][value=\'true\']').length) {
  9340. this.sipGatewayEnabled = true;
  9341. }
  9342. logger.info("Sip gateway enabled: " + this.sipGatewayEnabled);
  9343. };
  9344. // FIXME = we need to show the fact that we're waiting for the focus
  9345. // to the user(or that focus is not available)
  9346. Moderator.prototype.allocateConferenceFocus = function (callback) {
  9347. // Try to use focus user JID from the config
  9348. this.setFocusUserJid(this.xmppService.options.focusUserJid);
  9349. // Send create conference IQ
  9350. var iq = this.createConferenceIq();
  9351. var self = this;
  9352. this.connection.sendIQ(
  9353. iq,
  9354. function (result) {
  9355. // Setup config options
  9356. self.parseConfigOptions(result);
  9357. if ('true' === $(result).find('conference').attr('ready')) {
  9358. // Reset both timers
  9359. self.getNextTimeout(true);
  9360. self.getNextErrorTimeout(true);
  9361. // Exec callback
  9362. callback();
  9363. } else {
  9364. var waitMs = self.getNextTimeout();
  9365. logger.info("Waiting for the focus... " + waitMs);
  9366. // Reset error timeout
  9367. self.getNextErrorTimeout(true);
  9368. window.setTimeout(
  9369. function () {
  9370. self.allocateConferenceFocus(callback);
  9371. }, waitMs);
  9372. }
  9373. },
  9374. function (error) {
  9375. // Invalid session ? remove and try again
  9376. // without session ID to get a new one
  9377. var invalidSession
  9378. = $(error).find('>error>session-invalid').length;
  9379. if (invalidSession) {
  9380. logger.info("Session expired! - removing");
  9381. localStorage.removeItem("sessionId");
  9382. }
  9383. if ($(error).find('>error>graceful-shutdown').length) {
  9384. self.eventEmitter.emit(XMPPEvents.GRACEFUL_SHUTDOWN);
  9385. return;
  9386. }
  9387. // Check for error returned by the reservation system
  9388. var reservationErr = $(error).find('>error>reservation-error');
  9389. if (reservationErr.length) {
  9390. // Trigger error event
  9391. var errorCode = reservationErr.attr('error-code');
  9392. var errorMsg;
  9393. if ($(error).find('>error>text')) {
  9394. errorMsg = $(error).find('>error>text').text();
  9395. }
  9396. self.eventEmitter.emit(
  9397. XMPPEvents.RESERVATION_ERROR, errorCode, errorMsg);
  9398. return;
  9399. }
  9400. // Not authorized to create new room
  9401. if ($(error).find('>error>not-authorized').length) {
  9402. logger.warn("Unauthorized to start the conference", error);
  9403. var toDomain
  9404. = Strophe.getDomainFromJid(error.getAttribute('to'));
  9405. if (toDomain !==
  9406. this.xmppService.options.hosts.anonymousdomain) {
  9407. //FIXME: "is external" should come either from
  9408. // the focus or config.js
  9409. self.externalAuthEnabled = true;
  9410. }
  9411. self.eventEmitter.emit(
  9412. XMPPEvents.AUTHENTICATION_REQUIRED,
  9413. function () {
  9414. self.allocateConferenceFocus(
  9415. callback);
  9416. });
  9417. return;
  9418. }
  9419. var waitMs = self.getNextErrorTimeout();
  9420. logger.error("Focus error, retry after " + waitMs, error);
  9421. // Show message
  9422. var focusComponent = self.getFocusComponent();
  9423. var retrySec = waitMs / 1000;
  9424. //FIXME: message is duplicated ?
  9425. // Do not show in case of session invalid
  9426. // which means just a retry
  9427. if (!invalidSession) {
  9428. self.eventEmitter.emit(XMPPEvents.FOCUS_DISCONNECTED,
  9429. focusComponent, retrySec);
  9430. }
  9431. // Reset response timeout
  9432. self.getNextTimeout(true);
  9433. window.setTimeout(
  9434. function () {
  9435. self.allocateConferenceFocus(callback);
  9436. }, waitMs);
  9437. }
  9438. );
  9439. };
  9440. Moderator.prototype.getLoginUrl = function (urlCallback, failureCallback) {
  9441. var iq = $iq({to: this.getFocusComponent(), type: 'get'});
  9442. iq.c('login-url', {
  9443. xmlns: 'http://jitsi.org/protocol/focus',
  9444. room: this.roomName,
  9445. 'machine-uid': this.settings.getSettings().uid
  9446. });
  9447. this.connection.sendIQ(
  9448. iq,
  9449. function (result) {
  9450. var url = $(result).find('login-url').attr('url');
  9451. url = url = decodeURIComponent(url);
  9452. if (url) {
  9453. logger.info("Got auth url: " + url);
  9454. urlCallback(url);
  9455. } else {
  9456. logger.error(
  9457. "Failed to get auth url from the focus", result);
  9458. failureCallback(result);
  9459. }
  9460. },
  9461. function (error) {
  9462. logger.error("Get auth url error", error);
  9463. failureCallback(error);
  9464. }
  9465. );
  9466. };
  9467. Moderator.prototype.getPopupLoginUrl = function (urlCallback, failureCallback) {
  9468. var iq = $iq({to: this.getFocusComponent(), type: 'get'});
  9469. iq.c('login-url', {
  9470. xmlns: 'http://jitsi.org/protocol/focus',
  9471. room: this.roomName,
  9472. 'machine-uid': this.settings.getSettings().uid,
  9473. popup: true
  9474. });
  9475. this.connection.sendIQ(
  9476. iq,
  9477. function (result) {
  9478. var url = $(result).find('login-url').attr('url');
  9479. url = url = decodeURIComponent(url);
  9480. if (url) {
  9481. logger.info("Got POPUP auth url: " + url);
  9482. urlCallback(url);
  9483. } else {
  9484. logger.error(
  9485. "Failed to get POPUP auth url from the focus", result);
  9486. failureCallback(result);
  9487. }
  9488. },
  9489. function (error) {
  9490. logger.error('Get POPUP auth url error', error);
  9491. failureCallback(error);
  9492. }
  9493. );
  9494. };
  9495. Moderator.prototype.logout = function (callback) {
  9496. var iq = $iq({to: this.getFocusComponent(), type: 'set'});
  9497. var sessionId = localStorage.getItem('sessionId');
  9498. if (!sessionId) {
  9499. callback();
  9500. return;
  9501. }
  9502. iq.c('logout', {
  9503. xmlns: 'http://jitsi.org/protocol/focus',
  9504. 'session-id': sessionId
  9505. });
  9506. this.connection.sendIQ(
  9507. iq,
  9508. function (result) {
  9509. var logoutUrl = $(result).find('logout').attr('logout-url');
  9510. if (logoutUrl) {
  9511. logoutUrl = decodeURIComponent(logoutUrl);
  9512. }
  9513. logger.info("Log out OK, url: " + logoutUrl, result);
  9514. localStorage.removeItem('sessionId');
  9515. callback(logoutUrl);
  9516. },
  9517. function (error) {
  9518. logger.error("Logout error", error);
  9519. }
  9520. );
  9521. };
  9522. module.exports = Moderator;
  9523. }).call(this,"/modules/xmpp/moderator.js")
  9524. },{"../../service/authentication/AuthenticationEvents":81,"../../service/xmpp/XMPPEvents":85,"../settings/Settings":21,"jitsi-meet-logger":47}],35:[function(require,module,exports){
  9525. (function (__filename){
  9526. /* jshint -W117 */
  9527. /* a simple MUC connection plugin
  9528. * can only handle a single MUC room
  9529. */
  9530. var logger = require("jitsi-meet-logger").getLogger(__filename);
  9531. var ChatRoom = require("./ChatRoom");
  9532. module.exports = function(XMPP) {
  9533. Strophe.addConnectionPlugin('emuc', {
  9534. connection: null,
  9535. rooms: {},//map with the rooms
  9536. init: function (conn) {
  9537. this.connection = conn;
  9538. // add handlers (just once)
  9539. this.connection.addHandler(this.onPresence.bind(this), null, 'presence', null, null, null, null);
  9540. this.connection.addHandler(this.onPresenceUnavailable.bind(this), null, 'presence', 'unavailable', null);
  9541. this.connection.addHandler(this.onPresenceError.bind(this), null, 'presence', 'error', null);
  9542. this.connection.addHandler(this.onMessage.bind(this), null, 'message', null, null);
  9543. },
  9544. createRoom: function (jid, password, options) {
  9545. var roomJid = Strophe.getBareJidFromJid(jid);
  9546. if (this.rooms[roomJid]) {
  9547. logger.error("You are already in the room!");
  9548. return;
  9549. }
  9550. this.rooms[roomJid] = new ChatRoom(this.connection, jid, password, XMPP, options);
  9551. return this.rooms[roomJid];
  9552. },
  9553. doLeave: function (jid) {
  9554. this.rooms[jid].doLeave();
  9555. delete this.rooms[jid];
  9556. },
  9557. onPresence: function (pres) {
  9558. var from = pres.getAttribute('from');
  9559. // What is this for? A workaround for something?
  9560. if (pres.getAttribute('type')) {
  9561. return true;
  9562. }
  9563. var room = this.rooms[Strophe.getBareJidFromJid(from)];
  9564. if(!room)
  9565. return;
  9566. // Parse status.
  9567. if ($(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>status[code="201"]').length) {
  9568. room.createNonAnonymousRoom();
  9569. }
  9570. room.onPresence(pres);
  9571. return true;
  9572. },
  9573. onPresenceUnavailable: function (pres) {
  9574. var from = pres.getAttribute('from');
  9575. var room = this.rooms[Strophe.getBareJidFromJid(from)];
  9576. if(!room)
  9577. return;
  9578. room.onPresenceUnavailable(pres, from);
  9579. return true;
  9580. },
  9581. onPresenceError: function (pres) {
  9582. var from = pres.getAttribute('from');
  9583. var room = this.rooms[Strophe.getBareJidFromJid(from)];
  9584. if(!room)
  9585. return;
  9586. room.onPresenceError(pres, from);
  9587. return true;
  9588. },
  9589. onMessage: function (msg) {
  9590. // FIXME: this is a hack. but jingle on muc makes nickchanges hard
  9591. var from = msg.getAttribute('from');
  9592. var room = this.rooms[Strophe.getBareJidFromJid(from)];
  9593. if(!room)
  9594. return;
  9595. room.onMessage(msg, from);
  9596. return true;
  9597. },
  9598. setJingleSession: function (from, session) {
  9599. var room = this.rooms[Strophe.getBareJidFromJid(from)];
  9600. if(!room)
  9601. return;
  9602. room.setJingleSession(session);
  9603. }
  9604. });
  9605. };
  9606. }).call(this,"/modules/xmpp/strophe.emuc.js")
  9607. },{"./ChatRoom":26,"jitsi-meet-logger":47}],36:[function(require,module,exports){
  9608. (function (__filename){
  9609. /* jshint -W117 */
  9610. var logger = require("jitsi-meet-logger").getLogger(__filename);
  9611. var JingleSession = require("./JingleSessionPC");
  9612. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  9613. var RTCBrowserType = require("../RTC/RTCBrowserType");
  9614. module.exports = function(XMPP, eventEmitter) {
  9615. Strophe.addConnectionPlugin('jingle', {
  9616. connection: null,
  9617. sessions: {},
  9618. jid2session: {},
  9619. ice_config: {iceServers: []},
  9620. media_constraints: {
  9621. mandatory: {
  9622. 'OfferToReceiveAudio': true,
  9623. 'OfferToReceiveVideo': true
  9624. }
  9625. // MozDontOfferDataChannel: true when this is firefox
  9626. },
  9627. init: function (conn) {
  9628. this.connection = conn;
  9629. if (this.connection.disco) {
  9630. // http://xmpp.org/extensions/xep-0167.html#support
  9631. // http://xmpp.org/extensions/xep-0176.html#support
  9632. this.connection.disco.addFeature('urn:xmpp:jingle:1');
  9633. this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:1');
  9634. this.connection.disco.addFeature('urn:xmpp:jingle:transports:ice-udp:1');
  9635. this.connection.disco.addFeature('urn:xmpp:jingle:apps:dtls:0');
  9636. this.connection.disco.addFeature('urn:xmpp:jingle:transports:dtls-sctp:1');
  9637. this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:audio');
  9638. this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:video');
  9639. if (RTCBrowserType.isChrome() || RTCBrowserType.isOpera()
  9640. || RTCBrowserType.isTemasysPluginUsed()) {
  9641. this.connection.disco.addFeature('urn:ietf:rfc:4588');
  9642. }
  9643. // this is dealt with by SDP O/A so we don't need to announce this
  9644. //this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:rtcp-fb:0'); // XEP-0293
  9645. //this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:rtp-hdrext:0'); // XEP-0294
  9646. this.connection.disco.addFeature('urn:ietf:rfc:5761'); // rtcp-mux
  9647. this.connection.disco.addFeature('urn:ietf:rfc:5888'); // a=group, e.g. bundle
  9648. //this.connection.disco.addFeature('urn:ietf:rfc:5576'); // a=ssrc
  9649. }
  9650. this.connection.addHandler(this.onJingle.bind(this), 'urn:xmpp:jingle:1', 'iq', 'set', null, null);
  9651. },
  9652. onJingle: function (iq) {
  9653. var sid = $(iq).find('jingle').attr('sid');
  9654. var action = $(iq).find('jingle').attr('action');
  9655. var fromJid = iq.getAttribute('from');
  9656. // send ack first
  9657. var ack = $iq({type: 'result',
  9658. to: fromJid,
  9659. id: iq.getAttribute('id')
  9660. });
  9661. logger.log('on jingle ' + action + ' from ' + fromJid, iq);
  9662. var sess = this.sessions[sid];
  9663. if ('session-initiate' != action) {
  9664. if (sess === null) {
  9665. ack.type = 'error';
  9666. ack.c('error', {type: 'cancel'})
  9667. .c('item-not-found', {xmlns: 'urn:ietf:params:xml:ns:xmpp-stanzas'}).up()
  9668. .c('unknown-session', {xmlns: 'urn:xmpp:jingle:errors:1'});
  9669. this.connection.send(ack);
  9670. return true;
  9671. }
  9672. // local jid is not checked
  9673. if (fromJid != sess.peerjid) {
  9674. logger.warn('jid mismatch for session id', sid, fromJid, sess.peerjid);
  9675. ack.type = 'error';
  9676. ack.c('error', {type: 'cancel'})
  9677. .c('item-not-found', {xmlns: 'urn:ietf:params:xml:ns:xmpp-stanzas'}).up()
  9678. .c('unknown-session', {xmlns: 'urn:xmpp:jingle:errors:1'});
  9679. this.connection.send(ack);
  9680. return true;
  9681. }
  9682. } else if (sess !== undefined) {
  9683. // existing session with same session id
  9684. // this might be out-of-order if the sess.peerjid is the same as from
  9685. ack.type = 'error';
  9686. ack.c('error', {type: 'cancel'})
  9687. .c('service-unavailable', {xmlns: 'urn:ietf:params:xml:ns:xmpp-stanzas'}).up();
  9688. logger.warn('duplicate session id', sid);
  9689. this.connection.send(ack);
  9690. return true;
  9691. }
  9692. // FIXME: check for a defined action
  9693. this.connection.send(ack);
  9694. // see http://xmpp.org/extensions/xep-0166.html#concepts-session
  9695. switch (action) {
  9696. case 'session-initiate':
  9697. console.log("(TIME) received session-initiate:\t",
  9698. window.performance.now());
  9699. var startMuted = $(iq).find('jingle>startmuted');
  9700. if (startMuted && startMuted.length > 0) {
  9701. var audioMuted = startMuted.attr("audio");
  9702. var videoMuted = startMuted.attr("video");
  9703. eventEmitter.emit(XMPPEvents.START_MUTED_FROM_FOCUS,
  9704. audioMuted === "true", videoMuted === "true");
  9705. }
  9706. sess = new JingleSession(
  9707. $(iq).attr('to'), $(iq).find('jingle').attr('sid'),
  9708. this.connection, XMPP);
  9709. // configure session
  9710. var fromBareJid = Strophe.getBareJidFromJid(fromJid);
  9711. this.connection.emuc.setJingleSession(fromBareJid, sess);
  9712. sess.media_constraints = this.media_constraints;
  9713. sess.ice_config = this.ice_config;
  9714. sess.initialize(fromJid, false);
  9715. eventEmitter.emit(XMPPEvents.CALL_INCOMING, sess);
  9716. // FIXME: setRemoteDescription should only be done when this call is to be accepted
  9717. sess.setOffer($(iq).find('>jingle'));
  9718. this.sessions[sess.sid] = sess;
  9719. this.jid2session[sess.peerjid] = sess;
  9720. // the callback should either
  9721. // .sendAnswer and .accept
  9722. // or .sendTerminate -- not necessarily synchronous
  9723. sess.sendAnswer();
  9724. sess.accept();
  9725. break;
  9726. case 'session-accept':
  9727. sess.setAnswer($(iq).find('>jingle'));
  9728. sess.accept();
  9729. break;
  9730. case 'session-terminate':
  9731. // If this is not the focus sending the terminate, we have
  9732. // nothing more to do here.
  9733. if (Object.keys(this.sessions).length < 1
  9734. || !(this.sessions[Object.keys(this.sessions)[0]]
  9735. instanceof JingleSession))
  9736. {
  9737. break;
  9738. }
  9739. logger.log('terminating...', sess.sid);
  9740. sess.terminate();
  9741. this.terminate(sess.sid);
  9742. if ($(iq).find('>jingle>reason').length) {
  9743. $(document).trigger('callterminated.jingle', [
  9744. sess.sid,
  9745. sess.peerjid,
  9746. $(iq).find('>jingle>reason>:first')[0].tagName,
  9747. $(iq).find('>jingle>reason>text').text()
  9748. ]);
  9749. } else {
  9750. $(document).trigger('callterminated.jingle',
  9751. [sess.sid, sess.peerjid]);
  9752. }
  9753. break;
  9754. case 'transport-info':
  9755. sess.addIceCandidate($(iq).find('>jingle>content'));
  9756. break;
  9757. case 'session-info':
  9758. var affected;
  9759. if ($(iq).find('>jingle>ringing[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').length) {
  9760. $(document).trigger('ringing.jingle', [sess.sid]);
  9761. } else if ($(iq).find('>jingle>mute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').length) {
  9762. affected = $(iq).find('>jingle>mute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').attr('name');
  9763. $(document).trigger('mute.jingle', [sess.sid, affected]);
  9764. } else if ($(iq).find('>jingle>unmute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').length) {
  9765. affected = $(iq).find('>jingle>unmute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').attr('name');
  9766. $(document).trigger('unmute.jingle', [sess.sid, affected]);
  9767. }
  9768. break;
  9769. case 'addsource': // FIXME: proprietary, un-jingleish
  9770. case 'source-add': // FIXME: proprietary
  9771. sess.addSource($(iq).find('>jingle>content'));
  9772. break;
  9773. case 'removesource': // FIXME: proprietary, un-jingleish
  9774. case 'source-remove': // FIXME: proprietary
  9775. sess.removeSource($(iq).find('>jingle>content'));
  9776. break;
  9777. default:
  9778. logger.warn('jingle action not implemented', action);
  9779. break;
  9780. }
  9781. return true;
  9782. },
  9783. terminate: function (sid, reason, text) { // terminate by sessionid (or all sessions)
  9784. if (sid === null || sid === undefined) {
  9785. for (sid in this.sessions) {
  9786. if (this.sessions[sid].state != 'ended') {
  9787. this.sessions[sid].sendTerminate(reason || (!this.sessions[sid].active()) ? 'cancel' : null, text);
  9788. this.sessions[sid].terminate();
  9789. }
  9790. delete this.jid2session[this.sessions[sid].peerjid];
  9791. delete this.sessions[sid];
  9792. }
  9793. } else if (this.sessions.hasOwnProperty(sid)) {
  9794. if (this.sessions[sid].state != 'ended') {
  9795. this.sessions[sid].sendTerminate(reason || (!this.sessions[sid].active()) ? 'cancel' : null, text);
  9796. this.sessions[sid].terminate();
  9797. }
  9798. delete this.jid2session[this.sessions[sid].peerjid];
  9799. delete this.sessions[sid];
  9800. }
  9801. },
  9802. getStunAndTurnCredentials: function () {
  9803. // get stun and turn configuration from server via xep-0215
  9804. // uses time-limited credentials as described in
  9805. // http://tools.ietf.org/html/draft-uberti-behave-turn-rest-00
  9806. //
  9807. // see https://code.google.com/p/prosody-modules/source/browse/mod_turncredentials/mod_turncredentials.lua
  9808. // for a prosody module which implements this
  9809. //
  9810. // currently, this doesn't work with updateIce and therefore credentials with a long
  9811. // validity have to be fetched before creating the peerconnection
  9812. // TODO: implement refresh via updateIce as described in
  9813. // https://code.google.com/p/webrtc/issues/detail?id=1650
  9814. var self = this;
  9815. this.connection.sendIQ(
  9816. $iq({type: 'get', to: this.connection.domain})
  9817. .c('services', {xmlns: 'urn:xmpp:extdisco:1'}).c('service', {host: 'turn.' + this.connection.domain}),
  9818. function (res) {
  9819. var iceservers = [];
  9820. $(res).find('>services>service').each(function (idx, el) {
  9821. el = $(el);
  9822. var dict = {};
  9823. var type = el.attr('type');
  9824. switch (type) {
  9825. case 'stun':
  9826. dict.url = 'stun:' + el.attr('host');
  9827. if (el.attr('port')) {
  9828. dict.url += ':' + el.attr('port');
  9829. }
  9830. iceservers.push(dict);
  9831. break;
  9832. case 'turn':
  9833. case 'turns':
  9834. dict.url = type + ':';
  9835. if (el.attr('username')) { // https://code.google.com/p/webrtc/issues/detail?id=1508
  9836. if (navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./) && parseInt(navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./)[2], 10) < 28) {
  9837. dict.url += el.attr('username') + '@';
  9838. } else {
  9839. dict.username = el.attr('username'); // only works in M28
  9840. }
  9841. }
  9842. dict.url += el.attr('host');
  9843. if (el.attr('port') && el.attr('port') != '3478') {
  9844. dict.url += ':' + el.attr('port');
  9845. }
  9846. if (el.attr('transport') && el.attr('transport') != 'udp') {
  9847. dict.url += '?transport=' + el.attr('transport');
  9848. }
  9849. if (el.attr('password')) {
  9850. dict.credential = el.attr('password');
  9851. }
  9852. iceservers.push(dict);
  9853. break;
  9854. }
  9855. });
  9856. self.ice_config.iceServers = iceservers;
  9857. },
  9858. function (err) {
  9859. logger.warn('getting turn credentials failed', err);
  9860. logger.warn('is mod_turncredentials or similar installed?');
  9861. }
  9862. );
  9863. // implement push?
  9864. },
  9865. /**
  9866. * Returns the data saved in 'updateLog' in a format to be logged.
  9867. */
  9868. getLog: function () {
  9869. var data = {};
  9870. var self = this;
  9871. Object.keys(this.sessions).forEach(function (sid) {
  9872. var session = self.sessions[sid];
  9873. if (session.peerconnection && session.peerconnection.updateLog) {
  9874. // FIXME: should probably be a .dump call
  9875. data["jingle_" + session.sid] = {
  9876. updateLog: session.peerconnection.updateLog,
  9877. stats: session.peerconnection.stats,
  9878. url: window.location.href
  9879. };
  9880. }
  9881. });
  9882. return data;
  9883. }
  9884. });
  9885. };
  9886. }).call(this,"/modules/xmpp/strophe.jingle.js")
  9887. },{"../../service/xmpp/XMPPEvents":85,"../RTC/RTCBrowserType":17,"./JingleSessionPC":28,"jitsi-meet-logger":47}],37:[function(require,module,exports){
  9888. /* global Strophe */
  9889. module.exports = function () {
  9890. Strophe.addConnectionPlugin('logger', {
  9891. // logs raw stanzas and makes them available for download as JSON
  9892. connection: null,
  9893. log: [],
  9894. init: function (conn) {
  9895. this.connection = conn;
  9896. this.connection.rawInput = this.log_incoming.bind(this);
  9897. this.connection.rawOutput = this.log_outgoing.bind(this);
  9898. },
  9899. log_incoming: function (stanza) {
  9900. this.log.push([new Date().getTime(), 'incoming', stanza]);
  9901. },
  9902. log_outgoing: function (stanza) {
  9903. this.log.push([new Date().getTime(), 'outgoing', stanza]);
  9904. }
  9905. });
  9906. };
  9907. },{}],38:[function(require,module,exports){
  9908. (function (__filename){
  9909. /* global $, $iq, Strophe */
  9910. var logger = require("jitsi-meet-logger").getLogger(__filename);
  9911. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  9912. /**
  9913. * Ping every 20 sec
  9914. */
  9915. var PING_INTERVAL = 20000;
  9916. /**
  9917. * Ping timeout error after 15 sec of waiting.
  9918. */
  9919. var PING_TIMEOUT = 15000;
  9920. /**
  9921. * Will close the connection after 3 consecutive ping errors.
  9922. */
  9923. var PING_THRESHOLD = 3;
  9924. /**
  9925. * XEP-0199 ping plugin.
  9926. *
  9927. * Registers "urn:xmpp:ping" namespace under Strophe.NS.PING.
  9928. */
  9929. module.exports = function (XMPP, eventEmitter) {
  9930. Strophe.addConnectionPlugin('ping', {
  9931. connection: null,
  9932. failedPings: 0,
  9933. /**
  9934. * Initializes the plugin. Method called by Strophe.
  9935. * @param connection Strophe connection instance.
  9936. */
  9937. init: function (connection) {
  9938. this.connection = connection;
  9939. Strophe.addNamespace('PING', "urn:xmpp:ping");
  9940. },
  9941. /**
  9942. * Sends "ping" to given <tt>jid</tt>
  9943. * @param jid the JID to which ping request will be sent.
  9944. * @param success callback called on success.
  9945. * @param error callback called on error.
  9946. * @param timeout ms how long are we going to wait for the response. On
  9947. * timeout <tt>error<//t> callback is called with undefined error
  9948. * argument.
  9949. */
  9950. ping: function (jid, success, error, timeout) {
  9951. var iq = $iq({type: 'get', to: jid});
  9952. iq.c('ping', {xmlns: Strophe.NS.PING});
  9953. this.connection.sendIQ(iq, success, error, timeout);
  9954. },
  9955. /**
  9956. * Checks if given <tt>jid</tt> has XEP-0199 ping support.
  9957. * @param jid the JID to be checked for ping support.
  9958. * @param callback function with boolean argument which will be
  9959. * <tt>true</tt> if XEP-0199 ping is supported by given <tt>jid</tt>
  9960. */
  9961. hasPingSupport: function (jid, callback) {
  9962. this.connection.disco.info(
  9963. jid, null,
  9964. function (result) {
  9965. var ping = $(result).find('>>feature[var="urn:xmpp:ping"]');
  9966. callback(ping.length > 0);
  9967. },
  9968. function (error) {
  9969. logger.error("Ping feature discovery error", error);
  9970. callback(false);
  9971. }
  9972. );
  9973. },
  9974. /**
  9975. * Starts to send ping in given interval to specified remote JID.
  9976. * This plugin supports only one such task and <tt>stopInterval</tt>
  9977. * must be called before starting a new one.
  9978. * @param remoteJid remote JID to which ping requests will be sent to.
  9979. * @param interval task interval in ms.
  9980. */
  9981. startInterval: function (remoteJid, interval) {
  9982. if (this.intervalId) {
  9983. logger.error("Ping task scheduled already");
  9984. return;
  9985. }
  9986. if (!interval)
  9987. interval = PING_INTERVAL;
  9988. var self = this;
  9989. this.intervalId = window.setInterval(function () {
  9990. self.ping(remoteJid,
  9991. function (result) {
  9992. // Ping OK
  9993. self.failedPings = 0;
  9994. },
  9995. function (error) {
  9996. self.failedPings += 1;
  9997. logger.error(
  9998. "Ping " + (error ? "error" : "timeout"), error);
  9999. if (self.failedPings >= PING_THRESHOLD) {
  10000. self.connection.disconnect();
  10001. }
  10002. }, PING_TIMEOUT);
  10003. }, interval);
  10004. logger.info("XMPP pings will be sent every " + interval + " ms");
  10005. },
  10006. /**
  10007. * Stops current "ping" interval task.
  10008. */
  10009. stopInterval: function () {
  10010. if (this.intervalId) {
  10011. window.clearInterval(this.intervalId);
  10012. this.intervalId = null;
  10013. this.failedPings = 0;
  10014. logger.info("Ping interval cleared");
  10015. }
  10016. }
  10017. });
  10018. };
  10019. }).call(this,"/modules/xmpp/strophe.ping.js")
  10020. },{"../../service/xmpp/XMPPEvents":85,"jitsi-meet-logger":47}],39:[function(require,module,exports){
  10021. (function (__filename){
  10022. /* jshint -W117 */
  10023. var logger = require("jitsi-meet-logger").getLogger(__filename);
  10024. module.exports = function() {
  10025. Strophe.addConnectionPlugin('rayo',
  10026. {
  10027. RAYO_XMLNS: 'urn:xmpp:rayo:1',
  10028. connection: null,
  10029. init: function (conn) {
  10030. this.connection = conn;
  10031. if (this.connection.disco) {
  10032. this.connection.disco.addFeature('urn:xmpp:rayo:client:1');
  10033. }
  10034. this.connection.addHandler(
  10035. this.onRayo.bind(this),
  10036. this.RAYO_XMLNS, 'iq', 'set', null, null);
  10037. },
  10038. onRayo: function (iq) {
  10039. logger.info("Rayo IQ", iq);
  10040. },
  10041. dial: function (to, from, roomName, roomPass) {
  10042. var self = this;
  10043. var req = $iq(
  10044. {
  10045. type: 'set',
  10046. to: this.connection.emuc.focusMucJid
  10047. }
  10048. );
  10049. req.c('dial',
  10050. {
  10051. xmlns: this.RAYO_XMLNS,
  10052. to: to,
  10053. from: from
  10054. });
  10055. req.c('header',
  10056. {
  10057. name: 'JvbRoomName',
  10058. value: roomName
  10059. }).up();
  10060. if (roomPass !== null && roomPass.length) {
  10061. req.c('header',
  10062. {
  10063. name: 'JvbRoomPassword',
  10064. value: roomPass
  10065. }).up();
  10066. }
  10067. this.connection.sendIQ(
  10068. req,
  10069. function (result) {
  10070. logger.info('Dial result ', result);
  10071. var resource = $(result).find('ref').attr('uri');
  10072. this.call_resource = resource.substr('xmpp:'.length);
  10073. logger.info(
  10074. "Received call resource: " + this.call_resource);
  10075. },
  10076. function (error) {
  10077. logger.info('Dial error ', error);
  10078. }
  10079. );
  10080. },
  10081. hang_up: function () {
  10082. if (!this.call_resource) {
  10083. logger.warn("No call in progress");
  10084. return;
  10085. }
  10086. var self = this;
  10087. var req = $iq(
  10088. {
  10089. type: 'set',
  10090. to: this.call_resource
  10091. }
  10092. );
  10093. req.c('hangup',
  10094. {
  10095. xmlns: this.RAYO_XMLNS
  10096. });
  10097. this.connection.sendIQ(
  10098. req,
  10099. function (result) {
  10100. logger.info('Hangup result ', result);
  10101. self.call_resource = null;
  10102. },
  10103. function (error) {
  10104. logger.info('Hangup error ', error);
  10105. self.call_resource = null;
  10106. }
  10107. );
  10108. }
  10109. }
  10110. );
  10111. };
  10112. }).call(this,"/modules/xmpp/strophe.rayo.js")
  10113. },{"jitsi-meet-logger":47}],40:[function(require,module,exports){
  10114. (function (__filename){
  10115. /* global Strophe */
  10116. /**
  10117. * Strophe logger implementation. Logs from level WARN and above.
  10118. */
  10119. var logger = require("jitsi-meet-logger").getLogger(__filename);
  10120. module.exports = function () {
  10121. Strophe.log = function (level, msg) {
  10122. switch (level) {
  10123. case Strophe.LogLevel.WARN:
  10124. logger.warn("Strophe: " + msg);
  10125. break;
  10126. case Strophe.LogLevel.ERROR:
  10127. case Strophe.LogLevel.FATAL:
  10128. logger.error("Strophe: " + msg);
  10129. break;
  10130. }
  10131. };
  10132. Strophe.getStatusString = function (status) {
  10133. switch (status) {
  10134. case Strophe.Status.ERROR:
  10135. return "ERROR";
  10136. case Strophe.Status.CONNECTING:
  10137. return "CONNECTING";
  10138. case Strophe.Status.CONNFAIL:
  10139. return "CONNFAIL";
  10140. case Strophe.Status.AUTHENTICATING:
  10141. return "AUTHENTICATING";
  10142. case Strophe.Status.AUTHFAIL:
  10143. return "AUTHFAIL";
  10144. case Strophe.Status.CONNECTED:
  10145. return "CONNECTED";
  10146. case Strophe.Status.DISCONNECTED:
  10147. return "DISCONNECTED";
  10148. case Strophe.Status.DISCONNECTING:
  10149. return "DISCONNECTING";
  10150. case Strophe.Status.ATTACHED:
  10151. return "ATTACHED";
  10152. default:
  10153. return "unknown";
  10154. }
  10155. };
  10156. };
  10157. }).call(this,"/modules/xmpp/strophe.util.js")
  10158. },{"jitsi-meet-logger":47}],41:[function(require,module,exports){
  10159. (function (__filename){
  10160. /* global $, APP, config, Strophe*/
  10161. var logger = require("jitsi-meet-logger").getLogger(__filename);
  10162. var EventEmitter = require("events");
  10163. var Pako = require("pako");
  10164. var RTCEvents = require("../../service/RTC/RTCEvents");
  10165. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  10166. var JitsiConnectionErrors = require("../../JitsiConnectionErrors");
  10167. var JitsiConnectionEvents = require("../../JitsiConnectionEvents");
  10168. var RTC = require("../RTC/RTC");
  10169. var authenticatedUser = false;
  10170. function createConnection(bosh) {
  10171. bosh = bosh || '/http-bind';
  10172. return new Strophe.Connection(bosh);
  10173. };
  10174. //!!!!!!!!!! FIXME: ...
  10175. function initStrophePlugins(XMPP)
  10176. {
  10177. require("./strophe.emuc")(XMPP);
  10178. require("./strophe.jingle")(XMPP, XMPP.eventEmitter);
  10179. // require("./strophe.moderate")(XMPP, eventEmitter);
  10180. require("./strophe.util")();
  10181. require("./strophe.ping")(XMPP, XMPP.eventEmitter);
  10182. require("./strophe.rayo")();
  10183. require("./strophe.logger")();
  10184. }
  10185. //!!!!!!!!!! FIXME: ...
  10186. ///**
  10187. // * If given <tt>localStream</tt> is video one this method will advertise it's
  10188. // * video type in MUC presence.
  10189. // * @param localStream new or modified <tt>LocalStream</tt>.
  10190. // */
  10191. //function broadcastLocalVideoType(localStream) {
  10192. // if (localStream.videoType)
  10193. // XMPP.addToPresence('videoType', localStream.videoType);
  10194. //}
  10195. //
  10196. //function registerListeners() {
  10197. // RTC.addStreamListener(
  10198. // broadcastLocalVideoType,
  10199. // StreamEventTypes.EVENT_TYPE_LOCAL_CHANGED
  10200. // );
  10201. // RTC.addListener(RTCEvents.AVAILABLE_DEVICES_CHANGED, function (devices) {
  10202. // XMPP.addToPresence("devices", devices);
  10203. // });
  10204. //}
  10205. function XMPP(options) {
  10206. this.eventEmitter = new EventEmitter();
  10207. this.connection = null;
  10208. this.disconnectInProgress = false;
  10209. this.forceMuted = false;
  10210. this.options = options;
  10211. initStrophePlugins(this);
  10212. // registerListeners();
  10213. this.connection = createConnection(options.bosh);
  10214. }
  10215. XMPP.prototype.getConnection = function(){ return connection; };
  10216. XMPP.prototype._connect = function (jid, password) {
  10217. var self = this;
  10218. // connection.connect() starts the connection process.
  10219. //
  10220. // As the connection process proceeds, the user supplied callback will
  10221. // be triggered multiple times with status updates. The callback should
  10222. // take two arguments - the status code and the error condition.
  10223. //
  10224. // The status code will be one of the values in the Strophe.Status
  10225. // constants. The error condition will be one of the conditions defined
  10226. // in RFC 3920 or the condition ‘strophe-parsererror’.
  10227. //
  10228. // The Parameters wait, hold and route are optional and only relevant
  10229. // for BOSH connections. Please see XEP 124 for a more detailed
  10230. // explanation of the optional parameters.
  10231. //
  10232. // Connection status constants for use by the connection handler
  10233. // callback.
  10234. //
  10235. // Status.ERROR - An error has occurred (websockets specific)
  10236. // Status.CONNECTING - The connection is currently being made
  10237. // Status.CONNFAIL - The connection attempt failed
  10238. // Status.AUTHENTICATING - The connection is authenticating
  10239. // Status.AUTHFAIL - The authentication attempt failed
  10240. // Status.CONNECTED - The connection has succeeded
  10241. // Status.DISCONNECTED - The connection has been terminated
  10242. // Status.DISCONNECTING - The connection is currently being terminated
  10243. // Status.ATTACHED - The connection has been attached
  10244. var anonymousConnectionFailed = false;
  10245. var connectionFailed = false;
  10246. var lastErrorMsg;
  10247. this.connection.connect(jid, password, function (status, msg) {
  10248. logger.log("(TIME) Strophe " + Strophe.getStatusString(status) +
  10249. (msg ? "[" + msg + "]" : "") + "\t:" + window.performance.now());
  10250. if (status === Strophe.Status.CONNECTED) {
  10251. if (self.options.useStunTurn) {
  10252. self.connection.jingle.getStunAndTurnCredentials();
  10253. }
  10254. logger.info("My Jabber ID: " + self.connection.jid);
  10255. // Schedule ping ?
  10256. var pingJid = self.connection.domain;
  10257. self.connection.ping.hasPingSupport(
  10258. pingJid,
  10259. function (hasPing) {
  10260. if (hasPing)
  10261. self.connection.ping.startInterval(pingJid);
  10262. else
  10263. logger.warn("Ping NOT supported by " + pingJid);
  10264. }
  10265. );
  10266. if (password)
  10267. authenticatedUser = true;
  10268. if (self.connection && self.connection.connected &&
  10269. Strophe.getResourceFromJid(self.connection.jid)) {
  10270. // .connected is true while connecting?
  10271. // self.connection.send($pres());
  10272. self.eventEmitter.emit(JitsiConnectionEvents.CONNECTION_ESTABLISHED,
  10273. Strophe.getResourceFromJid(self.connection.jid));
  10274. }
  10275. } else if (status === Strophe.Status.CONNFAIL) {
  10276. if (msg === 'x-strophe-bad-non-anon-jid') {
  10277. anonymousConnectionFailed = true;
  10278. }
  10279. else
  10280. {
  10281. connectionFailed = true;
  10282. }
  10283. lastErrorMsg = msg;
  10284. } else if (status === Strophe.Status.DISCONNECTED) {
  10285. // Stop ping interval
  10286. self.connection.ping.stopInterval();
  10287. self.disconnectInProgress = false;
  10288. if (anonymousConnectionFailed) {
  10289. // prompt user for username and password
  10290. self.eventEmitter.emit(JitsiConnectionEvents.CONNECTION_FAILED,
  10291. JitsiConnectionErrors.PASSWORD_REQUIRED);
  10292. } else if(connectionFailed) {
  10293. self.eventEmitter.emit(JitsiConnectionEvents.CONNECTION_FAILED,
  10294. JitsiConnectionErrors.OTHER_ERROR,
  10295. msg ? msg : lastErrorMsg);
  10296. } else {
  10297. self.eventEmitter.emit(JitsiConnectionEvents.CONNECTION_DISCONNECTED,
  10298. msg ? msg : lastErrorMsg);
  10299. }
  10300. } else if (status === Strophe.Status.AUTHFAIL) {
  10301. // wrong password or username, prompt user
  10302. self.eventEmitter.emit(JitsiConnectionEvents.CONNECTION_FAILED,
  10303. JitsiConnectionErrors.PASSWORD_REQUIRED);
  10304. }
  10305. });
  10306. }
  10307. XMPP.prototype.connect = function (jid, password) {
  10308. if(!jid) {
  10309. var configDomain = this.options.hosts.anonymousdomain || this.options.hosts.domain;
  10310. // Force authenticated domain if room is appended with '?login=true'
  10311. if (this.options.hosts.anonymousdomain &&
  10312. window.location.search.indexOf("login=true") !== -1) {
  10313. configDomain = this.options.hosts.domain;
  10314. }
  10315. jid = configDomain || window.location.hostname;
  10316. }
  10317. return this._connect(jid, password);
  10318. };
  10319. XMPP.prototype.createRoom = function (roomName, options, useNicks, nick) {
  10320. var roomjid = roomName + '@' + this.options.hosts.muc;
  10321. if (useNicks) {
  10322. if (nick) {
  10323. roomjid += '/' + nick;
  10324. } else {
  10325. roomjid += '/' + Strophe.getNodeFromJid(this.connection.jid);
  10326. }
  10327. } else {
  10328. var tmpJid = Strophe.getNodeFromJid(this.connection.jid);
  10329. if(!authenticatedUser)
  10330. tmpJid = tmpJid.substr(0, 8);
  10331. roomjid += '/' + tmpJid;
  10332. }
  10333. return this.connection.emuc.createRoom(roomjid, null, options);
  10334. }
  10335. XMPP.prototype.addListener = function(type, listener) {
  10336. this.eventEmitter.on(type, listener);
  10337. };
  10338. XMPP.prototype.removeListener = function (type, listener) {
  10339. this.eventEmitter.removeListener(type, listener);
  10340. };
  10341. //FIXME: this should work with the room
  10342. XMPP.prototype.leaveRoom = function (jid) {
  10343. var handler = this.connection.jingle.jid2session[jid];
  10344. if (handler && handler.peerconnection) {
  10345. // FIXME: probably removing streams is not required and close() should
  10346. // be enough
  10347. if (RTC.localAudio) {
  10348. handler.peerconnection.removeStream(
  10349. RTC.localAudio.getOriginalStream(), true);
  10350. }
  10351. if (RTC.localVideo) {
  10352. handler.peerconnection.removeStream(
  10353. RTC.localVideo.getOriginalStream(), true);
  10354. }
  10355. handler.peerconnection.close();
  10356. }
  10357. this.eventEmitter.emit(XMPPEvents.DISPOSE_CONFERENCE);
  10358. this.connection.emuc.doLeave(jid);
  10359. };
  10360. /**
  10361. * Sends 'data' as a log message to the focus. Returns true iff a message
  10362. * was sent.
  10363. * @param data
  10364. * @returns {boolean} true iff a message was sent.
  10365. */
  10366. XMPP.prototype.sendLogs = function (data) {
  10367. if(!this.connection.emuc.focusMucJid)
  10368. return false;
  10369. var deflate = true;
  10370. var content = JSON.stringify(data);
  10371. if (deflate) {
  10372. content = String.fromCharCode.apply(null, Pako.deflateRaw(content));
  10373. }
  10374. content = Base64.encode(content);
  10375. // XEP-0337-ish
  10376. var message = $msg({to: this.connection.emuc.focusMucJid, type: 'normal'});
  10377. message.c('log', { xmlns: 'urn:xmpp:eventlog',
  10378. id: 'PeerConnectionStats'});
  10379. message.c('message').t(content).up();
  10380. if (deflate) {
  10381. message.c('tag', {name: "deflated", value: "true"}).up();
  10382. }
  10383. message.up();
  10384. this.connection.send(message);
  10385. return true;
  10386. };
  10387. // Gets the logs from strophe.jingle.
  10388. XMPP.prototype.getJingleLog = function () {
  10389. return this.connection.jingle ? this.connection.jingle.getLog() : {};
  10390. };
  10391. // Gets the logs from strophe.
  10392. XMPP.prototype.getXmppLog = function () {
  10393. return this.connection.logger ? this.connection.logger.log : null;
  10394. };
  10395. XMPP.prototype.dial = function (to, from, roomName,roomPass) {
  10396. this.connection.rayo.dial(to, from, roomName,roomPass);
  10397. };
  10398. XMPP.prototype.setMute = function (jid, mute) {
  10399. this.connection.moderate.setMute(jid, mute);
  10400. };
  10401. XMPP.prototype.eject = function (jid) {
  10402. this.connection.moderate.eject(jid);
  10403. };
  10404. XMPP.prototype.getSessions = function () {
  10405. return this.connection.jingle.sessions;
  10406. };
  10407. XMPP.prototype.disconnect = function () {
  10408. if (this.disconnectInProgress || !this.connection || !this.connection.connected)
  10409. {
  10410. this.eventEmitter.emit(JitsiConnectionEvents.WRONG_STATE);
  10411. return;
  10412. }
  10413. this.disconnectInProgress = true;
  10414. this.connection.disconnect();
  10415. };
  10416. /**
  10417. * Gets the SSRC of local media stream.
  10418. * @param mediaType the media type that tells whether we want to get
  10419. * the SSRC of local audio or video stream.
  10420. * @returns {*} the SSRC number for local media stream or <tt>null</tt> if
  10421. * not available.
  10422. */
  10423. XMPP.prototype.getLocalSSRC = function (mediaType) {
  10424. if (this.connection.jingle.activecall &&
  10425. this.connection.jingle.activecall.peerconnection) {
  10426. return this.connection.jingle.activecall.getLocalSSRC(mediaType);
  10427. } else {
  10428. return null;
  10429. }
  10430. };
  10431. module.exports = XMPP;
  10432. }).call(this,"/modules/xmpp/xmpp.js")
  10433. },{"../../JitsiConnectionErrors":5,"../../JitsiConnectionEvents":6,"../../service/RTC/RTCEvents":79,"../../service/xmpp/XMPPEvents":85,"../RTC/RTC":16,"./strophe.emuc":35,"./strophe.jingle":36,"./strophe.logger":37,"./strophe.ping":38,"./strophe.rayo":39,"./strophe.util":40,"events":43,"jitsi-meet-logger":47,"pako":48}],42:[function(require,module,exports){
  10434. (function (process){
  10435. /*!
  10436. * async
  10437. * https://github.com/caolan/async
  10438. *
  10439. * Copyright 2010-2014 Caolan McMahon
  10440. * Released under the MIT license
  10441. */
  10442. /*jshint onevar: false, indent:4 */
  10443. /*global setImmediate: false, setTimeout: false, console: false */
  10444. (function () {
  10445. var async = {};
  10446. // global on the server, window in the browser
  10447. var root, previous_async;
  10448. root = this;
  10449. if (root != null) {
  10450. previous_async = root.async;
  10451. }
  10452. async.noConflict = function () {
  10453. root.async = previous_async;
  10454. return async;
  10455. };
  10456. function only_once(fn) {
  10457. var called = false;
  10458. return function() {
  10459. if (called) throw new Error("Callback was already called.");
  10460. called = true;
  10461. fn.apply(root, arguments);
  10462. }
  10463. }
  10464. //// cross-browser compatiblity functions ////
  10465. var _toString = Object.prototype.toString;
  10466. var _isArray = Array.isArray || function (obj) {
  10467. return _toString.call(obj) === '[object Array]';
  10468. };
  10469. var _each = function (arr, iterator) {
  10470. if (arr.forEach) {
  10471. return arr.forEach(iterator);
  10472. }
  10473. for (var i = 0; i < arr.length; i += 1) {
  10474. iterator(arr[i], i, arr);
  10475. }
  10476. };
  10477. var _map = function (arr, iterator) {
  10478. if (arr.map) {
  10479. return arr.map(iterator);
  10480. }
  10481. var results = [];
  10482. _each(arr, function (x, i, a) {
  10483. results.push(iterator(x, i, a));
  10484. });
  10485. return results;
  10486. };
  10487. var _reduce = function (arr, iterator, memo) {
  10488. if (arr.reduce) {
  10489. return arr.reduce(iterator, memo);
  10490. }
  10491. _each(arr, function (x, i, a) {
  10492. memo = iterator(memo, x, i, a);
  10493. });
  10494. return memo;
  10495. };
  10496. var _keys = function (obj) {
  10497. if (Object.keys) {
  10498. return Object.keys(obj);
  10499. }
  10500. var keys = [];
  10501. for (var k in obj) {
  10502. if (obj.hasOwnProperty(k)) {
  10503. keys.push(k);
  10504. }
  10505. }
  10506. return keys;
  10507. };
  10508. //// exported async module functions ////
  10509. //// nextTick implementation with browser-compatible fallback ////
  10510. if (typeof process === 'undefined' || !(process.nextTick)) {
  10511. if (typeof setImmediate === 'function') {
  10512. async.nextTick = function (fn) {
  10513. // not a direct alias for IE10 compatibility
  10514. setImmediate(fn);
  10515. };
  10516. async.setImmediate = async.nextTick;
  10517. }
  10518. else {
  10519. async.nextTick = function (fn) {
  10520. setTimeout(fn, 0);
  10521. };
  10522. async.setImmediate = async.nextTick;
  10523. }
  10524. }
  10525. else {
  10526. async.nextTick = process.nextTick;
  10527. if (typeof setImmediate !== 'undefined') {
  10528. async.setImmediate = function (fn) {
  10529. // not a direct alias for IE10 compatibility
  10530. setImmediate(fn);
  10531. };
  10532. }
  10533. else {
  10534. async.setImmediate = async.nextTick;
  10535. }
  10536. }
  10537. async.each = function (arr, iterator, callback) {
  10538. callback = callback || function () {};
  10539. if (!arr.length) {
  10540. return callback();
  10541. }
  10542. var completed = 0;
  10543. _each(arr, function (x) {
  10544. iterator(x, only_once(done) );
  10545. });
  10546. function done(err) {
  10547. if (err) {
  10548. callback(err);
  10549. callback = function () {};
  10550. }
  10551. else {
  10552. completed += 1;
  10553. if (completed >= arr.length) {
  10554. callback();
  10555. }
  10556. }
  10557. }
  10558. };
  10559. async.forEach = async.each;
  10560. async.eachSeries = function (arr, iterator, callback) {
  10561. callback = callback || function () {};
  10562. if (!arr.length) {
  10563. return callback();
  10564. }
  10565. var completed = 0;
  10566. var iterate = function () {
  10567. iterator(arr[completed], function (err) {
  10568. if (err) {
  10569. callback(err);
  10570. callback = function () {};
  10571. }
  10572. else {
  10573. completed += 1;
  10574. if (completed >= arr.length) {
  10575. callback();
  10576. }
  10577. else {
  10578. iterate();
  10579. }
  10580. }
  10581. });
  10582. };
  10583. iterate();
  10584. };
  10585. async.forEachSeries = async.eachSeries;
  10586. async.eachLimit = function (arr, limit, iterator, callback) {
  10587. var fn = _eachLimit(limit);
  10588. fn.apply(null, [arr, iterator, callback]);
  10589. };
  10590. async.forEachLimit = async.eachLimit;
  10591. var _eachLimit = function (limit) {
  10592. return function (arr, iterator, callback) {
  10593. callback = callback || function () {};
  10594. if (!arr.length || limit <= 0) {
  10595. return callback();
  10596. }
  10597. var completed = 0;
  10598. var started = 0;
  10599. var running = 0;
  10600. (function replenish () {
  10601. if (completed >= arr.length) {
  10602. return callback();
  10603. }
  10604. while (running < limit && started < arr.length) {
  10605. started += 1;
  10606. running += 1;
  10607. iterator(arr[started - 1], function (err) {
  10608. if (err) {
  10609. callback(err);
  10610. callback = function () {};
  10611. }
  10612. else {
  10613. completed += 1;
  10614. running -= 1;
  10615. if (completed >= arr.length) {
  10616. callback();
  10617. }
  10618. else {
  10619. replenish();
  10620. }
  10621. }
  10622. });
  10623. }
  10624. })();
  10625. };
  10626. };
  10627. var doParallel = function (fn) {
  10628. return function () {
  10629. var args = Array.prototype.slice.call(arguments);
  10630. return fn.apply(null, [async.each].concat(args));
  10631. };
  10632. };
  10633. var doParallelLimit = function(limit, fn) {
  10634. return function () {
  10635. var args = Array.prototype.slice.call(arguments);
  10636. return fn.apply(null, [_eachLimit(limit)].concat(args));
  10637. };
  10638. };
  10639. var doSeries = function (fn) {
  10640. return function () {
  10641. var args = Array.prototype.slice.call(arguments);
  10642. return fn.apply(null, [async.eachSeries].concat(args));
  10643. };
  10644. };
  10645. var _asyncMap = function (eachfn, arr, iterator, callback) {
  10646. arr = _map(arr, function (x, i) {
  10647. return {index: i, value: x};
  10648. });
  10649. if (!callback) {
  10650. eachfn(arr, function (x, callback) {
  10651. iterator(x.value, function (err) {
  10652. callback(err);
  10653. });
  10654. });
  10655. } else {
  10656. var results = [];
  10657. eachfn(arr, function (x, callback) {
  10658. iterator(x.value, function (err, v) {
  10659. results[x.index] = v;
  10660. callback(err);
  10661. });
  10662. }, function (err) {
  10663. callback(err, results);
  10664. });
  10665. }
  10666. };
  10667. async.map = doParallel(_asyncMap);
  10668. async.mapSeries = doSeries(_asyncMap);
  10669. async.mapLimit = function (arr, limit, iterator, callback) {
  10670. return _mapLimit(limit)(arr, iterator, callback);
  10671. };
  10672. var _mapLimit = function(limit) {
  10673. return doParallelLimit(limit, _asyncMap);
  10674. };
  10675. // reduce only has a series version, as doing reduce in parallel won't
  10676. // work in many situations.
  10677. async.reduce = function (arr, memo, iterator, callback) {
  10678. async.eachSeries(arr, function (x, callback) {
  10679. iterator(memo, x, function (err, v) {
  10680. memo = v;
  10681. callback(err);
  10682. });
  10683. }, function (err) {
  10684. callback(err, memo);
  10685. });
  10686. };
  10687. // inject alias
  10688. async.inject = async.reduce;
  10689. // foldl alias
  10690. async.foldl = async.reduce;
  10691. async.reduceRight = function (arr, memo, iterator, callback) {
  10692. var reversed = _map(arr, function (x) {
  10693. return x;
  10694. }).reverse();
  10695. async.reduce(reversed, memo, iterator, callback);
  10696. };
  10697. // foldr alias
  10698. async.foldr = async.reduceRight;
  10699. var _filter = function (eachfn, arr, iterator, callback) {
  10700. var results = [];
  10701. arr = _map(arr, function (x, i) {
  10702. return {index: i, value: x};
  10703. });
  10704. eachfn(arr, function (x, callback) {
  10705. iterator(x.value, function (v) {
  10706. if (v) {
  10707. results.push(x);
  10708. }
  10709. callback();
  10710. });
  10711. }, function (err) {
  10712. callback(_map(results.sort(function (a, b) {
  10713. return a.index - b.index;
  10714. }), function (x) {
  10715. return x.value;
  10716. }));
  10717. });
  10718. };
  10719. async.filter = doParallel(_filter);
  10720. async.filterSeries = doSeries(_filter);
  10721. // select alias
  10722. async.select = async.filter;
  10723. async.selectSeries = async.filterSeries;
  10724. var _reject = function (eachfn, arr, iterator, callback) {
  10725. var results = [];
  10726. arr = _map(arr, function (x, i) {
  10727. return {index: i, value: x};
  10728. });
  10729. eachfn(arr, function (x, callback) {
  10730. iterator(x.value, function (v) {
  10731. if (!v) {
  10732. results.push(x);
  10733. }
  10734. callback();
  10735. });
  10736. }, function (err) {
  10737. callback(_map(results.sort(function (a, b) {
  10738. return a.index - b.index;
  10739. }), function (x) {
  10740. return x.value;
  10741. }));
  10742. });
  10743. };
  10744. async.reject = doParallel(_reject);
  10745. async.rejectSeries = doSeries(_reject);
  10746. var _detect = function (eachfn, arr, iterator, main_callback) {
  10747. eachfn(arr, function (x, callback) {
  10748. iterator(x, function (result) {
  10749. if (result) {
  10750. main_callback(x);
  10751. main_callback = function () {};
  10752. }
  10753. else {
  10754. callback();
  10755. }
  10756. });
  10757. }, function (err) {
  10758. main_callback();
  10759. });
  10760. };
  10761. async.detect = doParallel(_detect);
  10762. async.detectSeries = doSeries(_detect);
  10763. async.some = function (arr, iterator, main_callback) {
  10764. async.each(arr, function (x, callback) {
  10765. iterator(x, function (v) {
  10766. if (v) {
  10767. main_callback(true);
  10768. main_callback = function () {};
  10769. }
  10770. callback();
  10771. });
  10772. }, function (err) {
  10773. main_callback(false);
  10774. });
  10775. };
  10776. // any alias
  10777. async.any = async.some;
  10778. async.every = function (arr, iterator, main_callback) {
  10779. async.each(arr, function (x, callback) {
  10780. iterator(x, function (v) {
  10781. if (!v) {
  10782. main_callback(false);
  10783. main_callback = function () {};
  10784. }
  10785. callback();
  10786. });
  10787. }, function (err) {
  10788. main_callback(true);
  10789. });
  10790. };
  10791. // all alias
  10792. async.all = async.every;
  10793. async.sortBy = function (arr, iterator, callback) {
  10794. async.map(arr, function (x, callback) {
  10795. iterator(x, function (err, criteria) {
  10796. if (err) {
  10797. callback(err);
  10798. }
  10799. else {
  10800. callback(null, {value: x, criteria: criteria});
  10801. }
  10802. });
  10803. }, function (err, results) {
  10804. if (err) {
  10805. return callback(err);
  10806. }
  10807. else {
  10808. var fn = function (left, right) {
  10809. var a = left.criteria, b = right.criteria;
  10810. return a < b ? -1 : a > b ? 1 : 0;
  10811. };
  10812. callback(null, _map(results.sort(fn), function (x) {
  10813. return x.value;
  10814. }));
  10815. }
  10816. });
  10817. };
  10818. async.auto = function (tasks, callback) {
  10819. callback = callback || function () {};
  10820. var keys = _keys(tasks);
  10821. var remainingTasks = keys.length
  10822. if (!remainingTasks) {
  10823. return callback();
  10824. }
  10825. var results = {};
  10826. var listeners = [];
  10827. var addListener = function (fn) {
  10828. listeners.unshift(fn);
  10829. };
  10830. var removeListener = function (fn) {
  10831. for (var i = 0; i < listeners.length; i += 1) {
  10832. if (listeners[i] === fn) {
  10833. listeners.splice(i, 1);
  10834. return;
  10835. }
  10836. }
  10837. };
  10838. var taskComplete = function () {
  10839. remainingTasks--
  10840. _each(listeners.slice(0), function (fn) {
  10841. fn();
  10842. });
  10843. };
  10844. addListener(function () {
  10845. if (!remainingTasks) {
  10846. var theCallback = callback;
  10847. // prevent final callback from calling itself if it errors
  10848. callback = function () {};
  10849. theCallback(null, results);
  10850. }
  10851. });
  10852. _each(keys, function (k) {
  10853. var task = _isArray(tasks[k]) ? tasks[k]: [tasks[k]];
  10854. var taskCallback = function (err) {
  10855. var args = Array.prototype.slice.call(arguments, 1);
  10856. if (args.length <= 1) {
  10857. args = args[0];
  10858. }
  10859. if (err) {
  10860. var safeResults = {};
  10861. _each(_keys(results), function(rkey) {
  10862. safeResults[rkey] = results[rkey];
  10863. });
  10864. safeResults[k] = args;
  10865. callback(err, safeResults);
  10866. // stop subsequent errors hitting callback multiple times
  10867. callback = function () {};
  10868. }
  10869. else {
  10870. results[k] = args;
  10871. async.setImmediate(taskComplete);
  10872. }
  10873. };
  10874. var requires = task.slice(0, Math.abs(task.length - 1)) || [];
  10875. var ready = function () {
  10876. return _reduce(requires, function (a, x) {
  10877. return (a && results.hasOwnProperty(x));
  10878. }, true) && !results.hasOwnProperty(k);
  10879. };
  10880. if (ready()) {
  10881. task[task.length - 1](taskCallback, results);
  10882. }
  10883. else {
  10884. var listener = function () {
  10885. if (ready()) {
  10886. removeListener(listener);
  10887. task[task.length - 1](taskCallback, results);
  10888. }
  10889. };
  10890. addListener(listener);
  10891. }
  10892. });
  10893. };
  10894. async.retry = function(times, task, callback) {
  10895. var DEFAULT_TIMES = 5;
  10896. var attempts = [];
  10897. // Use defaults if times not passed
  10898. if (typeof times === 'function') {
  10899. callback = task;
  10900. task = times;
  10901. times = DEFAULT_TIMES;
  10902. }
  10903. // Make sure times is a number
  10904. times = parseInt(times, 10) || DEFAULT_TIMES;
  10905. var wrappedTask = function(wrappedCallback, wrappedResults) {
  10906. var retryAttempt = function(task, finalAttempt) {
  10907. return function(seriesCallback) {
  10908. task(function(err, result){
  10909. seriesCallback(!err || finalAttempt, {err: err, result: result});
  10910. }, wrappedResults);
  10911. };
  10912. };
  10913. while (times) {
  10914. attempts.push(retryAttempt(task, !(times-=1)));
  10915. }
  10916. async.series(attempts, function(done, data){
  10917. data = data[data.length - 1];
  10918. (wrappedCallback || callback)(data.err, data.result);
  10919. });
  10920. }
  10921. // If a callback is passed, run this as a controll flow
  10922. return callback ? wrappedTask() : wrappedTask
  10923. };
  10924. async.waterfall = function (tasks, callback) {
  10925. callback = callback || function () {};
  10926. if (!_isArray(tasks)) {
  10927. var err = new Error('First argument to waterfall must be an array of functions');
  10928. return callback(err);
  10929. }
  10930. if (!tasks.length) {
  10931. return callback();
  10932. }
  10933. var wrapIterator = function (iterator) {
  10934. return function (err) {
  10935. if (err) {
  10936. callback.apply(null, arguments);
  10937. callback = function () {};
  10938. }
  10939. else {
  10940. var args = Array.prototype.slice.call(arguments, 1);
  10941. var next = iterator.next();
  10942. if (next) {
  10943. args.push(wrapIterator(next));
  10944. }
  10945. else {
  10946. args.push(callback);
  10947. }
  10948. async.setImmediate(function () {
  10949. iterator.apply(null, args);
  10950. });
  10951. }
  10952. };
  10953. };
  10954. wrapIterator(async.iterator(tasks))();
  10955. };
  10956. var _parallel = function(eachfn, tasks, callback) {
  10957. callback = callback || function () {};
  10958. if (_isArray(tasks)) {
  10959. eachfn.map(tasks, function (fn, callback) {
  10960. if (fn) {
  10961. fn(function (err) {
  10962. var args = Array.prototype.slice.call(arguments, 1);
  10963. if (args.length <= 1) {
  10964. args = args[0];
  10965. }
  10966. callback.call(null, err, args);
  10967. });
  10968. }
  10969. }, callback);
  10970. }
  10971. else {
  10972. var results = {};
  10973. eachfn.each(_keys(tasks), function (k, callback) {
  10974. tasks[k](function (err) {
  10975. var args = Array.prototype.slice.call(arguments, 1);
  10976. if (args.length <= 1) {
  10977. args = args[0];
  10978. }
  10979. results[k] = args;
  10980. callback(err);
  10981. });
  10982. }, function (err) {
  10983. callback(err, results);
  10984. });
  10985. }
  10986. };
  10987. async.parallel = function (tasks, callback) {
  10988. _parallel({ map: async.map, each: async.each }, tasks, callback);
  10989. };
  10990. async.parallelLimit = function(tasks, limit, callback) {
  10991. _parallel({ map: _mapLimit(limit), each: _eachLimit(limit) }, tasks, callback);
  10992. };
  10993. async.series = function (tasks, callback) {
  10994. callback = callback || function () {};
  10995. if (_isArray(tasks)) {
  10996. async.mapSeries(tasks, function (fn, callback) {
  10997. if (fn) {
  10998. fn(function (err) {
  10999. var args = Array.prototype.slice.call(arguments, 1);
  11000. if (args.length <= 1) {
  11001. args = args[0];
  11002. }
  11003. callback.call(null, err, args);
  11004. });
  11005. }
  11006. }, callback);
  11007. }
  11008. else {
  11009. var results = {};
  11010. async.eachSeries(_keys(tasks), function (k, callback) {
  11011. tasks[k](function (err) {
  11012. var args = Array.prototype.slice.call(arguments, 1);
  11013. if (args.length <= 1) {
  11014. args = args[0];
  11015. }
  11016. results[k] = args;
  11017. callback(err);
  11018. });
  11019. }, function (err) {
  11020. callback(err, results);
  11021. });
  11022. }
  11023. };
  11024. async.iterator = function (tasks) {
  11025. var makeCallback = function (index) {
  11026. var fn = function () {
  11027. if (tasks.length) {
  11028. tasks[index].apply(null, arguments);
  11029. }
  11030. return fn.next();
  11031. };
  11032. fn.next = function () {
  11033. return (index < tasks.length - 1) ? makeCallback(index + 1): null;
  11034. };
  11035. return fn;
  11036. };
  11037. return makeCallback(0);
  11038. };
  11039. async.apply = function (fn) {
  11040. var args = Array.prototype.slice.call(arguments, 1);
  11041. return function () {
  11042. return fn.apply(
  11043. null, args.concat(Array.prototype.slice.call(arguments))
  11044. );
  11045. };
  11046. };
  11047. var _concat = function (eachfn, arr, fn, callback) {
  11048. var r = [];
  11049. eachfn(arr, function (x, cb) {
  11050. fn(x, function (err, y) {
  11051. r = r.concat(y || []);
  11052. cb(err);
  11053. });
  11054. }, function (err) {
  11055. callback(err, r);
  11056. });
  11057. };
  11058. async.concat = doParallel(_concat);
  11059. async.concatSeries = doSeries(_concat);
  11060. async.whilst = function (test, iterator, callback) {
  11061. if (test()) {
  11062. iterator(function (err) {
  11063. if (err) {
  11064. return callback(err);
  11065. }
  11066. async.whilst(test, iterator, callback);
  11067. });
  11068. }
  11069. else {
  11070. callback();
  11071. }
  11072. };
  11073. async.doWhilst = function (iterator, test, callback) {
  11074. iterator(function (err) {
  11075. if (err) {
  11076. return callback(err);
  11077. }
  11078. var args = Array.prototype.slice.call(arguments, 1);
  11079. if (test.apply(null, args)) {
  11080. async.doWhilst(iterator, test, callback);
  11081. }
  11082. else {
  11083. callback();
  11084. }
  11085. });
  11086. };
  11087. async.until = function (test, iterator, callback) {
  11088. if (!test()) {
  11089. iterator(function (err) {
  11090. if (err) {
  11091. return callback(err);
  11092. }
  11093. async.until(test, iterator, callback);
  11094. });
  11095. }
  11096. else {
  11097. callback();
  11098. }
  11099. };
  11100. async.doUntil = function (iterator, test, callback) {
  11101. iterator(function (err) {
  11102. if (err) {
  11103. return callback(err);
  11104. }
  11105. var args = Array.prototype.slice.call(arguments, 1);
  11106. if (!test.apply(null, args)) {
  11107. async.doUntil(iterator, test, callback);
  11108. }
  11109. else {
  11110. callback();
  11111. }
  11112. });
  11113. };
  11114. async.queue = function (worker, concurrency) {
  11115. if (concurrency === undefined) {
  11116. concurrency = 1;
  11117. }
  11118. function _insert(q, data, pos, callback) {
  11119. if (!q.started){
  11120. q.started = true;
  11121. }
  11122. if (!_isArray(data)) {
  11123. data = [data];
  11124. }
  11125. if(data.length == 0) {
  11126. // call drain immediately if there are no tasks
  11127. return async.setImmediate(function() {
  11128. if (q.drain) {
  11129. q.drain();
  11130. }
  11131. });
  11132. }
  11133. _each(data, function(task) {
  11134. var item = {
  11135. data: task,
  11136. callback: typeof callback === 'function' ? callback : null
  11137. };
  11138. if (pos) {
  11139. q.tasks.unshift(item);
  11140. } else {
  11141. q.tasks.push(item);
  11142. }
  11143. if (q.saturated && q.tasks.length === q.concurrency) {
  11144. q.saturated();
  11145. }
  11146. async.setImmediate(q.process);
  11147. });
  11148. }
  11149. var workers = 0;
  11150. var q = {
  11151. tasks: [],
  11152. concurrency: concurrency,
  11153. saturated: null,
  11154. empty: null,
  11155. drain: null,
  11156. started: false,
  11157. paused: false,
  11158. push: function (data, callback) {
  11159. _insert(q, data, false, callback);
  11160. },
  11161. kill: function () {
  11162. q.drain = null;
  11163. q.tasks = [];
  11164. },
  11165. unshift: function (data, callback) {
  11166. _insert(q, data, true, callback);
  11167. },
  11168. process: function () {
  11169. if (!q.paused && workers < q.concurrency && q.tasks.length) {
  11170. var task = q.tasks.shift();
  11171. if (q.empty && q.tasks.length === 0) {
  11172. q.empty();
  11173. }
  11174. workers += 1;
  11175. var next = function () {
  11176. workers -= 1;
  11177. if (task.callback) {
  11178. task.callback.apply(task, arguments);
  11179. }
  11180. if (q.drain && q.tasks.length + workers === 0) {
  11181. q.drain();
  11182. }
  11183. q.process();
  11184. };
  11185. var cb = only_once(next);
  11186. worker(task.data, cb);
  11187. }
  11188. },
  11189. length: function () {
  11190. return q.tasks.length;
  11191. },
  11192. running: function () {
  11193. return workers;
  11194. },
  11195. idle: function() {
  11196. return q.tasks.length + workers === 0;
  11197. },
  11198. pause: function () {
  11199. if (q.paused === true) { return; }
  11200. q.paused = true;
  11201. q.process();
  11202. },
  11203. resume: function () {
  11204. if (q.paused === false) { return; }
  11205. q.paused = false;
  11206. q.process();
  11207. }
  11208. };
  11209. return q;
  11210. };
  11211. async.priorityQueue = function (worker, concurrency) {
  11212. function _compareTasks(a, b){
  11213. return a.priority - b.priority;
  11214. };
  11215. function _binarySearch(sequence, item, compare) {
  11216. var beg = -1,
  11217. end = sequence.length - 1;
  11218. while (beg < end) {
  11219. var mid = beg + ((end - beg + 1) >>> 1);
  11220. if (compare(item, sequence[mid]) >= 0) {
  11221. beg = mid;
  11222. } else {
  11223. end = mid - 1;
  11224. }
  11225. }
  11226. return beg;
  11227. }
  11228. function _insert(q, data, priority, callback) {
  11229. if (!q.started){
  11230. q.started = true;
  11231. }
  11232. if (!_isArray(data)) {
  11233. data = [data];
  11234. }
  11235. if(data.length == 0) {
  11236. // call drain immediately if there are no tasks
  11237. return async.setImmediate(function() {
  11238. if (q.drain) {
  11239. q.drain();
  11240. }
  11241. });
  11242. }
  11243. _each(data, function(task) {
  11244. var item = {
  11245. data: task,
  11246. priority: priority,
  11247. callback: typeof callback === 'function' ? callback : null
  11248. };
  11249. q.tasks.splice(_binarySearch(q.tasks, item, _compareTasks) + 1, 0, item);
  11250. if (q.saturated && q.tasks.length === q.concurrency) {
  11251. q.saturated();
  11252. }
  11253. async.setImmediate(q.process);
  11254. });
  11255. }
  11256. // Start with a normal queue
  11257. var q = async.queue(worker, concurrency);
  11258. // Override push to accept second parameter representing priority
  11259. q.push = function (data, priority, callback) {
  11260. _insert(q, data, priority, callback);
  11261. };
  11262. // Remove unshift function
  11263. delete q.unshift;
  11264. return q;
  11265. };
  11266. async.cargo = function (worker, payload) {
  11267. var working = false,
  11268. tasks = [];
  11269. var cargo = {
  11270. tasks: tasks,
  11271. payload: payload,
  11272. saturated: null,
  11273. empty: null,
  11274. drain: null,
  11275. drained: true,
  11276. push: function (data, callback) {
  11277. if (!_isArray(data)) {
  11278. data = [data];
  11279. }
  11280. _each(data, function(task) {
  11281. tasks.push({
  11282. data: task,
  11283. callback: typeof callback === 'function' ? callback : null
  11284. });
  11285. cargo.drained = false;
  11286. if (cargo.saturated && tasks.length === payload) {
  11287. cargo.saturated();
  11288. }
  11289. });
  11290. async.setImmediate(cargo.process);
  11291. },
  11292. process: function process() {
  11293. if (working) return;
  11294. if (tasks.length === 0) {
  11295. if(cargo.drain && !cargo.drained) cargo.drain();
  11296. cargo.drained = true;
  11297. return;
  11298. }
  11299. var ts = typeof payload === 'number'
  11300. ? tasks.splice(0, payload)
  11301. : tasks.splice(0, tasks.length);
  11302. var ds = _map(ts, function (task) {
  11303. return task.data;
  11304. });
  11305. if(cargo.empty) cargo.empty();
  11306. working = true;
  11307. worker(ds, function () {
  11308. working = false;
  11309. var args = arguments;
  11310. _each(ts, function (data) {
  11311. if (data.callback) {
  11312. data.callback.apply(null, args);
  11313. }
  11314. });
  11315. process();
  11316. });
  11317. },
  11318. length: function () {
  11319. return tasks.length;
  11320. },
  11321. running: function () {
  11322. return working;
  11323. }
  11324. };
  11325. return cargo;
  11326. };
  11327. var _console_fn = function (name) {
  11328. return function (fn) {
  11329. var args = Array.prototype.slice.call(arguments, 1);
  11330. fn.apply(null, args.concat([function (err) {
  11331. var args = Array.prototype.slice.call(arguments, 1);
  11332. if (typeof console !== 'undefined') {
  11333. if (err) {
  11334. if (console.error) {
  11335. console.error(err);
  11336. }
  11337. }
  11338. else if (console[name]) {
  11339. _each(args, function (x) {
  11340. console[name](x);
  11341. });
  11342. }
  11343. }
  11344. }]));
  11345. };
  11346. };
  11347. async.log = _console_fn('log');
  11348. async.dir = _console_fn('dir');
  11349. /*async.info = _console_fn('info');
  11350. async.warn = _console_fn('warn');
  11351. async.error = _console_fn('error');*/
  11352. async.memoize = function (fn, hasher) {
  11353. var memo = {};
  11354. var queues = {};
  11355. hasher = hasher || function (x) {
  11356. return x;
  11357. };
  11358. var memoized = function () {
  11359. var args = Array.prototype.slice.call(arguments);
  11360. var callback = args.pop();
  11361. var key = hasher.apply(null, args);
  11362. if (key in memo) {
  11363. async.nextTick(function () {
  11364. callback.apply(null, memo[key]);
  11365. });
  11366. }
  11367. else if (key in queues) {
  11368. queues[key].push(callback);
  11369. }
  11370. else {
  11371. queues[key] = [callback];
  11372. fn.apply(null, args.concat([function () {
  11373. memo[key] = arguments;
  11374. var q = queues[key];
  11375. delete queues[key];
  11376. for (var i = 0, l = q.length; i < l; i++) {
  11377. q[i].apply(null, arguments);
  11378. }
  11379. }]));
  11380. }
  11381. };
  11382. memoized.memo = memo;
  11383. memoized.unmemoized = fn;
  11384. return memoized;
  11385. };
  11386. async.unmemoize = function (fn) {
  11387. return function () {
  11388. return (fn.unmemoized || fn).apply(null, arguments);
  11389. };
  11390. };
  11391. async.times = function (count, iterator, callback) {
  11392. var counter = [];
  11393. for (var i = 0; i < count; i++) {
  11394. counter.push(i);
  11395. }
  11396. return async.map(counter, iterator, callback);
  11397. };
  11398. async.timesSeries = function (count, iterator, callback) {
  11399. var counter = [];
  11400. for (var i = 0; i < count; i++) {
  11401. counter.push(i);
  11402. }
  11403. return async.mapSeries(counter, iterator, callback);
  11404. };
  11405. async.seq = function (/* functions... */) {
  11406. var fns = arguments;
  11407. return function () {
  11408. var that = this;
  11409. var args = Array.prototype.slice.call(arguments);
  11410. var callback = args.pop();
  11411. async.reduce(fns, args, function (newargs, fn, cb) {
  11412. fn.apply(that, newargs.concat([function () {
  11413. var err = arguments[0];
  11414. var nextargs = Array.prototype.slice.call(arguments, 1);
  11415. cb(err, nextargs);
  11416. }]))
  11417. },
  11418. function (err, results) {
  11419. callback.apply(that, [err].concat(results));
  11420. });
  11421. };
  11422. };
  11423. async.compose = function (/* functions... */) {
  11424. return async.seq.apply(null, Array.prototype.reverse.call(arguments));
  11425. };
  11426. var _applyEach = function (eachfn, fns /*args...*/) {
  11427. var go = function () {
  11428. var that = this;
  11429. var args = Array.prototype.slice.call(arguments);
  11430. var callback = args.pop();
  11431. return eachfn(fns, function (fn, cb) {
  11432. fn.apply(that, args.concat([cb]));
  11433. },
  11434. callback);
  11435. };
  11436. if (arguments.length > 2) {
  11437. var args = Array.prototype.slice.call(arguments, 2);
  11438. return go.apply(this, args);
  11439. }
  11440. else {
  11441. return go;
  11442. }
  11443. };
  11444. async.applyEach = doParallel(_applyEach);
  11445. async.applyEachSeries = doSeries(_applyEach);
  11446. async.forever = function (fn, callback) {
  11447. function next(err) {
  11448. if (err) {
  11449. if (callback) {
  11450. return callback(err);
  11451. }
  11452. throw err;
  11453. }
  11454. fn(next);
  11455. }
  11456. next();
  11457. };
  11458. // Node.js
  11459. if (typeof module !== 'undefined' && module.exports) {
  11460. module.exports = async;
  11461. }
  11462. // AMD / RequireJS
  11463. else if (typeof define !== 'undefined' && define.amd) {
  11464. define([], function () {
  11465. return async;
  11466. });
  11467. }
  11468. // included directly via <script> tag
  11469. else {
  11470. root.async = async;
  11471. }
  11472. }());
  11473. }).call(this,require('_process'))
  11474. },{"_process":44}],43:[function(require,module,exports){
  11475. // Copyright Joyent, Inc. and other Node contributors.
  11476. //
  11477. // Permission is hereby granted, free of charge, to any person obtaining a
  11478. // copy of this software and associated documentation files (the
  11479. // "Software"), to deal in the Software without restriction, including
  11480. // without limitation the rights to use, copy, modify, merge, publish,
  11481. // distribute, sublicense, and/or sell copies of the Software, and to permit
  11482. // persons to whom the Software is furnished to do so, subject to the
  11483. // following conditions:
  11484. //
  11485. // The above copyright notice and this permission notice shall be included
  11486. // in all copies or substantial portions of the Software.
  11487. //
  11488. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  11489. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  11490. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  11491. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  11492. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  11493. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  11494. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  11495. function EventEmitter() {
  11496. this._events = this._events || {};
  11497. this._maxListeners = this._maxListeners || undefined;
  11498. }
  11499. module.exports = EventEmitter;
  11500. // Backwards-compat with node 0.10.x
  11501. EventEmitter.EventEmitter = EventEmitter;
  11502. EventEmitter.prototype._events = undefined;
  11503. EventEmitter.prototype._maxListeners = undefined;
  11504. // By default EventEmitters will print a warning if more than 10 listeners are
  11505. // added to it. This is a useful default which helps finding memory leaks.
  11506. EventEmitter.defaultMaxListeners = 10;
  11507. // Obviously not all Emitters should be limited to 10. This function allows
  11508. // that to be increased. Set to zero for unlimited.
  11509. EventEmitter.prototype.setMaxListeners = function(n) {
  11510. if (!isNumber(n) || n < 0 || isNaN(n))
  11511. throw TypeError('n must be a positive number');
  11512. this._maxListeners = n;
  11513. return this;
  11514. };
  11515. EventEmitter.prototype.emit = function(type) {
  11516. var er, handler, len, args, i, listeners;
  11517. if (!this._events)
  11518. this._events = {};
  11519. // If there is no 'error' event listener then throw.
  11520. if (type === 'error') {
  11521. if (!this._events.error ||
  11522. (isObject(this._events.error) && !this._events.error.length)) {
  11523. er = arguments[1];
  11524. if (er instanceof Error) {
  11525. throw er; // Unhandled 'error' event
  11526. }
  11527. throw TypeError('Uncaught, unspecified "error" event.');
  11528. }
  11529. }
  11530. handler = this._events[type];
  11531. if (isUndefined(handler))
  11532. return false;
  11533. if (isFunction(handler)) {
  11534. switch (arguments.length) {
  11535. // fast cases
  11536. case 1:
  11537. handler.call(this);
  11538. break;
  11539. case 2:
  11540. handler.call(this, arguments[1]);
  11541. break;
  11542. case 3:
  11543. handler.call(this, arguments[1], arguments[2]);
  11544. break;
  11545. // slower
  11546. default:
  11547. len = arguments.length;
  11548. args = new Array(len - 1);
  11549. for (i = 1; i < len; i++)
  11550. args[i - 1] = arguments[i];
  11551. handler.apply(this, args);
  11552. }
  11553. } else if (isObject(handler)) {
  11554. len = arguments.length;
  11555. args = new Array(len - 1);
  11556. for (i = 1; i < len; i++)
  11557. args[i - 1] = arguments[i];
  11558. listeners = handler.slice();
  11559. len = listeners.length;
  11560. for (i = 0; i < len; i++)
  11561. listeners[i].apply(this, args);
  11562. }
  11563. return true;
  11564. };
  11565. EventEmitter.prototype.addListener = function(type, listener) {
  11566. var m;
  11567. if (!isFunction(listener))
  11568. throw TypeError('listener must be a function');
  11569. if (!this._events)
  11570. this._events = {};
  11571. // To avoid recursion in the case that type === "newListener"! Before
  11572. // adding it to the listeners, first emit "newListener".
  11573. if (this._events.newListener)
  11574. this.emit('newListener', type,
  11575. isFunction(listener.listener) ?
  11576. listener.listener : listener);
  11577. if (!this._events[type])
  11578. // Optimize the case of one listener. Don't need the extra array object.
  11579. this._events[type] = listener;
  11580. else if (isObject(this._events[type]))
  11581. // If we've already got an array, just append.
  11582. this._events[type].push(listener);
  11583. else
  11584. // Adding the second element, need to change to array.
  11585. this._events[type] = [this._events[type], listener];
  11586. // Check for listener leak
  11587. if (isObject(this._events[type]) && !this._events[type].warned) {
  11588. var m;
  11589. if (!isUndefined(this._maxListeners)) {
  11590. m = this._maxListeners;
  11591. } else {
  11592. m = EventEmitter.defaultMaxListeners;
  11593. }
  11594. if (m && m > 0 && this._events[type].length > m) {
  11595. this._events[type].warned = true;
  11596. console.error('(node) warning: possible EventEmitter memory ' +
  11597. 'leak detected. %d listeners added. ' +
  11598. 'Use emitter.setMaxListeners() to increase limit.',
  11599. this._events[type].length);
  11600. if (typeof console.trace === 'function') {
  11601. // not supported in IE 10
  11602. console.trace();
  11603. }
  11604. }
  11605. }
  11606. return this;
  11607. };
  11608. EventEmitter.prototype.on = EventEmitter.prototype.addListener;
  11609. EventEmitter.prototype.once = function(type, listener) {
  11610. if (!isFunction(listener))
  11611. throw TypeError('listener must be a function');
  11612. var fired = false;
  11613. function g() {
  11614. this.removeListener(type, g);
  11615. if (!fired) {
  11616. fired = true;
  11617. listener.apply(this, arguments);
  11618. }
  11619. }
  11620. g.listener = listener;
  11621. this.on(type, g);
  11622. return this;
  11623. };
  11624. // emits a 'removeListener' event iff the listener was removed
  11625. EventEmitter.prototype.removeListener = function(type, listener) {
  11626. var list, position, length, i;
  11627. if (!isFunction(listener))
  11628. throw TypeError('listener must be a function');
  11629. if (!this._events || !this._events[type])
  11630. return this;
  11631. list = this._events[type];
  11632. length = list.length;
  11633. position = -1;
  11634. if (list === listener ||
  11635. (isFunction(list.listener) && list.listener === listener)) {
  11636. delete this._events[type];
  11637. if (this._events.removeListener)
  11638. this.emit('removeListener', type, listener);
  11639. } else if (isObject(list)) {
  11640. for (i = length; i-- > 0;) {
  11641. if (list[i] === listener ||
  11642. (list[i].listener && list[i].listener === listener)) {
  11643. position = i;
  11644. break;
  11645. }
  11646. }
  11647. if (position < 0)
  11648. return this;
  11649. if (list.length === 1) {
  11650. list.length = 0;
  11651. delete this._events[type];
  11652. } else {
  11653. list.splice(position, 1);
  11654. }
  11655. if (this._events.removeListener)
  11656. this.emit('removeListener', type, listener);
  11657. }
  11658. return this;
  11659. };
  11660. EventEmitter.prototype.removeAllListeners = function(type) {
  11661. var key, listeners;
  11662. if (!this._events)
  11663. return this;
  11664. // not listening for removeListener, no need to emit
  11665. if (!this._events.removeListener) {
  11666. if (arguments.length === 0)
  11667. this._events = {};
  11668. else if (this._events[type])
  11669. delete this._events[type];
  11670. return this;
  11671. }
  11672. // emit removeListener for all listeners on all events
  11673. if (arguments.length === 0) {
  11674. for (key in this._events) {
  11675. if (key === 'removeListener') continue;
  11676. this.removeAllListeners(key);
  11677. }
  11678. this.removeAllListeners('removeListener');
  11679. this._events = {};
  11680. return this;
  11681. }
  11682. listeners = this._events[type];
  11683. if (isFunction(listeners)) {
  11684. this.removeListener(type, listeners);
  11685. } else {
  11686. // LIFO order
  11687. while (listeners.length)
  11688. this.removeListener(type, listeners[listeners.length - 1]);
  11689. }
  11690. delete this._events[type];
  11691. return this;
  11692. };
  11693. EventEmitter.prototype.listeners = function(type) {
  11694. var ret;
  11695. if (!this._events || !this._events[type])
  11696. ret = [];
  11697. else if (isFunction(this._events[type]))
  11698. ret = [this._events[type]];
  11699. else
  11700. ret = this._events[type].slice();
  11701. return ret;
  11702. };
  11703. EventEmitter.listenerCount = function(emitter, type) {
  11704. var ret;
  11705. if (!emitter._events || !emitter._events[type])
  11706. ret = 0;
  11707. else if (isFunction(emitter._events[type]))
  11708. ret = 1;
  11709. else
  11710. ret = emitter._events[type].length;
  11711. return ret;
  11712. };
  11713. function isFunction(arg) {
  11714. return typeof arg === 'function';
  11715. }
  11716. function isNumber(arg) {
  11717. return typeof arg === 'number';
  11718. }
  11719. function isObject(arg) {
  11720. return typeof arg === 'object' && arg !== null;
  11721. }
  11722. function isUndefined(arg) {
  11723. return arg === void 0;
  11724. }
  11725. },{}],44:[function(require,module,exports){
  11726. // shim for using process in browser
  11727. var process = module.exports = {};
  11728. var queue = [];
  11729. var draining = false;
  11730. var currentQueue;
  11731. var queueIndex = -1;
  11732. function cleanUpNextTick() {
  11733. draining = false;
  11734. if (currentQueue.length) {
  11735. queue = currentQueue.concat(queue);
  11736. } else {
  11737. queueIndex = -1;
  11738. }
  11739. if (queue.length) {
  11740. drainQueue();
  11741. }
  11742. }
  11743. function drainQueue() {
  11744. if (draining) {
  11745. return;
  11746. }
  11747. var timeout = setTimeout(cleanUpNextTick);
  11748. draining = true;
  11749. var len = queue.length;
  11750. while(len) {
  11751. currentQueue = queue;
  11752. queue = [];
  11753. while (++queueIndex < len) {
  11754. if (currentQueue) {
  11755. currentQueue[queueIndex].run();
  11756. }
  11757. }
  11758. queueIndex = -1;
  11759. len = queue.length;
  11760. }
  11761. currentQueue = null;
  11762. draining = false;
  11763. clearTimeout(timeout);
  11764. }
  11765. process.nextTick = function (fun) {
  11766. var args = new Array(arguments.length - 1);
  11767. if (arguments.length > 1) {
  11768. for (var i = 1; i < arguments.length; i++) {
  11769. args[i - 1] = arguments[i];
  11770. }
  11771. }
  11772. queue.push(new Item(fun, args));
  11773. if (queue.length === 1 && !draining) {
  11774. setTimeout(drainQueue, 0);
  11775. }
  11776. };
  11777. // v8 likes predictible objects
  11778. function Item(fun, array) {
  11779. this.fun = fun;
  11780. this.array = array;
  11781. }
  11782. Item.prototype.run = function () {
  11783. this.fun.apply(null, this.array);
  11784. };
  11785. process.title = 'browser';
  11786. process.browser = true;
  11787. process.env = {};
  11788. process.argv = [];
  11789. process.version = ''; // empty string to avoid regexp issues
  11790. process.versions = {};
  11791. function noop() {}
  11792. process.on = noop;
  11793. process.addListener = noop;
  11794. process.once = noop;
  11795. process.off = noop;
  11796. process.removeListener = noop;
  11797. process.removeAllListeners = noop;
  11798. process.emit = noop;
  11799. process.binding = function (name) {
  11800. throw new Error('process.binding is not supported');
  11801. };
  11802. process.cwd = function () { return '/' };
  11803. process.chdir = function (dir) {
  11804. throw new Error('process.chdir is not supported');
  11805. };
  11806. process.umask = function() { return 0; };
  11807. },{}],45:[function(require,module,exports){
  11808. (function (process,global){
  11809. /*!
  11810. * @overview es6-promise - a tiny implementation of Promises/A+.
  11811. * @copyright Copyright (c) 2014 Yehuda Katz, Tom Dale, Stefan Penner and contributors (Conversion to ES6 API by Jake Archibald)
  11812. * @license Licensed under MIT license
  11813. * See https://raw.githubusercontent.com/jakearchibald/es6-promise/master/LICENSE
  11814. * @version 3.0.2
  11815. */
  11816. (function() {
  11817. "use strict";
  11818. function lib$es6$promise$utils$$objectOrFunction(x) {
  11819. return typeof x === 'function' || (typeof x === 'object' && x !== null);
  11820. }
  11821. function lib$es6$promise$utils$$isFunction(x) {
  11822. return typeof x === 'function';
  11823. }
  11824. function lib$es6$promise$utils$$isMaybeThenable(x) {
  11825. return typeof x === 'object' && x !== null;
  11826. }
  11827. var lib$es6$promise$utils$$_isArray;
  11828. if (!Array.isArray) {
  11829. lib$es6$promise$utils$$_isArray = function (x) {
  11830. return Object.prototype.toString.call(x) === '[object Array]';
  11831. };
  11832. } else {
  11833. lib$es6$promise$utils$$_isArray = Array.isArray;
  11834. }
  11835. var lib$es6$promise$utils$$isArray = lib$es6$promise$utils$$_isArray;
  11836. var lib$es6$promise$asap$$len = 0;
  11837. var lib$es6$promise$asap$$toString = {}.toString;
  11838. var lib$es6$promise$asap$$vertxNext;
  11839. var lib$es6$promise$asap$$customSchedulerFn;
  11840. var lib$es6$promise$asap$$asap = function asap(callback, arg) {
  11841. lib$es6$promise$asap$$queue[lib$es6$promise$asap$$len] = callback;
  11842. lib$es6$promise$asap$$queue[lib$es6$promise$asap$$len + 1] = arg;
  11843. lib$es6$promise$asap$$len += 2;
  11844. if (lib$es6$promise$asap$$len === 2) {
  11845. // If len is 2, that means that we need to schedule an async flush.
  11846. // If additional callbacks are queued before the queue is flushed, they
  11847. // will be processed by this flush that we are scheduling.
  11848. if (lib$es6$promise$asap$$customSchedulerFn) {
  11849. lib$es6$promise$asap$$customSchedulerFn(lib$es6$promise$asap$$flush);
  11850. } else {
  11851. lib$es6$promise$asap$$scheduleFlush();
  11852. }
  11853. }
  11854. }
  11855. function lib$es6$promise$asap$$setScheduler(scheduleFn) {
  11856. lib$es6$promise$asap$$customSchedulerFn = scheduleFn;
  11857. }
  11858. function lib$es6$promise$asap$$setAsap(asapFn) {
  11859. lib$es6$promise$asap$$asap = asapFn;
  11860. }
  11861. var lib$es6$promise$asap$$browserWindow = (typeof window !== 'undefined') ? window : undefined;
  11862. var lib$es6$promise$asap$$browserGlobal = lib$es6$promise$asap$$browserWindow || {};
  11863. var lib$es6$promise$asap$$BrowserMutationObserver = lib$es6$promise$asap$$browserGlobal.MutationObserver || lib$es6$promise$asap$$browserGlobal.WebKitMutationObserver;
  11864. var lib$es6$promise$asap$$isNode = typeof process !== 'undefined' && {}.toString.call(process) === '[object process]';
  11865. // test for web worker but not in IE10
  11866. var lib$es6$promise$asap$$isWorker = typeof Uint8ClampedArray !== 'undefined' &&
  11867. typeof importScripts !== 'undefined' &&
  11868. typeof MessageChannel !== 'undefined';
  11869. // node
  11870. function lib$es6$promise$asap$$useNextTick() {
  11871. // node version 0.10.x displays a deprecation warning when nextTick is used recursively
  11872. // see https://github.com/cujojs/when/issues/410 for details
  11873. return function() {
  11874. process.nextTick(lib$es6$promise$asap$$flush);
  11875. };
  11876. }
  11877. // vertx
  11878. function lib$es6$promise$asap$$useVertxTimer() {
  11879. return function() {
  11880. lib$es6$promise$asap$$vertxNext(lib$es6$promise$asap$$flush);
  11881. };
  11882. }
  11883. function lib$es6$promise$asap$$useMutationObserver() {
  11884. var iterations = 0;
  11885. var observer = new lib$es6$promise$asap$$BrowserMutationObserver(lib$es6$promise$asap$$flush);
  11886. var node = document.createTextNode('');
  11887. observer.observe(node, { characterData: true });
  11888. return function() {
  11889. node.data = (iterations = ++iterations % 2);
  11890. };
  11891. }
  11892. // web worker
  11893. function lib$es6$promise$asap$$useMessageChannel() {
  11894. var channel = new MessageChannel();
  11895. channel.port1.onmessage = lib$es6$promise$asap$$flush;
  11896. return function () {
  11897. channel.port2.postMessage(0);
  11898. };
  11899. }
  11900. function lib$es6$promise$asap$$useSetTimeout() {
  11901. return function() {
  11902. setTimeout(lib$es6$promise$asap$$flush, 1);
  11903. };
  11904. }
  11905. var lib$es6$promise$asap$$queue = new Array(1000);
  11906. function lib$es6$promise$asap$$flush() {
  11907. for (var i = 0; i < lib$es6$promise$asap$$len; i+=2) {
  11908. var callback = lib$es6$promise$asap$$queue[i];
  11909. var arg = lib$es6$promise$asap$$queue[i+1];
  11910. callback(arg);
  11911. lib$es6$promise$asap$$queue[i] = undefined;
  11912. lib$es6$promise$asap$$queue[i+1] = undefined;
  11913. }
  11914. lib$es6$promise$asap$$len = 0;
  11915. }
  11916. function lib$es6$promise$asap$$attemptVertx() {
  11917. try {
  11918. var r = require;
  11919. var vertx = r('vertx');
  11920. lib$es6$promise$asap$$vertxNext = vertx.runOnLoop || vertx.runOnContext;
  11921. return lib$es6$promise$asap$$useVertxTimer();
  11922. } catch(e) {
  11923. return lib$es6$promise$asap$$useSetTimeout();
  11924. }
  11925. }
  11926. var lib$es6$promise$asap$$scheduleFlush;
  11927. // Decide what async method to use to triggering processing of queued callbacks:
  11928. if (lib$es6$promise$asap$$isNode) {
  11929. lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useNextTick();
  11930. } else if (lib$es6$promise$asap$$BrowserMutationObserver) {
  11931. lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useMutationObserver();
  11932. } else if (lib$es6$promise$asap$$isWorker) {
  11933. lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useMessageChannel();
  11934. } else if (lib$es6$promise$asap$$browserWindow === undefined && typeof require === 'function') {
  11935. lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$attemptVertx();
  11936. } else {
  11937. lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useSetTimeout();
  11938. }
  11939. function lib$es6$promise$$internal$$noop() {}
  11940. var lib$es6$promise$$internal$$PENDING = void 0;
  11941. var lib$es6$promise$$internal$$FULFILLED = 1;
  11942. var lib$es6$promise$$internal$$REJECTED = 2;
  11943. var lib$es6$promise$$internal$$GET_THEN_ERROR = new lib$es6$promise$$internal$$ErrorObject();
  11944. function lib$es6$promise$$internal$$selfFulfillment() {
  11945. return new TypeError("You cannot resolve a promise with itself");
  11946. }
  11947. function lib$es6$promise$$internal$$cannotReturnOwn() {
  11948. return new TypeError('A promises callback cannot return that same promise.');
  11949. }
  11950. function lib$es6$promise$$internal$$getThen(promise) {
  11951. try {
  11952. return promise.then;
  11953. } catch(error) {
  11954. lib$es6$promise$$internal$$GET_THEN_ERROR.error = error;
  11955. return lib$es6$promise$$internal$$GET_THEN_ERROR;
  11956. }
  11957. }
  11958. function lib$es6$promise$$internal$$tryThen(then, value, fulfillmentHandler, rejectionHandler) {
  11959. try {
  11960. then.call(value, fulfillmentHandler, rejectionHandler);
  11961. } catch(e) {
  11962. return e;
  11963. }
  11964. }
  11965. function lib$es6$promise$$internal$$handleForeignThenable(promise, thenable, then) {
  11966. lib$es6$promise$asap$$asap(function(promise) {
  11967. var sealed = false;
  11968. var error = lib$es6$promise$$internal$$tryThen(then, thenable, function(value) {
  11969. if (sealed) { return; }
  11970. sealed = true;
  11971. if (thenable !== value) {
  11972. lib$es6$promise$$internal$$resolve(promise, value);
  11973. } else {
  11974. lib$es6$promise$$internal$$fulfill(promise, value);
  11975. }
  11976. }, function(reason) {
  11977. if (sealed) { return; }
  11978. sealed = true;
  11979. lib$es6$promise$$internal$$reject(promise, reason);
  11980. }, 'Settle: ' + (promise._label || ' unknown promise'));
  11981. if (!sealed && error) {
  11982. sealed = true;
  11983. lib$es6$promise$$internal$$reject(promise, error);
  11984. }
  11985. }, promise);
  11986. }
  11987. function lib$es6$promise$$internal$$handleOwnThenable(promise, thenable) {
  11988. if (thenable._state === lib$es6$promise$$internal$$FULFILLED) {
  11989. lib$es6$promise$$internal$$fulfill(promise, thenable._result);
  11990. } else if (thenable._state === lib$es6$promise$$internal$$REJECTED) {
  11991. lib$es6$promise$$internal$$reject(promise, thenable._result);
  11992. } else {
  11993. lib$es6$promise$$internal$$subscribe(thenable, undefined, function(value) {
  11994. lib$es6$promise$$internal$$resolve(promise, value);
  11995. }, function(reason) {
  11996. lib$es6$promise$$internal$$reject(promise, reason);
  11997. });
  11998. }
  11999. }
  12000. function lib$es6$promise$$internal$$handleMaybeThenable(promise, maybeThenable) {
  12001. if (maybeThenable.constructor === promise.constructor) {
  12002. lib$es6$promise$$internal$$handleOwnThenable(promise, maybeThenable);
  12003. } else {
  12004. var then = lib$es6$promise$$internal$$getThen(maybeThenable);
  12005. if (then === lib$es6$promise$$internal$$GET_THEN_ERROR) {
  12006. lib$es6$promise$$internal$$reject(promise, lib$es6$promise$$internal$$GET_THEN_ERROR.error);
  12007. } else if (then === undefined) {
  12008. lib$es6$promise$$internal$$fulfill(promise, maybeThenable);
  12009. } else if (lib$es6$promise$utils$$isFunction(then)) {
  12010. lib$es6$promise$$internal$$handleForeignThenable(promise, maybeThenable, then);
  12011. } else {
  12012. lib$es6$promise$$internal$$fulfill(promise, maybeThenable);
  12013. }
  12014. }
  12015. }
  12016. function lib$es6$promise$$internal$$resolve(promise, value) {
  12017. if (promise === value) {
  12018. lib$es6$promise$$internal$$reject(promise, lib$es6$promise$$internal$$selfFulfillment());
  12019. } else if (lib$es6$promise$utils$$objectOrFunction(value)) {
  12020. lib$es6$promise$$internal$$handleMaybeThenable(promise, value);
  12021. } else {
  12022. lib$es6$promise$$internal$$fulfill(promise, value);
  12023. }
  12024. }
  12025. function lib$es6$promise$$internal$$publishRejection(promise) {
  12026. if (promise._onerror) {
  12027. promise._onerror(promise._result);
  12028. }
  12029. lib$es6$promise$$internal$$publish(promise);
  12030. }
  12031. function lib$es6$promise$$internal$$fulfill(promise, value) {
  12032. if (promise._state !== lib$es6$promise$$internal$$PENDING) { return; }
  12033. promise._result = value;
  12034. promise._state = lib$es6$promise$$internal$$FULFILLED;
  12035. if (promise._subscribers.length !== 0) {
  12036. lib$es6$promise$asap$$asap(lib$es6$promise$$internal$$publish, promise);
  12037. }
  12038. }
  12039. function lib$es6$promise$$internal$$reject(promise, reason) {
  12040. if (promise._state !== lib$es6$promise$$internal$$PENDING) { return; }
  12041. promise._state = lib$es6$promise$$internal$$REJECTED;
  12042. promise._result = reason;
  12043. lib$es6$promise$asap$$asap(lib$es6$promise$$internal$$publishRejection, promise);
  12044. }
  12045. function lib$es6$promise$$internal$$subscribe(parent, child, onFulfillment, onRejection) {
  12046. var subscribers = parent._subscribers;
  12047. var length = subscribers.length;
  12048. parent._onerror = null;
  12049. subscribers[length] = child;
  12050. subscribers[length + lib$es6$promise$$internal$$FULFILLED] = onFulfillment;
  12051. subscribers[length + lib$es6$promise$$internal$$REJECTED] = onRejection;
  12052. if (length === 0 && parent._state) {
  12053. lib$es6$promise$asap$$asap(lib$es6$promise$$internal$$publish, parent);
  12054. }
  12055. }
  12056. function lib$es6$promise$$internal$$publish(promise) {
  12057. var subscribers = promise._subscribers;
  12058. var settled = promise._state;
  12059. if (subscribers.length === 0) { return; }
  12060. var child, callback, detail = promise._result;
  12061. for (var i = 0; i < subscribers.length; i += 3) {
  12062. child = subscribers[i];
  12063. callback = subscribers[i + settled];
  12064. if (child) {
  12065. lib$es6$promise$$internal$$invokeCallback(settled, child, callback, detail);
  12066. } else {
  12067. callback(detail);
  12068. }
  12069. }
  12070. promise._subscribers.length = 0;
  12071. }
  12072. function lib$es6$promise$$internal$$ErrorObject() {
  12073. this.error = null;
  12074. }
  12075. var lib$es6$promise$$internal$$TRY_CATCH_ERROR = new lib$es6$promise$$internal$$ErrorObject();
  12076. function lib$es6$promise$$internal$$tryCatch(callback, detail) {
  12077. try {
  12078. return callback(detail);
  12079. } catch(e) {
  12080. lib$es6$promise$$internal$$TRY_CATCH_ERROR.error = e;
  12081. return lib$es6$promise$$internal$$TRY_CATCH_ERROR;
  12082. }
  12083. }
  12084. function lib$es6$promise$$internal$$invokeCallback(settled, promise, callback, detail) {
  12085. var hasCallback = lib$es6$promise$utils$$isFunction(callback),
  12086. value, error, succeeded, failed;
  12087. if (hasCallback) {
  12088. value = lib$es6$promise$$internal$$tryCatch(callback, detail);
  12089. if (value === lib$es6$promise$$internal$$TRY_CATCH_ERROR) {
  12090. failed = true;
  12091. error = value.error;
  12092. value = null;
  12093. } else {
  12094. succeeded = true;
  12095. }
  12096. if (promise === value) {
  12097. lib$es6$promise$$internal$$reject(promise, lib$es6$promise$$internal$$cannotReturnOwn());
  12098. return;
  12099. }
  12100. } else {
  12101. value = detail;
  12102. succeeded = true;
  12103. }
  12104. if (promise._state !== lib$es6$promise$$internal$$PENDING) {
  12105. // noop
  12106. } else if (hasCallback && succeeded) {
  12107. lib$es6$promise$$internal$$resolve(promise, value);
  12108. } else if (failed) {
  12109. lib$es6$promise$$internal$$reject(promise, error);
  12110. } else if (settled === lib$es6$promise$$internal$$FULFILLED) {
  12111. lib$es6$promise$$internal$$fulfill(promise, value);
  12112. } else if (settled === lib$es6$promise$$internal$$REJECTED) {
  12113. lib$es6$promise$$internal$$reject(promise, value);
  12114. }
  12115. }
  12116. function lib$es6$promise$$internal$$initializePromise(promise, resolver) {
  12117. try {
  12118. resolver(function resolvePromise(value){
  12119. lib$es6$promise$$internal$$resolve(promise, value);
  12120. }, function rejectPromise(reason) {
  12121. lib$es6$promise$$internal$$reject(promise, reason);
  12122. });
  12123. } catch(e) {
  12124. lib$es6$promise$$internal$$reject(promise, e);
  12125. }
  12126. }
  12127. function lib$es6$promise$enumerator$$Enumerator(Constructor, input) {
  12128. var enumerator = this;
  12129. enumerator._instanceConstructor = Constructor;
  12130. enumerator.promise = new Constructor(lib$es6$promise$$internal$$noop);
  12131. if (enumerator._validateInput(input)) {
  12132. enumerator._input = input;
  12133. enumerator.length = input.length;
  12134. enumerator._remaining = input.length;
  12135. enumerator._init();
  12136. if (enumerator.length === 0) {
  12137. lib$es6$promise$$internal$$fulfill(enumerator.promise, enumerator._result);
  12138. } else {
  12139. enumerator.length = enumerator.length || 0;
  12140. enumerator._enumerate();
  12141. if (enumerator._remaining === 0) {
  12142. lib$es6$promise$$internal$$fulfill(enumerator.promise, enumerator._result);
  12143. }
  12144. }
  12145. } else {
  12146. lib$es6$promise$$internal$$reject(enumerator.promise, enumerator._validationError());
  12147. }
  12148. }
  12149. lib$es6$promise$enumerator$$Enumerator.prototype._validateInput = function(input) {
  12150. return lib$es6$promise$utils$$isArray(input);
  12151. };
  12152. lib$es6$promise$enumerator$$Enumerator.prototype._validationError = function() {
  12153. return new Error('Array Methods must be provided an Array');
  12154. };
  12155. lib$es6$promise$enumerator$$Enumerator.prototype._init = function() {
  12156. this._result = new Array(this.length);
  12157. };
  12158. var lib$es6$promise$enumerator$$default = lib$es6$promise$enumerator$$Enumerator;
  12159. lib$es6$promise$enumerator$$Enumerator.prototype._enumerate = function() {
  12160. var enumerator = this;
  12161. var length = enumerator.length;
  12162. var promise = enumerator.promise;
  12163. var input = enumerator._input;
  12164. for (var i = 0; promise._state === lib$es6$promise$$internal$$PENDING && i < length; i++) {
  12165. enumerator._eachEntry(input[i], i);
  12166. }
  12167. };
  12168. lib$es6$promise$enumerator$$Enumerator.prototype._eachEntry = function(entry, i) {
  12169. var enumerator = this;
  12170. var c = enumerator._instanceConstructor;
  12171. if (lib$es6$promise$utils$$isMaybeThenable(entry)) {
  12172. if (entry.constructor === c && entry._state !== lib$es6$promise$$internal$$PENDING) {
  12173. entry._onerror = null;
  12174. enumerator._settledAt(entry._state, i, entry._result);
  12175. } else {
  12176. enumerator._willSettleAt(c.resolve(entry), i);
  12177. }
  12178. } else {
  12179. enumerator._remaining--;
  12180. enumerator._result[i] = entry;
  12181. }
  12182. };
  12183. lib$es6$promise$enumerator$$Enumerator.prototype._settledAt = function(state, i, value) {
  12184. var enumerator = this;
  12185. var promise = enumerator.promise;
  12186. if (promise._state === lib$es6$promise$$internal$$PENDING) {
  12187. enumerator._remaining--;
  12188. if (state === lib$es6$promise$$internal$$REJECTED) {
  12189. lib$es6$promise$$internal$$reject(promise, value);
  12190. } else {
  12191. enumerator._result[i] = value;
  12192. }
  12193. }
  12194. if (enumerator._remaining === 0) {
  12195. lib$es6$promise$$internal$$fulfill(promise, enumerator._result);
  12196. }
  12197. };
  12198. lib$es6$promise$enumerator$$Enumerator.prototype._willSettleAt = function(promise, i) {
  12199. var enumerator = this;
  12200. lib$es6$promise$$internal$$subscribe(promise, undefined, function(value) {
  12201. enumerator._settledAt(lib$es6$promise$$internal$$FULFILLED, i, value);
  12202. }, function(reason) {
  12203. enumerator._settledAt(lib$es6$promise$$internal$$REJECTED, i, reason);
  12204. });
  12205. };
  12206. function lib$es6$promise$promise$all$$all(entries) {
  12207. return new lib$es6$promise$enumerator$$default(this, entries).promise;
  12208. }
  12209. var lib$es6$promise$promise$all$$default = lib$es6$promise$promise$all$$all;
  12210. function lib$es6$promise$promise$race$$race(entries) {
  12211. /*jshint validthis:true */
  12212. var Constructor = this;
  12213. var promise = new Constructor(lib$es6$promise$$internal$$noop);
  12214. if (!lib$es6$promise$utils$$isArray(entries)) {
  12215. lib$es6$promise$$internal$$reject(promise, new TypeError('You must pass an array to race.'));
  12216. return promise;
  12217. }
  12218. var length = entries.length;
  12219. function onFulfillment(value) {
  12220. lib$es6$promise$$internal$$resolve(promise, value);
  12221. }
  12222. function onRejection(reason) {
  12223. lib$es6$promise$$internal$$reject(promise, reason);
  12224. }
  12225. for (var i = 0; promise._state === lib$es6$promise$$internal$$PENDING && i < length; i++) {
  12226. lib$es6$promise$$internal$$subscribe(Constructor.resolve(entries[i]), undefined, onFulfillment, onRejection);
  12227. }
  12228. return promise;
  12229. }
  12230. var lib$es6$promise$promise$race$$default = lib$es6$promise$promise$race$$race;
  12231. function lib$es6$promise$promise$resolve$$resolve(object) {
  12232. /*jshint validthis:true */
  12233. var Constructor = this;
  12234. if (object && typeof object === 'object' && object.constructor === Constructor) {
  12235. return object;
  12236. }
  12237. var promise = new Constructor(lib$es6$promise$$internal$$noop);
  12238. lib$es6$promise$$internal$$resolve(promise, object);
  12239. return promise;
  12240. }
  12241. var lib$es6$promise$promise$resolve$$default = lib$es6$promise$promise$resolve$$resolve;
  12242. function lib$es6$promise$promise$reject$$reject(reason) {
  12243. /*jshint validthis:true */
  12244. var Constructor = this;
  12245. var promise = new Constructor(lib$es6$promise$$internal$$noop);
  12246. lib$es6$promise$$internal$$reject(promise, reason);
  12247. return promise;
  12248. }
  12249. var lib$es6$promise$promise$reject$$default = lib$es6$promise$promise$reject$$reject;
  12250. var lib$es6$promise$promise$$counter = 0;
  12251. function lib$es6$promise$promise$$needsResolver() {
  12252. throw new TypeError('You must pass a resolver function as the first argument to the promise constructor');
  12253. }
  12254. function lib$es6$promise$promise$$needsNew() {
  12255. throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function.");
  12256. }
  12257. var lib$es6$promise$promise$$default = lib$es6$promise$promise$$Promise;
  12258. /**
  12259. Promise objects represent the eventual result of an asynchronous operation. The
  12260. primary way of interacting with a promise is through its `then` method, which
  12261. registers callbacks to receive either a promise's eventual value or the reason
  12262. why the promise cannot be fulfilled.
  12263. Terminology
  12264. -----------
  12265. - `promise` is an object or function with a `then` method whose behavior conforms to this specification.
  12266. - `thenable` is an object or function that defines a `then` method.
  12267. - `value` is any legal JavaScript value (including undefined, a thenable, or a promise).
  12268. - `exception` is a value that is thrown using the throw statement.
  12269. - `reason` is a value that indicates why a promise was rejected.
  12270. - `settled` the final resting state of a promise, fulfilled or rejected.
  12271. A promise can be in one of three states: pending, fulfilled, or rejected.
  12272. Promises that are fulfilled have a fulfillment value and are in the fulfilled
  12273. state. Promises that are rejected have a rejection reason and are in the
  12274. rejected state. A fulfillment value is never a thenable.
  12275. Promises can also be said to *resolve* a value. If this value is also a
  12276. promise, then the original promise's settled state will match the value's
  12277. settled state. So a promise that *resolves* a promise that rejects will
  12278. itself reject, and a promise that *resolves* a promise that fulfills will
  12279. itself fulfill.
  12280. Basic Usage:
  12281. ------------
  12282. ```js
  12283. var promise = new Promise(function(resolve, reject) {
  12284. // on success
  12285. resolve(value);
  12286. // on failure
  12287. reject(reason);
  12288. });
  12289. promise.then(function(value) {
  12290. // on fulfillment
  12291. }, function(reason) {
  12292. // on rejection
  12293. });
  12294. ```
  12295. Advanced Usage:
  12296. ---------------
  12297. Promises shine when abstracting away asynchronous interactions such as
  12298. `XMLHttpRequest`s.
  12299. ```js
  12300. function getJSON(url) {
  12301. return new Promise(function(resolve, reject){
  12302. var xhr = new XMLHttpRequest();
  12303. xhr.open('GET', url);
  12304. xhr.onreadystatechange = handler;
  12305. xhr.responseType = 'json';
  12306. xhr.setRequestHeader('Accept', 'application/json');
  12307. xhr.send();
  12308. function handler() {
  12309. if (this.readyState === this.DONE) {
  12310. if (this.status === 200) {
  12311. resolve(this.response);
  12312. } else {
  12313. reject(new Error('getJSON: `' + url + '` failed with status: [' + this.status + ']'));
  12314. }
  12315. }
  12316. };
  12317. });
  12318. }
  12319. getJSON('/posts.json').then(function(json) {
  12320. // on fulfillment
  12321. }, function(reason) {
  12322. // on rejection
  12323. });
  12324. ```
  12325. Unlike callbacks, promises are great composable primitives.
  12326. ```js
  12327. Promise.all([
  12328. getJSON('/posts'),
  12329. getJSON('/comments')
  12330. ]).then(function(values){
  12331. values[0] // => postsJSON
  12332. values[1] // => commentsJSON
  12333. return values;
  12334. });
  12335. ```
  12336. @class Promise
  12337. @param {function} resolver
  12338. Useful for tooling.
  12339. @constructor
  12340. */
  12341. function lib$es6$promise$promise$$Promise(resolver) {
  12342. this._id = lib$es6$promise$promise$$counter++;
  12343. this._state = undefined;
  12344. this._result = undefined;
  12345. this._subscribers = [];
  12346. if (lib$es6$promise$$internal$$noop !== resolver) {
  12347. if (!lib$es6$promise$utils$$isFunction(resolver)) {
  12348. lib$es6$promise$promise$$needsResolver();
  12349. }
  12350. if (!(this instanceof lib$es6$promise$promise$$Promise)) {
  12351. lib$es6$promise$promise$$needsNew();
  12352. }
  12353. lib$es6$promise$$internal$$initializePromise(this, resolver);
  12354. }
  12355. }
  12356. lib$es6$promise$promise$$Promise.all = lib$es6$promise$promise$all$$default;
  12357. lib$es6$promise$promise$$Promise.race = lib$es6$promise$promise$race$$default;
  12358. lib$es6$promise$promise$$Promise.resolve = lib$es6$promise$promise$resolve$$default;
  12359. lib$es6$promise$promise$$Promise.reject = lib$es6$promise$promise$reject$$default;
  12360. lib$es6$promise$promise$$Promise._setScheduler = lib$es6$promise$asap$$setScheduler;
  12361. lib$es6$promise$promise$$Promise._setAsap = lib$es6$promise$asap$$setAsap;
  12362. lib$es6$promise$promise$$Promise._asap = lib$es6$promise$asap$$asap;
  12363. lib$es6$promise$promise$$Promise.prototype = {
  12364. constructor: lib$es6$promise$promise$$Promise,
  12365. /**
  12366. The primary way of interacting with a promise is through its `then` method,
  12367. which registers callbacks to receive either a promise's eventual value or the
  12368. reason why the promise cannot be fulfilled.
  12369. ```js
  12370. findUser().then(function(user){
  12371. // user is available
  12372. }, function(reason){
  12373. // user is unavailable, and you are given the reason why
  12374. });
  12375. ```
  12376. Chaining
  12377. --------
  12378. The return value of `then` is itself a promise. This second, 'downstream'
  12379. promise is resolved with the return value of the first promise's fulfillment
  12380. or rejection handler, or rejected if the handler throws an exception.
  12381. ```js
  12382. findUser().then(function (user) {
  12383. return user.name;
  12384. }, function (reason) {
  12385. return 'default name';
  12386. }).then(function (userName) {
  12387. // If `findUser` fulfilled, `userName` will be the user's name, otherwise it
  12388. // will be `'default name'`
  12389. });
  12390. findUser().then(function (user) {
  12391. throw new Error('Found user, but still unhappy');
  12392. }, function (reason) {
  12393. throw new Error('`findUser` rejected and we're unhappy');
  12394. }).then(function (value) {
  12395. // never reached
  12396. }, function (reason) {
  12397. // if `findUser` fulfilled, `reason` will be 'Found user, but still unhappy'.
  12398. // If `findUser` rejected, `reason` will be '`findUser` rejected and we're unhappy'.
  12399. });
  12400. ```
  12401. If the downstream promise does not specify a rejection handler, rejection reasons will be propagated further downstream.
  12402. ```js
  12403. findUser().then(function (user) {
  12404. throw new PedagogicalException('Upstream error');
  12405. }).then(function (value) {
  12406. // never reached
  12407. }).then(function (value) {
  12408. // never reached
  12409. }, function (reason) {
  12410. // The `PedgagocialException` is propagated all the way down to here
  12411. });
  12412. ```
  12413. Assimilation
  12414. ------------
  12415. Sometimes the value you want to propagate to a downstream promise can only be
  12416. retrieved asynchronously. This can be achieved by returning a promise in the
  12417. fulfillment or rejection handler. The downstream promise will then be pending
  12418. until the returned promise is settled. This is called *assimilation*.
  12419. ```js
  12420. findUser().then(function (user) {
  12421. return findCommentsByAuthor(user);
  12422. }).then(function (comments) {
  12423. // The user's comments are now available
  12424. });
  12425. ```
  12426. If the assimliated promise rejects, then the downstream promise will also reject.
  12427. ```js
  12428. findUser().then(function (user) {
  12429. return findCommentsByAuthor(user);
  12430. }).then(function (comments) {
  12431. // If `findCommentsByAuthor` fulfills, we'll have the value here
  12432. }, function (reason) {
  12433. // If `findCommentsByAuthor` rejects, we'll have the reason here
  12434. });
  12435. ```
  12436. Simple Example
  12437. --------------
  12438. Synchronous Example
  12439. ```javascript
  12440. var result;
  12441. try {
  12442. result = findResult();
  12443. // success
  12444. } catch(reason) {
  12445. // failure
  12446. }
  12447. ```
  12448. Errback Example
  12449. ```js
  12450. findResult(function(result, err){
  12451. if (err) {
  12452. // failure
  12453. } else {
  12454. // success
  12455. }
  12456. });
  12457. ```
  12458. Promise Example;
  12459. ```javascript
  12460. findResult().then(function(result){
  12461. // success
  12462. }, function(reason){
  12463. // failure
  12464. });
  12465. ```
  12466. Advanced Example
  12467. --------------
  12468. Synchronous Example
  12469. ```javascript
  12470. var author, books;
  12471. try {
  12472. author = findAuthor();
  12473. books = findBooksByAuthor(author);
  12474. // success
  12475. } catch(reason) {
  12476. // failure
  12477. }
  12478. ```
  12479. Errback Example
  12480. ```js
  12481. function foundBooks(books) {
  12482. }
  12483. function failure(reason) {
  12484. }
  12485. findAuthor(function(author, err){
  12486. if (err) {
  12487. failure(err);
  12488. // failure
  12489. } else {
  12490. try {
  12491. findBoooksByAuthor(author, function(books, err) {
  12492. if (err) {
  12493. failure(err);
  12494. } else {
  12495. try {
  12496. foundBooks(books);
  12497. } catch(reason) {
  12498. failure(reason);
  12499. }
  12500. }
  12501. });
  12502. } catch(error) {
  12503. failure(err);
  12504. }
  12505. // success
  12506. }
  12507. });
  12508. ```
  12509. Promise Example;
  12510. ```javascript
  12511. findAuthor().
  12512. then(findBooksByAuthor).
  12513. then(function(books){
  12514. // found books
  12515. }).catch(function(reason){
  12516. // something went wrong
  12517. });
  12518. ```
  12519. @method then
  12520. @param {Function} onFulfilled
  12521. @param {Function} onRejected
  12522. Useful for tooling.
  12523. @return {Promise}
  12524. */
  12525. then: function(onFulfillment, onRejection) {
  12526. var parent = this;
  12527. var state = parent._state;
  12528. if (state === lib$es6$promise$$internal$$FULFILLED && !onFulfillment || state === lib$es6$promise$$internal$$REJECTED && !onRejection) {
  12529. return this;
  12530. }
  12531. var child = new this.constructor(lib$es6$promise$$internal$$noop);
  12532. var result = parent._result;
  12533. if (state) {
  12534. var callback = arguments[state - 1];
  12535. lib$es6$promise$asap$$asap(function(){
  12536. lib$es6$promise$$internal$$invokeCallback(state, child, callback, result);
  12537. });
  12538. } else {
  12539. lib$es6$promise$$internal$$subscribe(parent, child, onFulfillment, onRejection);
  12540. }
  12541. return child;
  12542. },
  12543. /**
  12544. `catch` is simply sugar for `then(undefined, onRejection)` which makes it the same
  12545. as the catch block of a try/catch statement.
  12546. ```js
  12547. function findAuthor(){
  12548. throw new Error('couldn't find that author');
  12549. }
  12550. // synchronous
  12551. try {
  12552. findAuthor();
  12553. } catch(reason) {
  12554. // something went wrong
  12555. }
  12556. // async with promises
  12557. findAuthor().catch(function(reason){
  12558. // something went wrong
  12559. });
  12560. ```
  12561. @method catch
  12562. @param {Function} onRejection
  12563. Useful for tooling.
  12564. @return {Promise}
  12565. */
  12566. 'catch': function(onRejection) {
  12567. return this.then(null, onRejection);
  12568. }
  12569. };
  12570. function lib$es6$promise$polyfill$$polyfill() {
  12571. var local;
  12572. if (typeof global !== 'undefined') {
  12573. local = global;
  12574. } else if (typeof self !== 'undefined') {
  12575. local = self;
  12576. } else {
  12577. try {
  12578. local = Function('return this')();
  12579. } catch (e) {
  12580. throw new Error('polyfill failed because global object is unavailable in this environment');
  12581. }
  12582. }
  12583. var P = local.Promise;
  12584. if (P && Object.prototype.toString.call(P.resolve()) === '[object Promise]' && !P.cast) {
  12585. return;
  12586. }
  12587. local.Promise = lib$es6$promise$promise$$default;
  12588. }
  12589. var lib$es6$promise$polyfill$$default = lib$es6$promise$polyfill$$polyfill;
  12590. var lib$es6$promise$umd$$ES6Promise = {
  12591. 'Promise': lib$es6$promise$promise$$default,
  12592. 'polyfill': lib$es6$promise$polyfill$$default
  12593. };
  12594. /* global define:true module:true window: true */
  12595. if (typeof define === 'function' && define['amd']) {
  12596. define(function() { return lib$es6$promise$umd$$ES6Promise; });
  12597. } else if (typeof module !== 'undefined' && module['exports']) {
  12598. module['exports'] = lib$es6$promise$umd$$ES6Promise;
  12599. } else if (typeof this !== 'undefined') {
  12600. this['ES6Promise'] = lib$es6$promise$umd$$ES6Promise;
  12601. }
  12602. lib$es6$promise$polyfill$$default();
  12603. }).call(this);
  12604. }).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  12605. },{"_process":44}],46:[function(require,module,exports){
  12606. /* Copyright @ 2015 Atlassian Pty Ltd
  12607. *
  12608. * Licensed under the Apache License, Version 2.0 (the "License");
  12609. * you may not use this file except in compliance with the License.
  12610. * You may obtain a copy of the License at
  12611. *
  12612. * http://www.apache.org/licenses/LICENSE-2.0
  12613. *
  12614. * Unless required by applicable law or agreed to in writing, software
  12615. * distributed under the License is distributed on an "AS IS" BASIS,
  12616. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12617. * See the License for the specific language governing permissions and
  12618. * limitations under the License.
  12619. */
  12620. /**
  12621. * Ordered log levels.
  12622. */
  12623. var levels = {
  12624. "trace": 0,
  12625. "debug": 1,
  12626. "info": 2,
  12627. "log": 3,
  12628. "warn": 4,
  12629. "error": 5
  12630. };
  12631. /**
  12632. * Parses Error's object stack trace and extracts information about the last
  12633. * caller before the log method was called.
  12634. * @returns JS object with info about the caller - method name, file location,
  12635. * line and column.
  12636. */
  12637. function getCallerInfo() {
  12638. var callerInfo = {
  12639. methodName: "",
  12640. fileLocation: "",
  12641. line: null,
  12642. column: null
  12643. };
  12644. //gets the part of the stack without the logger wrappers
  12645. var error = new Error();
  12646. var stack = error.stack? error.stack.split("\n") : [];
  12647. if(!stack || stack.length < 1) {
  12648. return callerInfo;
  12649. }
  12650. var m = null;
  12651. if(stack[3]) {
  12652. m = stack[3].match(/\s*at\s*(.+?)\s*\((\S*)\s*:(\d*)\s*:(\d*)\)/);
  12653. }
  12654. if(!m || m.length <= 4) {
  12655. //Firefox && Safari
  12656. if(stack[2].indexOf("log@") === 0){
  12657. //Safari
  12658. callerInfo.methodName = stack[3].substr(0, stack[3].indexOf("@"));
  12659. } else {
  12660. //Firefox
  12661. callerInfo.methodName = stack[2].substr(0, stack[2].indexOf("@"));
  12662. }
  12663. return callerInfo;
  12664. }
  12665. callerInfo.methodName = m[1];
  12666. callerInfo.fileLocation = m[2];
  12667. callerInfo.line = m[3];
  12668. callerInfo.column = m[4];
  12669. return callerInfo;
  12670. }
  12671. /**
  12672. * Logs messages using the transports and level from the logger.
  12673. * @param logger a logger instance.
  12674. * @param level the log level of the message. See the levels variable.
  12675. * @param arguments array with arguments that will be logged.
  12676. */
  12677. function log() {
  12678. var logger = arguments[0], level = arguments[1],
  12679. args = Array.prototype.slice.call(arguments, 2);
  12680. if(levels[level] <= logger.level) {
  12681. return;
  12682. }
  12683. var callerInfo = getCallerInfo();
  12684. for(var i = 0; i < logger.transports.length; i++) {
  12685. var t = logger.transports[i];
  12686. var l = t[level];
  12687. if(l && typeof(l) === "function") {
  12688. l.bind(t, logger.id? "[" + logger.id + "]" : "", "<" + callerInfo.methodName + ">: ")
  12689. .apply(t, args);
  12690. }
  12691. }
  12692. }
  12693. /**
  12694. *
  12695. * Constructs new logger object.
  12696. * @param level the logging level for the new logger
  12697. * @param id optional identifier for the logger instance.
  12698. * @param transports optional list of handlers(objects) for the logs.
  12699. * The handlers must support - log, warn, error, debug, info, trace.
  12700. * @param format optional (NOT implemented) string.
  12701. */
  12702. function Logger(level, id, transports, format) {
  12703. this.id = id;
  12704. this.format = format;
  12705. if(!this.transports) {
  12706. this.transports = [];
  12707. this.transports.push(Logger.consoleTransport);
  12708. }
  12709. this.level = levels[level];
  12710. var methods = Object.keys(levels);
  12711. for(var i = 0; i < methods.length; i++){
  12712. this[methods[i]] =
  12713. log.bind(null, this, methods[i]);
  12714. }
  12715. }
  12716. /**
  12717. * Sets the log level for the logger.
  12718. * @param level the new log level.
  12719. */
  12720. Logger.prototype.setLevel = function (level) {
  12721. this.level = levels[level];
  12722. };
  12723. module.exports = Logger;
  12724. /**
  12725. * The default transport - console
  12726. */
  12727. Logger.consoleTransport = console;
  12728. /**
  12729. * Enum for the supported log levels.
  12730. */
  12731. Logger.levels = {
  12732. TRACE: "trace",
  12733. DEBUG: "debug",
  12734. INFO: "info",
  12735. LOG: "log",
  12736. WARN: "warn",
  12737. ERROR: "error"
  12738. };
  12739. },{}],47:[function(require,module,exports){
  12740. /* Copyright @ 2015 Atlassian Pty Ltd
  12741. *
  12742. * Licensed under the Apache License, Version 2.0 (the "License");
  12743. * you may not use this file except in compliance with the License.
  12744. * You may obtain a copy of the License at
  12745. *
  12746. * http://www.apache.org/licenses/LICENSE-2.0
  12747. *
  12748. * Unless required by applicable law or agreed to in writing, software
  12749. * distributed under the License is distributed on an "AS IS" BASIS,
  12750. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12751. * See the License for the specific language governing permissions and
  12752. * limitations under the License.
  12753. */
  12754. var Logger = require("./Logger");
  12755. /**
  12756. * Map with the created loggers with ID.
  12757. */
  12758. var idLoggers = {};
  12759. /**
  12760. * Array with the loggers without id.
  12761. */
  12762. var loggers = [];
  12763. /**
  12764. * Log level for the lbrary.
  12765. */
  12766. var curLevel = Logger.levels.TRACE;
  12767. module.exports = {
  12768. /**
  12769. * Creates new logger.
  12770. * @arguments the same as Logger constructor
  12771. */
  12772. getLogger: function(id, transports, format) {
  12773. var logger = new Logger(curLevel, id, transports, format);
  12774. if(id) {
  12775. idLoggers[id] = idLoggers[id] || [];
  12776. idLoggers[id].push(logger);
  12777. } else {
  12778. loggers.push(logger);
  12779. }
  12780. return logger;
  12781. },
  12782. /**
  12783. * Changes the log level for the existing loggers by id.
  12784. * @param level the new log level.
  12785. * @param id if specified the level will be changed only for loggers with the
  12786. * same id. Otherwise the operation will affect all loggers that don't
  12787. * have id.
  12788. */
  12789. setLogLevelById: function(level, id) {
  12790. var l = id? (idLoggers[id] || []) : loggers;
  12791. for(var i = 0; i < l.length; i++) {
  12792. l[i].setLevel(level);
  12793. }
  12794. },
  12795. /**
  12796. * Changes the log level for all existing loggers.
  12797. * @param level the new log level.
  12798. */
  12799. setLogLevel: function (level) {
  12800. curLevel = level;
  12801. var i = 0;
  12802. for(; i < loggers.length; i++) {
  12803. loggers[i].setLevel(level);
  12804. }
  12805. for(var id in idLoggers) {
  12806. var l = idLoggers[id] || [];
  12807. for(i = 0; i < l.length; i++) {
  12808. l[i].setLevel(level);
  12809. }
  12810. }
  12811. },
  12812. /**
  12813. * The supported log levels.
  12814. */
  12815. levels: Logger.levels
  12816. };
  12817. },{"./Logger":46}],48:[function(require,module,exports){
  12818. // Top level file is just a mixin of submodules & constants
  12819. 'use strict';
  12820. var assign = require('./lib/utils/common').assign;
  12821. var deflate = require('./lib/deflate');
  12822. var inflate = require('./lib/inflate');
  12823. var constants = require('./lib/zlib/constants');
  12824. var pako = {};
  12825. assign(pako, deflate, inflate, constants);
  12826. module.exports = pako;
  12827. },{"./lib/deflate":49,"./lib/inflate":50,"./lib/utils/common":51,"./lib/zlib/constants":54}],49:[function(require,module,exports){
  12828. 'use strict';
  12829. var zlib_deflate = require('./zlib/deflate.js');
  12830. var utils = require('./utils/common');
  12831. var strings = require('./utils/strings');
  12832. var msg = require('./zlib/messages');
  12833. var zstream = require('./zlib/zstream');
  12834. var toString = Object.prototype.toString;
  12835. /* Public constants ==========================================================*/
  12836. /* ===========================================================================*/
  12837. var Z_NO_FLUSH = 0;
  12838. var Z_FINISH = 4;
  12839. var Z_OK = 0;
  12840. var Z_STREAM_END = 1;
  12841. var Z_SYNC_FLUSH = 2;
  12842. var Z_DEFAULT_COMPRESSION = -1;
  12843. var Z_DEFAULT_STRATEGY = 0;
  12844. var Z_DEFLATED = 8;
  12845. /* ===========================================================================*/
  12846. /**
  12847. * class Deflate
  12848. *
  12849. * Generic JS-style wrapper for zlib calls. If you don't need
  12850. * streaming behaviour - use more simple functions: [[deflate]],
  12851. * [[deflateRaw]] and [[gzip]].
  12852. **/
  12853. /* internal
  12854. * Deflate.chunks -> Array
  12855. *
  12856. * Chunks of output data, if [[Deflate#onData]] not overriden.
  12857. **/
  12858. /**
  12859. * Deflate.result -> Uint8Array|Array
  12860. *
  12861. * Compressed result, generated by default [[Deflate#onData]]
  12862. * and [[Deflate#onEnd]] handlers. Filled after you push last chunk
  12863. * (call [[Deflate#push]] with `Z_FINISH` / `true` param) or if you
  12864. * push a chunk with explicit flush (call [[Deflate#push]] with
  12865. * `Z_SYNC_FLUSH` param).
  12866. **/
  12867. /**
  12868. * Deflate.err -> Number
  12869. *
  12870. * Error code after deflate finished. 0 (Z_OK) on success.
  12871. * You will not need it in real life, because deflate errors
  12872. * are possible only on wrong options or bad `onData` / `onEnd`
  12873. * custom handlers.
  12874. **/
  12875. /**
  12876. * Deflate.msg -> String
  12877. *
  12878. * Error message, if [[Deflate.err]] != 0
  12879. **/
  12880. /**
  12881. * new Deflate(options)
  12882. * - options (Object): zlib deflate options.
  12883. *
  12884. * Creates new deflator instance with specified params. Throws exception
  12885. * on bad params. Supported options:
  12886. *
  12887. * - `level`
  12888. * - `windowBits`
  12889. * - `memLevel`
  12890. * - `strategy`
  12891. *
  12892. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  12893. * for more information on these.
  12894. *
  12895. * Additional options, for internal needs:
  12896. *
  12897. * - `chunkSize` - size of generated data chunks (16K by default)
  12898. * - `raw` (Boolean) - do raw deflate
  12899. * - `gzip` (Boolean) - create gzip wrapper
  12900. * - `to` (String) - if equal to 'string', then result will be "binary string"
  12901. * (each char code [0..255])
  12902. * - `header` (Object) - custom header for gzip
  12903. * - `text` (Boolean) - true if compressed data believed to be text
  12904. * - `time` (Number) - modification time, unix timestamp
  12905. * - `os` (Number) - operation system code
  12906. * - `extra` (Array) - array of bytes with extra data (max 65536)
  12907. * - `name` (String) - file name (binary string)
  12908. * - `comment` (String) - comment (binary string)
  12909. * - `hcrc` (Boolean) - true if header crc should be added
  12910. *
  12911. * ##### Example:
  12912. *
  12913. * ```javascript
  12914. * var pako = require('pako')
  12915. * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
  12916. * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
  12917. *
  12918. * var deflate = new pako.Deflate({ level: 3});
  12919. *
  12920. * deflate.push(chunk1, false);
  12921. * deflate.push(chunk2, true); // true -> last chunk
  12922. *
  12923. * if (deflate.err) { throw new Error(deflate.err); }
  12924. *
  12925. * console.log(deflate.result);
  12926. * ```
  12927. **/
  12928. var Deflate = function(options) {
  12929. this.options = utils.assign({
  12930. level: Z_DEFAULT_COMPRESSION,
  12931. method: Z_DEFLATED,
  12932. chunkSize: 16384,
  12933. windowBits: 15,
  12934. memLevel: 8,
  12935. strategy: Z_DEFAULT_STRATEGY,
  12936. to: ''
  12937. }, options || {});
  12938. var opt = this.options;
  12939. if (opt.raw && (opt.windowBits > 0)) {
  12940. opt.windowBits = -opt.windowBits;
  12941. }
  12942. else if (opt.gzip && (opt.windowBits > 0) && (opt.windowBits < 16)) {
  12943. opt.windowBits += 16;
  12944. }
  12945. this.err = 0; // error code, if happens (0 = Z_OK)
  12946. this.msg = ''; // error message
  12947. this.ended = false; // used to avoid multiple onEnd() calls
  12948. this.chunks = []; // chunks of compressed data
  12949. this.strm = new zstream();
  12950. this.strm.avail_out = 0;
  12951. var status = zlib_deflate.deflateInit2(
  12952. this.strm,
  12953. opt.level,
  12954. opt.method,
  12955. opt.windowBits,
  12956. opt.memLevel,
  12957. opt.strategy
  12958. );
  12959. if (status !== Z_OK) {
  12960. throw new Error(msg[status]);
  12961. }
  12962. if (opt.header) {
  12963. zlib_deflate.deflateSetHeader(this.strm, opt.header);
  12964. }
  12965. };
  12966. /**
  12967. * Deflate#push(data[, mode]) -> Boolean
  12968. * - data (Uint8Array|Array|ArrayBuffer|String): input data. Strings will be
  12969. * converted to utf8 byte sequence.
  12970. * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
  12971. * See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH.
  12972. *
  12973. * Sends input data to deflate pipe, generating [[Deflate#onData]] calls with
  12974. * new compressed chunks. Returns `true` on success. The last data block must have
  12975. * mode Z_FINISH (or `true`). That will flush internal pending buffers and call
  12976. * [[Deflate#onEnd]]. For interim explicit flushes (without ending the stream) you
  12977. * can use mode Z_SYNC_FLUSH, keeping the compression context.
  12978. *
  12979. * On fail call [[Deflate#onEnd]] with error code and return false.
  12980. *
  12981. * We strongly recommend to use `Uint8Array` on input for best speed (output
  12982. * array format is detected automatically). Also, don't skip last param and always
  12983. * use the same type in your code (boolean or number). That will improve JS speed.
  12984. *
  12985. * For regular `Array`-s make sure all elements are [0..255].
  12986. *
  12987. * ##### Example
  12988. *
  12989. * ```javascript
  12990. * push(chunk, false); // push one of data chunks
  12991. * ...
  12992. * push(chunk, true); // push last chunk
  12993. * ```
  12994. **/
  12995. Deflate.prototype.push = function(data, mode) {
  12996. var strm = this.strm;
  12997. var chunkSize = this.options.chunkSize;
  12998. var status, _mode;
  12999. if (this.ended) { return false; }
  13000. _mode = (mode === ~~mode) ? mode : ((mode === true) ? Z_FINISH : Z_NO_FLUSH);
  13001. // Convert data if needed
  13002. if (typeof data === 'string') {
  13003. // If we need to compress text, change encoding to utf8.
  13004. strm.input = strings.string2buf(data);
  13005. } else if (toString.call(data) === '[object ArrayBuffer]') {
  13006. strm.input = new Uint8Array(data);
  13007. } else {
  13008. strm.input = data;
  13009. }
  13010. strm.next_in = 0;
  13011. strm.avail_in = strm.input.length;
  13012. do {
  13013. if (strm.avail_out === 0) {
  13014. strm.output = new utils.Buf8(chunkSize);
  13015. strm.next_out = 0;
  13016. strm.avail_out = chunkSize;
  13017. }
  13018. status = zlib_deflate.deflate(strm, _mode); /* no bad return value */
  13019. if (status !== Z_STREAM_END && status !== Z_OK) {
  13020. this.onEnd(status);
  13021. this.ended = true;
  13022. return false;
  13023. }
  13024. if (strm.avail_out === 0 || (strm.avail_in === 0 && (_mode === Z_FINISH || _mode === Z_SYNC_FLUSH))) {
  13025. if (this.options.to === 'string') {
  13026. this.onData(strings.buf2binstring(utils.shrinkBuf(strm.output, strm.next_out)));
  13027. } else {
  13028. this.onData(utils.shrinkBuf(strm.output, strm.next_out));
  13029. }
  13030. }
  13031. } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== Z_STREAM_END);
  13032. // Finalize on the last chunk.
  13033. if (_mode === Z_FINISH) {
  13034. status = zlib_deflate.deflateEnd(this.strm);
  13035. this.onEnd(status);
  13036. this.ended = true;
  13037. return status === Z_OK;
  13038. }
  13039. // callback interim results if Z_SYNC_FLUSH.
  13040. if (_mode === Z_SYNC_FLUSH) {
  13041. this.onEnd(Z_OK);
  13042. strm.avail_out = 0;
  13043. return true;
  13044. }
  13045. return true;
  13046. };
  13047. /**
  13048. * Deflate#onData(chunk) -> Void
  13049. * - chunk (Uint8Array|Array|String): ouput data. Type of array depends
  13050. * on js engine support. When string output requested, each chunk
  13051. * will be string.
  13052. *
  13053. * By default, stores data blocks in `chunks[]` property and glue
  13054. * those in `onEnd`. Override this handler, if you need another behaviour.
  13055. **/
  13056. Deflate.prototype.onData = function(chunk) {
  13057. this.chunks.push(chunk);
  13058. };
  13059. /**
  13060. * Deflate#onEnd(status) -> Void
  13061. * - status (Number): deflate status. 0 (Z_OK) on success,
  13062. * other if not.
  13063. *
  13064. * Called once after you tell deflate that the input stream is
  13065. * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH)
  13066. * or if an error happened. By default - join collected chunks,
  13067. * free memory and fill `results` / `err` properties.
  13068. **/
  13069. Deflate.prototype.onEnd = function(status) {
  13070. // On success - join
  13071. if (status === Z_OK) {
  13072. if (this.options.to === 'string') {
  13073. this.result = this.chunks.join('');
  13074. } else {
  13075. this.result = utils.flattenChunks(this.chunks);
  13076. }
  13077. }
  13078. this.chunks = [];
  13079. this.err = status;
  13080. this.msg = this.strm.msg;
  13081. };
  13082. /**
  13083. * deflate(data[, options]) -> Uint8Array|Array|String
  13084. * - data (Uint8Array|Array|String): input data to compress.
  13085. * - options (Object): zlib deflate options.
  13086. *
  13087. * Compress `data` with deflate alrorythm and `options`.
  13088. *
  13089. * Supported options are:
  13090. *
  13091. * - level
  13092. * - windowBits
  13093. * - memLevel
  13094. * - strategy
  13095. *
  13096. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  13097. * for more information on these.
  13098. *
  13099. * Sugar (options):
  13100. *
  13101. * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
  13102. * negative windowBits implicitly.
  13103. * - `to` (String) - if equal to 'string', then result will be "binary string"
  13104. * (each char code [0..255])
  13105. *
  13106. * ##### Example:
  13107. *
  13108. * ```javascript
  13109. * var pako = require('pako')
  13110. * , data = Uint8Array([1,2,3,4,5,6,7,8,9]);
  13111. *
  13112. * console.log(pako.deflate(data));
  13113. * ```
  13114. **/
  13115. function deflate(input, options) {
  13116. var deflator = new Deflate(options);
  13117. deflator.push(input, true);
  13118. // That will never happens, if you don't cheat with options :)
  13119. if (deflator.err) { throw deflator.msg; }
  13120. return deflator.result;
  13121. }
  13122. /**
  13123. * deflateRaw(data[, options]) -> Uint8Array|Array|String
  13124. * - data (Uint8Array|Array|String): input data to compress.
  13125. * - options (Object): zlib deflate options.
  13126. *
  13127. * The same as [[deflate]], but creates raw data, without wrapper
  13128. * (header and adler32 crc).
  13129. **/
  13130. function deflateRaw(input, options) {
  13131. options = options || {};
  13132. options.raw = true;
  13133. return deflate(input, options);
  13134. }
  13135. /**
  13136. * gzip(data[, options]) -> Uint8Array|Array|String
  13137. * - data (Uint8Array|Array|String): input data to compress.
  13138. * - options (Object): zlib deflate options.
  13139. *
  13140. * The same as [[deflate]], but create gzip wrapper instead of
  13141. * deflate one.
  13142. **/
  13143. function gzip(input, options) {
  13144. options = options || {};
  13145. options.gzip = true;
  13146. return deflate(input, options);
  13147. }
  13148. exports.Deflate = Deflate;
  13149. exports.deflate = deflate;
  13150. exports.deflateRaw = deflateRaw;
  13151. exports.gzip = gzip;
  13152. },{"./utils/common":51,"./utils/strings":52,"./zlib/deflate.js":56,"./zlib/messages":61,"./zlib/zstream":63}],50:[function(require,module,exports){
  13153. 'use strict';
  13154. var zlib_inflate = require('./zlib/inflate.js');
  13155. var utils = require('./utils/common');
  13156. var strings = require('./utils/strings');
  13157. var c = require('./zlib/constants');
  13158. var msg = require('./zlib/messages');
  13159. var zstream = require('./zlib/zstream');
  13160. var gzheader = require('./zlib/gzheader');
  13161. var toString = Object.prototype.toString;
  13162. /**
  13163. * class Inflate
  13164. *
  13165. * Generic JS-style wrapper for zlib calls. If you don't need
  13166. * streaming behaviour - use more simple functions: [[inflate]]
  13167. * and [[inflateRaw]].
  13168. **/
  13169. /* internal
  13170. * inflate.chunks -> Array
  13171. *
  13172. * Chunks of output data, if [[Inflate#onData]] not overriden.
  13173. **/
  13174. /**
  13175. * Inflate.result -> Uint8Array|Array|String
  13176. *
  13177. * Uncompressed result, generated by default [[Inflate#onData]]
  13178. * and [[Inflate#onEnd]] handlers. Filled after you push last chunk
  13179. * (call [[Inflate#push]] with `Z_FINISH` / `true` param) or if you
  13180. * push a chunk with explicit flush (call [[Inflate#push]] with
  13181. * `Z_SYNC_FLUSH` param).
  13182. **/
  13183. /**
  13184. * Inflate.err -> Number
  13185. *
  13186. * Error code after inflate finished. 0 (Z_OK) on success.
  13187. * Should be checked if broken data possible.
  13188. **/
  13189. /**
  13190. * Inflate.msg -> String
  13191. *
  13192. * Error message, if [[Inflate.err]] != 0
  13193. **/
  13194. /**
  13195. * new Inflate(options)
  13196. * - options (Object): zlib inflate options.
  13197. *
  13198. * Creates new inflator instance with specified params. Throws exception
  13199. * on bad params. Supported options:
  13200. *
  13201. * - `windowBits`
  13202. *
  13203. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  13204. * for more information on these.
  13205. *
  13206. * Additional options, for internal needs:
  13207. *
  13208. * - `chunkSize` - size of generated data chunks (16K by default)
  13209. * - `raw` (Boolean) - do raw inflate
  13210. * - `to` (String) - if equal to 'string', then result will be converted
  13211. * from utf8 to utf16 (javascript) string. When string output requested,
  13212. * chunk length can differ from `chunkSize`, depending on content.
  13213. *
  13214. * By default, when no options set, autodetect deflate/gzip data format via
  13215. * wrapper header.
  13216. *
  13217. * ##### Example:
  13218. *
  13219. * ```javascript
  13220. * var pako = require('pako')
  13221. * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
  13222. * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
  13223. *
  13224. * var inflate = new pako.Inflate({ level: 3});
  13225. *
  13226. * inflate.push(chunk1, false);
  13227. * inflate.push(chunk2, true); // true -> last chunk
  13228. *
  13229. * if (inflate.err) { throw new Error(inflate.err); }
  13230. *
  13231. * console.log(inflate.result);
  13232. * ```
  13233. **/
  13234. var Inflate = function(options) {
  13235. this.options = utils.assign({
  13236. chunkSize: 16384,
  13237. windowBits: 0,
  13238. to: ''
  13239. }, options || {});
  13240. var opt = this.options;
  13241. // Force window size for `raw` data, if not set directly,
  13242. // because we have no header for autodetect.
  13243. if (opt.raw && (opt.windowBits >= 0) && (opt.windowBits < 16)) {
  13244. opt.windowBits = -opt.windowBits;
  13245. if (opt.windowBits === 0) { opt.windowBits = -15; }
  13246. }
  13247. // If `windowBits` not defined (and mode not raw) - set autodetect flag for gzip/deflate
  13248. if ((opt.windowBits >= 0) && (opt.windowBits < 16) &&
  13249. !(options && options.windowBits)) {
  13250. opt.windowBits += 32;
  13251. }
  13252. // Gzip header has no info about windows size, we can do autodetect only
  13253. // for deflate. So, if window size not set, force it to max when gzip possible
  13254. if ((opt.windowBits > 15) && (opt.windowBits < 48)) {
  13255. // bit 3 (16) -> gzipped data
  13256. // bit 4 (32) -> autodetect gzip/deflate
  13257. if ((opt.windowBits & 15) === 0) {
  13258. opt.windowBits |= 15;
  13259. }
  13260. }
  13261. this.err = 0; // error code, if happens (0 = Z_OK)
  13262. this.msg = ''; // error message
  13263. this.ended = false; // used to avoid multiple onEnd() calls
  13264. this.chunks = []; // chunks of compressed data
  13265. this.strm = new zstream();
  13266. this.strm.avail_out = 0;
  13267. var status = zlib_inflate.inflateInit2(
  13268. this.strm,
  13269. opt.windowBits
  13270. );
  13271. if (status !== c.Z_OK) {
  13272. throw new Error(msg[status]);
  13273. }
  13274. this.header = new gzheader();
  13275. zlib_inflate.inflateGetHeader(this.strm, this.header);
  13276. };
  13277. /**
  13278. * Inflate#push(data[, mode]) -> Boolean
  13279. * - data (Uint8Array|Array|ArrayBuffer|String): input data
  13280. * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
  13281. * See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH.
  13282. *
  13283. * Sends input data to inflate pipe, generating [[Inflate#onData]] calls with
  13284. * new output chunks. Returns `true` on success. The last data block must have
  13285. * mode Z_FINISH (or `true`). That will flush internal pending buffers and call
  13286. * [[Inflate#onEnd]]. For interim explicit flushes (without ending the stream) you
  13287. * can use mode Z_SYNC_FLUSH, keeping the decompression context.
  13288. *
  13289. * On fail call [[Inflate#onEnd]] with error code and return false.
  13290. *
  13291. * We strongly recommend to use `Uint8Array` on input for best speed (output
  13292. * format is detected automatically). Also, don't skip last param and always
  13293. * use the same type in your code (boolean or number). That will improve JS speed.
  13294. *
  13295. * For regular `Array`-s make sure all elements are [0..255].
  13296. *
  13297. * ##### Example
  13298. *
  13299. * ```javascript
  13300. * push(chunk, false); // push one of data chunks
  13301. * ...
  13302. * push(chunk, true); // push last chunk
  13303. * ```
  13304. **/
  13305. Inflate.prototype.push = function(data, mode) {
  13306. var strm = this.strm;
  13307. var chunkSize = this.options.chunkSize;
  13308. var status, _mode;
  13309. var next_out_utf8, tail, utf8str;
  13310. // Flag to properly process Z_BUF_ERROR on testing inflate call
  13311. // when we check that all output data was flushed.
  13312. var allowBufError = false;
  13313. if (this.ended) { return false; }
  13314. _mode = (mode === ~~mode) ? mode : ((mode === true) ? c.Z_FINISH : c.Z_NO_FLUSH);
  13315. // Convert data if needed
  13316. if (typeof data === 'string') {
  13317. // Only binary strings can be decompressed on practice
  13318. strm.input = strings.binstring2buf(data);
  13319. } else if (toString.call(data) === '[object ArrayBuffer]') {
  13320. strm.input = new Uint8Array(data);
  13321. } else {
  13322. strm.input = data;
  13323. }
  13324. strm.next_in = 0;
  13325. strm.avail_in = strm.input.length;
  13326. do {
  13327. if (strm.avail_out === 0) {
  13328. strm.output = new utils.Buf8(chunkSize);
  13329. strm.next_out = 0;
  13330. strm.avail_out = chunkSize;
  13331. }
  13332. status = zlib_inflate.inflate(strm, c.Z_NO_FLUSH); /* no bad return value */
  13333. if (status === c.Z_BUF_ERROR && allowBufError === true) {
  13334. status = c.Z_OK;
  13335. allowBufError = false;
  13336. }
  13337. if (status !== c.Z_STREAM_END && status !== c.Z_OK) {
  13338. this.onEnd(status);
  13339. this.ended = true;
  13340. return false;
  13341. }
  13342. if (strm.next_out) {
  13343. if (strm.avail_out === 0 || status === c.Z_STREAM_END || (strm.avail_in === 0 && (_mode === c.Z_FINISH || _mode === c.Z_SYNC_FLUSH))) {
  13344. if (this.options.to === 'string') {
  13345. next_out_utf8 = strings.utf8border(strm.output, strm.next_out);
  13346. tail = strm.next_out - next_out_utf8;
  13347. utf8str = strings.buf2string(strm.output, next_out_utf8);
  13348. // move tail
  13349. strm.next_out = tail;
  13350. strm.avail_out = chunkSize - tail;
  13351. if (tail) { utils.arraySet(strm.output, strm.output, next_out_utf8, tail, 0); }
  13352. this.onData(utf8str);
  13353. } else {
  13354. this.onData(utils.shrinkBuf(strm.output, strm.next_out));
  13355. }
  13356. }
  13357. }
  13358. // When no more input data, we should check that internal inflate buffers
  13359. // are flushed. The only way to do it when avail_out = 0 - run one more
  13360. // inflate pass. But if output data not exists, inflate return Z_BUF_ERROR.
  13361. // Here we set flag to process this error properly.
  13362. //
  13363. // NOTE. Deflate does not return error in this case and does not needs such
  13364. // logic.
  13365. if (strm.avail_in === 0 && strm.avail_out === 0) {
  13366. allowBufError = true;
  13367. }
  13368. } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== c.Z_STREAM_END);
  13369. if (status === c.Z_STREAM_END) {
  13370. _mode = c.Z_FINISH;
  13371. }
  13372. // Finalize on the last chunk.
  13373. if (_mode === c.Z_FINISH) {
  13374. status = zlib_inflate.inflateEnd(this.strm);
  13375. this.onEnd(status);
  13376. this.ended = true;
  13377. return status === c.Z_OK;
  13378. }
  13379. // callback interim results if Z_SYNC_FLUSH.
  13380. if (_mode === c.Z_SYNC_FLUSH) {
  13381. this.onEnd(c.Z_OK);
  13382. strm.avail_out = 0;
  13383. return true;
  13384. }
  13385. return true;
  13386. };
  13387. /**
  13388. * Inflate#onData(chunk) -> Void
  13389. * - chunk (Uint8Array|Array|String): ouput data. Type of array depends
  13390. * on js engine support. When string output requested, each chunk
  13391. * will be string.
  13392. *
  13393. * By default, stores data blocks in `chunks[]` property and glue
  13394. * those in `onEnd`. Override this handler, if you need another behaviour.
  13395. **/
  13396. Inflate.prototype.onData = function(chunk) {
  13397. this.chunks.push(chunk);
  13398. };
  13399. /**
  13400. * Inflate#onEnd(status) -> Void
  13401. * - status (Number): inflate status. 0 (Z_OK) on success,
  13402. * other if not.
  13403. *
  13404. * Called either after you tell inflate that the input stream is
  13405. * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH)
  13406. * or if an error happened. By default - join collected chunks,
  13407. * free memory and fill `results` / `err` properties.
  13408. **/
  13409. Inflate.prototype.onEnd = function(status) {
  13410. // On success - join
  13411. if (status === c.Z_OK) {
  13412. if (this.options.to === 'string') {
  13413. // Glue & convert here, until we teach pako to send
  13414. // utf8 alligned strings to onData
  13415. this.result = this.chunks.join('');
  13416. } else {
  13417. this.result = utils.flattenChunks(this.chunks);
  13418. }
  13419. }
  13420. this.chunks = [];
  13421. this.err = status;
  13422. this.msg = this.strm.msg;
  13423. };
  13424. /**
  13425. * inflate(data[, options]) -> Uint8Array|Array|String
  13426. * - data (Uint8Array|Array|String): input data to decompress.
  13427. * - options (Object): zlib inflate options.
  13428. *
  13429. * Decompress `data` with inflate/ungzip and `options`. Autodetect
  13430. * format via wrapper header by default. That's why we don't provide
  13431. * separate `ungzip` method.
  13432. *
  13433. * Supported options are:
  13434. *
  13435. * - windowBits
  13436. *
  13437. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  13438. * for more information.
  13439. *
  13440. * Sugar (options):
  13441. *
  13442. * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
  13443. * negative windowBits implicitly.
  13444. * - `to` (String) - if equal to 'string', then result will be converted
  13445. * from utf8 to utf16 (javascript) string. When string output requested,
  13446. * chunk length can differ from `chunkSize`, depending on content.
  13447. *
  13448. *
  13449. * ##### Example:
  13450. *
  13451. * ```javascript
  13452. * var pako = require('pako')
  13453. * , input = pako.deflate([1,2,3,4,5,6,7,8,9])
  13454. * , output;
  13455. *
  13456. * try {
  13457. * output = pako.inflate(input);
  13458. * } catch (err)
  13459. * console.log(err);
  13460. * }
  13461. * ```
  13462. **/
  13463. function inflate(input, options) {
  13464. var inflator = new Inflate(options);
  13465. inflator.push(input, true);
  13466. // That will never happens, if you don't cheat with options :)
  13467. if (inflator.err) { throw inflator.msg; }
  13468. return inflator.result;
  13469. }
  13470. /**
  13471. * inflateRaw(data[, options]) -> Uint8Array|Array|String
  13472. * - data (Uint8Array|Array|String): input data to decompress.
  13473. * - options (Object): zlib inflate options.
  13474. *
  13475. * The same as [[inflate]], but creates raw data, without wrapper
  13476. * (header and adler32 crc).
  13477. **/
  13478. function inflateRaw(input, options) {
  13479. options = options || {};
  13480. options.raw = true;
  13481. return inflate(input, options);
  13482. }
  13483. /**
  13484. * ungzip(data[, options]) -> Uint8Array|Array|String
  13485. * - data (Uint8Array|Array|String): input data to decompress.
  13486. * - options (Object): zlib inflate options.
  13487. *
  13488. * Just shortcut to [[inflate]], because it autodetects format
  13489. * by header.content. Done for convenience.
  13490. **/
  13491. exports.Inflate = Inflate;
  13492. exports.inflate = inflate;
  13493. exports.inflateRaw = inflateRaw;
  13494. exports.ungzip = inflate;
  13495. },{"./utils/common":51,"./utils/strings":52,"./zlib/constants":54,"./zlib/gzheader":57,"./zlib/inflate.js":59,"./zlib/messages":61,"./zlib/zstream":63}],51:[function(require,module,exports){
  13496. 'use strict';
  13497. var TYPED_OK = (typeof Uint8Array !== 'undefined') &&
  13498. (typeof Uint16Array !== 'undefined') &&
  13499. (typeof Int32Array !== 'undefined');
  13500. exports.assign = function (obj /*from1, from2, from3, ...*/) {
  13501. var sources = Array.prototype.slice.call(arguments, 1);
  13502. while (sources.length) {
  13503. var source = sources.shift();
  13504. if (!source) { continue; }
  13505. if (typeof source !== 'object') {
  13506. throw new TypeError(source + 'must be non-object');
  13507. }
  13508. for (var p in source) {
  13509. if (source.hasOwnProperty(p)) {
  13510. obj[p] = source[p];
  13511. }
  13512. }
  13513. }
  13514. return obj;
  13515. };
  13516. // reduce buffer size, avoiding mem copy
  13517. exports.shrinkBuf = function (buf, size) {
  13518. if (buf.length === size) { return buf; }
  13519. if (buf.subarray) { return buf.subarray(0, size); }
  13520. buf.length = size;
  13521. return buf;
  13522. };
  13523. var fnTyped = {
  13524. arraySet: function (dest, src, src_offs, len, dest_offs) {
  13525. if (src.subarray && dest.subarray) {
  13526. dest.set(src.subarray(src_offs, src_offs+len), dest_offs);
  13527. return;
  13528. }
  13529. // Fallback to ordinary array
  13530. for (var i=0; i<len; i++) {
  13531. dest[dest_offs + i] = src[src_offs + i];
  13532. }
  13533. },
  13534. // Join array of chunks to single array.
  13535. flattenChunks: function(chunks) {
  13536. var i, l, len, pos, chunk, result;
  13537. // calculate data length
  13538. len = 0;
  13539. for (i=0, l=chunks.length; i<l; i++) {
  13540. len += chunks[i].length;
  13541. }
  13542. // join chunks
  13543. result = new Uint8Array(len);
  13544. pos = 0;
  13545. for (i=0, l=chunks.length; i<l; i++) {
  13546. chunk = chunks[i];
  13547. result.set(chunk, pos);
  13548. pos += chunk.length;
  13549. }
  13550. return result;
  13551. }
  13552. };
  13553. var fnUntyped = {
  13554. arraySet: function (dest, src, src_offs, len, dest_offs) {
  13555. for (var i=0; i<len; i++) {
  13556. dest[dest_offs + i] = src[src_offs + i];
  13557. }
  13558. },
  13559. // Join array of chunks to single array.
  13560. flattenChunks: function(chunks) {
  13561. return [].concat.apply([], chunks);
  13562. }
  13563. };
  13564. // Enable/Disable typed arrays use, for testing
  13565. //
  13566. exports.setTyped = function (on) {
  13567. if (on) {
  13568. exports.Buf8 = Uint8Array;
  13569. exports.Buf16 = Uint16Array;
  13570. exports.Buf32 = Int32Array;
  13571. exports.assign(exports, fnTyped);
  13572. } else {
  13573. exports.Buf8 = Array;
  13574. exports.Buf16 = Array;
  13575. exports.Buf32 = Array;
  13576. exports.assign(exports, fnUntyped);
  13577. }
  13578. };
  13579. exports.setTyped(TYPED_OK);
  13580. },{}],52:[function(require,module,exports){
  13581. // String encode/decode helpers
  13582. 'use strict';
  13583. var utils = require('./common');
  13584. // Quick check if we can use fast array to bin string conversion
  13585. //
  13586. // - apply(Array) can fail on Android 2.2
  13587. // - apply(Uint8Array) can fail on iOS 5.1 Safary
  13588. //
  13589. var STR_APPLY_OK = true;
  13590. var STR_APPLY_UIA_OK = true;
  13591. try { String.fromCharCode.apply(null, [0]); } catch(__) { STR_APPLY_OK = false; }
  13592. try { String.fromCharCode.apply(null, new Uint8Array(1)); } catch(__) { STR_APPLY_UIA_OK = false; }
  13593. // Table with utf8 lengths (calculated by first byte of sequence)
  13594. // Note, that 5 & 6-byte values and some 4-byte values can not be represented in JS,
  13595. // because max possible codepoint is 0x10ffff
  13596. var _utf8len = new utils.Buf8(256);
  13597. for (var q=0; q<256; q++) {
  13598. _utf8len[q] = (q >= 252 ? 6 : q >= 248 ? 5 : q >= 240 ? 4 : q >= 224 ? 3 : q >= 192 ? 2 : 1);
  13599. }
  13600. _utf8len[254]=_utf8len[254]=1; // Invalid sequence start
  13601. // convert string to array (typed, when possible)
  13602. exports.string2buf = function (str) {
  13603. var buf, c, c2, m_pos, i, str_len = str.length, buf_len = 0;
  13604. // count binary size
  13605. for (m_pos = 0; m_pos < str_len; m_pos++) {
  13606. c = str.charCodeAt(m_pos);
  13607. if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) {
  13608. c2 = str.charCodeAt(m_pos+1);
  13609. if ((c2 & 0xfc00) === 0xdc00) {
  13610. c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
  13611. m_pos++;
  13612. }
  13613. }
  13614. buf_len += c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4;
  13615. }
  13616. // allocate buffer
  13617. buf = new utils.Buf8(buf_len);
  13618. // convert
  13619. for (i=0, m_pos = 0; i < buf_len; m_pos++) {
  13620. c = str.charCodeAt(m_pos);
  13621. if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) {
  13622. c2 = str.charCodeAt(m_pos+1);
  13623. if ((c2 & 0xfc00) === 0xdc00) {
  13624. c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
  13625. m_pos++;
  13626. }
  13627. }
  13628. if (c < 0x80) {
  13629. /* one byte */
  13630. buf[i++] = c;
  13631. } else if (c < 0x800) {
  13632. /* two bytes */
  13633. buf[i++] = 0xC0 | (c >>> 6);
  13634. buf[i++] = 0x80 | (c & 0x3f);
  13635. } else if (c < 0x10000) {
  13636. /* three bytes */
  13637. buf[i++] = 0xE0 | (c >>> 12);
  13638. buf[i++] = 0x80 | (c >>> 6 & 0x3f);
  13639. buf[i++] = 0x80 | (c & 0x3f);
  13640. } else {
  13641. /* four bytes */
  13642. buf[i++] = 0xf0 | (c >>> 18);
  13643. buf[i++] = 0x80 | (c >>> 12 & 0x3f);
  13644. buf[i++] = 0x80 | (c >>> 6 & 0x3f);
  13645. buf[i++] = 0x80 | (c & 0x3f);
  13646. }
  13647. }
  13648. return buf;
  13649. };
  13650. // Helper (used in 2 places)
  13651. function buf2binstring(buf, len) {
  13652. // use fallback for big arrays to avoid stack overflow
  13653. if (len < 65537) {
  13654. if ((buf.subarray && STR_APPLY_UIA_OK) || (!buf.subarray && STR_APPLY_OK)) {
  13655. return String.fromCharCode.apply(null, utils.shrinkBuf(buf, len));
  13656. }
  13657. }
  13658. var result = '';
  13659. for (var i=0; i < len; i++) {
  13660. result += String.fromCharCode(buf[i]);
  13661. }
  13662. return result;
  13663. }
  13664. // Convert byte array to binary string
  13665. exports.buf2binstring = function(buf) {
  13666. return buf2binstring(buf, buf.length);
  13667. };
  13668. // Convert binary string (typed, when possible)
  13669. exports.binstring2buf = function(str) {
  13670. var buf = new utils.Buf8(str.length);
  13671. for (var i=0, len=buf.length; i < len; i++) {
  13672. buf[i] = str.charCodeAt(i);
  13673. }
  13674. return buf;
  13675. };
  13676. // convert array to string
  13677. exports.buf2string = function (buf, max) {
  13678. var i, out, c, c_len;
  13679. var len = max || buf.length;
  13680. // Reserve max possible length (2 words per char)
  13681. // NB: by unknown reasons, Array is significantly faster for
  13682. // String.fromCharCode.apply than Uint16Array.
  13683. var utf16buf = new Array(len*2);
  13684. for (out=0, i=0; i<len;) {
  13685. c = buf[i++];
  13686. // quick process ascii
  13687. if (c < 0x80) { utf16buf[out++] = c; continue; }
  13688. c_len = _utf8len[c];
  13689. // skip 5 & 6 byte codes
  13690. if (c_len > 4) { utf16buf[out++] = 0xfffd; i += c_len-1; continue; }
  13691. // apply mask on first byte
  13692. c &= c_len === 2 ? 0x1f : c_len === 3 ? 0x0f : 0x07;
  13693. // join the rest
  13694. while (c_len > 1 && i < len) {
  13695. c = (c << 6) | (buf[i++] & 0x3f);
  13696. c_len--;
  13697. }
  13698. // terminated by end of string?
  13699. if (c_len > 1) { utf16buf[out++] = 0xfffd; continue; }
  13700. if (c < 0x10000) {
  13701. utf16buf[out++] = c;
  13702. } else {
  13703. c -= 0x10000;
  13704. utf16buf[out++] = 0xd800 | ((c >> 10) & 0x3ff);
  13705. utf16buf[out++] = 0xdc00 | (c & 0x3ff);
  13706. }
  13707. }
  13708. return buf2binstring(utf16buf, out);
  13709. };
  13710. // Calculate max possible position in utf8 buffer,
  13711. // that will not break sequence. If that's not possible
  13712. // - (very small limits) return max size as is.
  13713. //
  13714. // buf[] - utf8 bytes array
  13715. // max - length limit (mandatory);
  13716. exports.utf8border = function(buf, max) {
  13717. var pos;
  13718. max = max || buf.length;
  13719. if (max > buf.length) { max = buf.length; }
  13720. // go back from last position, until start of sequence found
  13721. pos = max-1;
  13722. while (pos >= 0 && (buf[pos] & 0xC0) === 0x80) { pos--; }
  13723. // Fuckup - very small and broken sequence,
  13724. // return max, because we should return something anyway.
  13725. if (pos < 0) { return max; }
  13726. // If we came to start of buffer - that means vuffer is too small,
  13727. // return max too.
  13728. if (pos === 0) { return max; }
  13729. return (pos + _utf8len[buf[pos]] > max) ? pos : max;
  13730. };
  13731. },{"./common":51}],53:[function(require,module,exports){
  13732. 'use strict';
  13733. // Note: adler32 takes 12% for level 0 and 2% for level 6.
  13734. // It doesn't worth to make additional optimizationa as in original.
  13735. // Small size is preferable.
  13736. function adler32(adler, buf, len, pos) {
  13737. var s1 = (adler & 0xffff) |0,
  13738. s2 = ((adler >>> 16) & 0xffff) |0,
  13739. n = 0;
  13740. while (len !== 0) {
  13741. // Set limit ~ twice less than 5552, to keep
  13742. // s2 in 31-bits, because we force signed ints.
  13743. // in other case %= will fail.
  13744. n = len > 2000 ? 2000 : len;
  13745. len -= n;
  13746. do {
  13747. s1 = (s1 + buf[pos++]) |0;
  13748. s2 = (s2 + s1) |0;
  13749. } while (--n);
  13750. s1 %= 65521;
  13751. s2 %= 65521;
  13752. }
  13753. return (s1 | (s2 << 16)) |0;
  13754. }
  13755. module.exports = adler32;
  13756. },{}],54:[function(require,module,exports){
  13757. module.exports = {
  13758. /* Allowed flush values; see deflate() and inflate() below for details */
  13759. Z_NO_FLUSH: 0,
  13760. Z_PARTIAL_FLUSH: 1,
  13761. Z_SYNC_FLUSH: 2,
  13762. Z_FULL_FLUSH: 3,
  13763. Z_FINISH: 4,
  13764. Z_BLOCK: 5,
  13765. Z_TREES: 6,
  13766. /* Return codes for the compression/decompression functions. Negative values
  13767. * are errors, positive values are used for special but normal events.
  13768. */
  13769. Z_OK: 0,
  13770. Z_STREAM_END: 1,
  13771. Z_NEED_DICT: 2,
  13772. Z_ERRNO: -1,
  13773. Z_STREAM_ERROR: -2,
  13774. Z_DATA_ERROR: -3,
  13775. //Z_MEM_ERROR: -4,
  13776. Z_BUF_ERROR: -5,
  13777. //Z_VERSION_ERROR: -6,
  13778. /* compression levels */
  13779. Z_NO_COMPRESSION: 0,
  13780. Z_BEST_SPEED: 1,
  13781. Z_BEST_COMPRESSION: 9,
  13782. Z_DEFAULT_COMPRESSION: -1,
  13783. Z_FILTERED: 1,
  13784. Z_HUFFMAN_ONLY: 2,
  13785. Z_RLE: 3,
  13786. Z_FIXED: 4,
  13787. Z_DEFAULT_STRATEGY: 0,
  13788. /* Possible values of the data_type field (though see inflate()) */
  13789. Z_BINARY: 0,
  13790. Z_TEXT: 1,
  13791. //Z_ASCII: 1, // = Z_TEXT (deprecated)
  13792. Z_UNKNOWN: 2,
  13793. /* The deflate compression method */
  13794. Z_DEFLATED: 8
  13795. //Z_NULL: null // Use -1 or null inline, depending on var type
  13796. };
  13797. },{}],55:[function(require,module,exports){
  13798. 'use strict';
  13799. // Note: we can't get significant speed boost here.
  13800. // So write code to minimize size - no pregenerated tables
  13801. // and array tools dependencies.
  13802. // Use ordinary array, since untyped makes no boost here
  13803. function makeTable() {
  13804. var c, table = [];
  13805. for (var n =0; n < 256; n++) {
  13806. c = n;
  13807. for (var k =0; k < 8; k++) {
  13808. c = ((c&1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1));
  13809. }
  13810. table[n] = c;
  13811. }
  13812. return table;
  13813. }
  13814. // Create table on load. Just 255 signed longs. Not a problem.
  13815. var crcTable = makeTable();
  13816. function crc32(crc, buf, len, pos) {
  13817. var t = crcTable,
  13818. end = pos + len;
  13819. crc = crc ^ (-1);
  13820. for (var i = pos; i < end; i++) {
  13821. crc = (crc >>> 8) ^ t[(crc ^ buf[i]) & 0xFF];
  13822. }
  13823. return (crc ^ (-1)); // >>> 0;
  13824. }
  13825. module.exports = crc32;
  13826. },{}],56:[function(require,module,exports){
  13827. 'use strict';
  13828. var utils = require('../utils/common');
  13829. var trees = require('./trees');
  13830. var adler32 = require('./adler32');
  13831. var crc32 = require('./crc32');
  13832. var msg = require('./messages');
  13833. /* Public constants ==========================================================*/
  13834. /* ===========================================================================*/
  13835. /* Allowed flush values; see deflate() and inflate() below for details */
  13836. var Z_NO_FLUSH = 0;
  13837. var Z_PARTIAL_FLUSH = 1;
  13838. //var Z_SYNC_FLUSH = 2;
  13839. var Z_FULL_FLUSH = 3;
  13840. var Z_FINISH = 4;
  13841. var Z_BLOCK = 5;
  13842. //var Z_TREES = 6;
  13843. /* Return codes for the compression/decompression functions. Negative values
  13844. * are errors, positive values are used for special but normal events.
  13845. */
  13846. var Z_OK = 0;
  13847. var Z_STREAM_END = 1;
  13848. //var Z_NEED_DICT = 2;
  13849. //var Z_ERRNO = -1;
  13850. var Z_STREAM_ERROR = -2;
  13851. var Z_DATA_ERROR = -3;
  13852. //var Z_MEM_ERROR = -4;
  13853. var Z_BUF_ERROR = -5;
  13854. //var Z_VERSION_ERROR = -6;
  13855. /* compression levels */
  13856. //var Z_NO_COMPRESSION = 0;
  13857. //var Z_BEST_SPEED = 1;
  13858. //var Z_BEST_COMPRESSION = 9;
  13859. var Z_DEFAULT_COMPRESSION = -1;
  13860. var Z_FILTERED = 1;
  13861. var Z_HUFFMAN_ONLY = 2;
  13862. var Z_RLE = 3;
  13863. var Z_FIXED = 4;
  13864. var Z_DEFAULT_STRATEGY = 0;
  13865. /* Possible values of the data_type field (though see inflate()) */
  13866. //var Z_BINARY = 0;
  13867. //var Z_TEXT = 1;
  13868. //var Z_ASCII = 1; // = Z_TEXT
  13869. var Z_UNKNOWN = 2;
  13870. /* The deflate compression method */
  13871. var Z_DEFLATED = 8;
  13872. /*============================================================================*/
  13873. var MAX_MEM_LEVEL = 9;
  13874. /* Maximum value for memLevel in deflateInit2 */
  13875. var MAX_WBITS = 15;
  13876. /* 32K LZ77 window */
  13877. var DEF_MEM_LEVEL = 8;
  13878. var LENGTH_CODES = 29;
  13879. /* number of length codes, not counting the special END_BLOCK code */
  13880. var LITERALS = 256;
  13881. /* number of literal bytes 0..255 */
  13882. var L_CODES = LITERALS + 1 + LENGTH_CODES;
  13883. /* number of Literal or Length codes, including the END_BLOCK code */
  13884. var D_CODES = 30;
  13885. /* number of distance codes */
  13886. var BL_CODES = 19;
  13887. /* number of codes used to transfer the bit lengths */
  13888. var HEAP_SIZE = 2*L_CODES + 1;
  13889. /* maximum heap size */
  13890. var MAX_BITS = 15;
  13891. /* All codes must not exceed MAX_BITS bits */
  13892. var MIN_MATCH = 3;
  13893. var MAX_MATCH = 258;
  13894. var MIN_LOOKAHEAD = (MAX_MATCH + MIN_MATCH + 1);
  13895. var PRESET_DICT = 0x20;
  13896. var INIT_STATE = 42;
  13897. var EXTRA_STATE = 69;
  13898. var NAME_STATE = 73;
  13899. var COMMENT_STATE = 91;
  13900. var HCRC_STATE = 103;
  13901. var BUSY_STATE = 113;
  13902. var FINISH_STATE = 666;
  13903. var BS_NEED_MORE = 1; /* block not completed, need more input or more output */
  13904. var BS_BLOCK_DONE = 2; /* block flush performed */
  13905. var BS_FINISH_STARTED = 3; /* finish started, need only more output at next deflate */
  13906. var BS_FINISH_DONE = 4; /* finish done, accept no more input or output */
  13907. var OS_CODE = 0x03; // Unix :) . Don't detect, use this default.
  13908. function err(strm, errorCode) {
  13909. strm.msg = msg[errorCode];
  13910. return errorCode;
  13911. }
  13912. function rank(f) {
  13913. return ((f) << 1) - ((f) > 4 ? 9 : 0);
  13914. }
  13915. function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
  13916. /* =========================================================================
  13917. * Flush as much pending output as possible. All deflate() output goes
  13918. * through this function so some applications may wish to modify it
  13919. * to avoid allocating a large strm->output buffer and copying into it.
  13920. * (See also read_buf()).
  13921. */
  13922. function flush_pending(strm) {
  13923. var s = strm.state;
  13924. //_tr_flush_bits(s);
  13925. var len = s.pending;
  13926. if (len > strm.avail_out) {
  13927. len = strm.avail_out;
  13928. }
  13929. if (len === 0) { return; }
  13930. utils.arraySet(strm.output, s.pending_buf, s.pending_out, len, strm.next_out);
  13931. strm.next_out += len;
  13932. s.pending_out += len;
  13933. strm.total_out += len;
  13934. strm.avail_out -= len;
  13935. s.pending -= len;
  13936. if (s.pending === 0) {
  13937. s.pending_out = 0;
  13938. }
  13939. }
  13940. function flush_block_only (s, last) {
  13941. trees._tr_flush_block(s, (s.block_start >= 0 ? s.block_start : -1), s.strstart - s.block_start, last);
  13942. s.block_start = s.strstart;
  13943. flush_pending(s.strm);
  13944. }
  13945. function put_byte(s, b) {
  13946. s.pending_buf[s.pending++] = b;
  13947. }
  13948. /* =========================================================================
  13949. * Put a short in the pending buffer. The 16-bit value is put in MSB order.
  13950. * IN assertion: the stream state is correct and there is enough room in
  13951. * pending_buf.
  13952. */
  13953. function putShortMSB(s, b) {
  13954. // put_byte(s, (Byte)(b >> 8));
  13955. // put_byte(s, (Byte)(b & 0xff));
  13956. s.pending_buf[s.pending++] = (b >>> 8) & 0xff;
  13957. s.pending_buf[s.pending++] = b & 0xff;
  13958. }
  13959. /* ===========================================================================
  13960. * Read a new buffer from the current input stream, update the adler32
  13961. * and total number of bytes read. All deflate() input goes through
  13962. * this function so some applications may wish to modify it to avoid
  13963. * allocating a large strm->input buffer and copying from it.
  13964. * (See also flush_pending()).
  13965. */
  13966. function read_buf(strm, buf, start, size) {
  13967. var len = strm.avail_in;
  13968. if (len > size) { len = size; }
  13969. if (len === 0) { return 0; }
  13970. strm.avail_in -= len;
  13971. utils.arraySet(buf, strm.input, strm.next_in, len, start);
  13972. if (strm.state.wrap === 1) {
  13973. strm.adler = adler32(strm.adler, buf, len, start);
  13974. }
  13975. else if (strm.state.wrap === 2) {
  13976. strm.adler = crc32(strm.adler, buf, len, start);
  13977. }
  13978. strm.next_in += len;
  13979. strm.total_in += len;
  13980. return len;
  13981. }
  13982. /* ===========================================================================
  13983. * Set match_start to the longest match starting at the given string and
  13984. * return its length. Matches shorter or equal to prev_length are discarded,
  13985. * in which case the result is equal to prev_length and match_start is
  13986. * garbage.
  13987. * IN assertions: cur_match is the head of the hash chain for the current
  13988. * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
  13989. * OUT assertion: the match length is not greater than s->lookahead.
  13990. */
  13991. function longest_match(s, cur_match) {
  13992. var chain_length = s.max_chain_length; /* max hash chain length */
  13993. var scan = s.strstart; /* current string */
  13994. var match; /* matched string */
  13995. var len; /* length of current match */
  13996. var best_len = s.prev_length; /* best match length so far */
  13997. var nice_match = s.nice_match; /* stop if match long enough */
  13998. var limit = (s.strstart > (s.w_size - MIN_LOOKAHEAD)) ?
  13999. s.strstart - (s.w_size - MIN_LOOKAHEAD) : 0/*NIL*/;
  14000. var _win = s.window; // shortcut
  14001. var wmask = s.w_mask;
  14002. var prev = s.prev;
  14003. /* Stop when cur_match becomes <= limit. To simplify the code,
  14004. * we prevent matches with the string of window index 0.
  14005. */
  14006. var strend = s.strstart + MAX_MATCH;
  14007. var scan_end1 = _win[scan + best_len - 1];
  14008. var scan_end = _win[scan + best_len];
  14009. /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
  14010. * It is easy to get rid of this optimization if necessary.
  14011. */
  14012. // Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
  14013. /* Do not waste too much time if we already have a good match: */
  14014. if (s.prev_length >= s.good_match) {
  14015. chain_length >>= 2;
  14016. }
  14017. /* Do not look for matches beyond the end of the input. This is necessary
  14018. * to make deflate deterministic.
  14019. */
  14020. if (nice_match > s.lookahead) { nice_match = s.lookahead; }
  14021. // Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
  14022. do {
  14023. // Assert(cur_match < s->strstart, "no future");
  14024. match = cur_match;
  14025. /* Skip to next match if the match length cannot increase
  14026. * or if the match length is less than 2. Note that the checks below
  14027. * for insufficient lookahead only occur occasionally for performance
  14028. * reasons. Therefore uninitialized memory will be accessed, and
  14029. * conditional jumps will be made that depend on those values.
  14030. * However the length of the match is limited to the lookahead, so
  14031. * the output of deflate is not affected by the uninitialized values.
  14032. */
  14033. if (_win[match + best_len] !== scan_end ||
  14034. _win[match + best_len - 1] !== scan_end1 ||
  14035. _win[match] !== _win[scan] ||
  14036. _win[++match] !== _win[scan + 1]) {
  14037. continue;
  14038. }
  14039. /* The check at best_len-1 can be removed because it will be made
  14040. * again later. (This heuristic is not always a win.)
  14041. * It is not necessary to compare scan[2] and match[2] since they
  14042. * are always equal when the other bytes match, given that
  14043. * the hash keys are equal and that HASH_BITS >= 8.
  14044. */
  14045. scan += 2;
  14046. match++;
  14047. // Assert(*scan == *match, "match[2]?");
  14048. /* We check for insufficient lookahead only every 8th comparison;
  14049. * the 256th check will be made at strstart+258.
  14050. */
  14051. do {
  14052. /*jshint noempty:false*/
  14053. } while (_win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  14054. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  14055. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  14056. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  14057. scan < strend);
  14058. // Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  14059. len = MAX_MATCH - (strend - scan);
  14060. scan = strend - MAX_MATCH;
  14061. if (len > best_len) {
  14062. s.match_start = cur_match;
  14063. best_len = len;
  14064. if (len >= nice_match) {
  14065. break;
  14066. }
  14067. scan_end1 = _win[scan + best_len - 1];
  14068. scan_end = _win[scan + best_len];
  14069. }
  14070. } while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length !== 0);
  14071. if (best_len <= s.lookahead) {
  14072. return best_len;
  14073. }
  14074. return s.lookahead;
  14075. }
  14076. /* ===========================================================================
  14077. * Fill the window when the lookahead becomes insufficient.
  14078. * Updates strstart and lookahead.
  14079. *
  14080. * IN assertion: lookahead < MIN_LOOKAHEAD
  14081. * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
  14082. * At least one byte has been read, or avail_in == 0; reads are
  14083. * performed for at least two bytes (required for the zip translate_eol
  14084. * option -- not supported here).
  14085. */
  14086. function fill_window(s) {
  14087. var _w_size = s.w_size;
  14088. var p, n, m, more, str;
  14089. //Assert(s->lookahead < MIN_LOOKAHEAD, "already enough lookahead");
  14090. do {
  14091. more = s.window_size - s.lookahead - s.strstart;
  14092. // JS ints have 32 bit, block below not needed
  14093. /* Deal with !@#$% 64K limit: */
  14094. //if (sizeof(int) <= 2) {
  14095. // if (more == 0 && s->strstart == 0 && s->lookahead == 0) {
  14096. // more = wsize;
  14097. //
  14098. // } else if (more == (unsigned)(-1)) {
  14099. // /* Very unlikely, but possible on 16 bit machine if
  14100. // * strstart == 0 && lookahead == 1 (input done a byte at time)
  14101. // */
  14102. // more--;
  14103. // }
  14104. //}
  14105. /* If the window is almost full and there is insufficient lookahead,
  14106. * move the upper half to the lower one to make room in the upper half.
  14107. */
  14108. if (s.strstart >= _w_size + (_w_size - MIN_LOOKAHEAD)) {
  14109. utils.arraySet(s.window, s.window, _w_size, _w_size, 0);
  14110. s.match_start -= _w_size;
  14111. s.strstart -= _w_size;
  14112. /* we now have strstart >= MAX_DIST */
  14113. s.block_start -= _w_size;
  14114. /* Slide the hash table (could be avoided with 32 bit values
  14115. at the expense of memory usage). We slide even when level == 0
  14116. to keep the hash table consistent if we switch back to level > 0
  14117. later. (Using level 0 permanently is not an optimal usage of
  14118. zlib, so we don't care about this pathological case.)
  14119. */
  14120. n = s.hash_size;
  14121. p = n;
  14122. do {
  14123. m = s.head[--p];
  14124. s.head[p] = (m >= _w_size ? m - _w_size : 0);
  14125. } while (--n);
  14126. n = _w_size;
  14127. p = n;
  14128. do {
  14129. m = s.prev[--p];
  14130. s.prev[p] = (m >= _w_size ? m - _w_size : 0);
  14131. /* If n is not on any hash chain, prev[n] is garbage but
  14132. * its value will never be used.
  14133. */
  14134. } while (--n);
  14135. more += _w_size;
  14136. }
  14137. if (s.strm.avail_in === 0) {
  14138. break;
  14139. }
  14140. /* If there was no sliding:
  14141. * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
  14142. * more == window_size - lookahead - strstart
  14143. * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
  14144. * => more >= window_size - 2*WSIZE + 2
  14145. * In the BIG_MEM or MMAP case (not yet supported),
  14146. * window_size == input_size + MIN_LOOKAHEAD &&
  14147. * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
  14148. * Otherwise, window_size == 2*WSIZE so more >= 2.
  14149. * If there was sliding, more >= WSIZE. So in all cases, more >= 2.
  14150. */
  14151. //Assert(more >= 2, "more < 2");
  14152. n = read_buf(s.strm, s.window, s.strstart + s.lookahead, more);
  14153. s.lookahead += n;
  14154. /* Initialize the hash value now that we have some input: */
  14155. if (s.lookahead + s.insert >= MIN_MATCH) {
  14156. str = s.strstart - s.insert;
  14157. s.ins_h = s.window[str];
  14158. /* UPDATE_HASH(s, s->ins_h, s->window[str + 1]); */
  14159. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + 1]) & s.hash_mask;
  14160. //#if MIN_MATCH != 3
  14161. // Call update_hash() MIN_MATCH-3 more times
  14162. //#endif
  14163. while (s.insert) {
  14164. /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */
  14165. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH-1]) & s.hash_mask;
  14166. s.prev[str & s.w_mask] = s.head[s.ins_h];
  14167. s.head[s.ins_h] = str;
  14168. str++;
  14169. s.insert--;
  14170. if (s.lookahead + s.insert < MIN_MATCH) {
  14171. break;
  14172. }
  14173. }
  14174. }
  14175. /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,
  14176. * but this is not important since only literal bytes will be emitted.
  14177. */
  14178. } while (s.lookahead < MIN_LOOKAHEAD && s.strm.avail_in !== 0);
  14179. /* If the WIN_INIT bytes after the end of the current data have never been
  14180. * written, then zero those bytes in order to avoid memory check reports of
  14181. * the use of uninitialized (or uninitialised as Julian writes) bytes by
  14182. * the longest match routines. Update the high water mark for the next
  14183. * time through here. WIN_INIT is set to MAX_MATCH since the longest match
  14184. * routines allow scanning to strstart + MAX_MATCH, ignoring lookahead.
  14185. */
  14186. // if (s.high_water < s.window_size) {
  14187. // var curr = s.strstart + s.lookahead;
  14188. // var init = 0;
  14189. //
  14190. // if (s.high_water < curr) {
  14191. // /* Previous high water mark below current data -- zero WIN_INIT
  14192. // * bytes or up to end of window, whichever is less.
  14193. // */
  14194. // init = s.window_size - curr;
  14195. // if (init > WIN_INIT)
  14196. // init = WIN_INIT;
  14197. // zmemzero(s->window + curr, (unsigned)init);
  14198. // s->high_water = curr + init;
  14199. // }
  14200. // else if (s->high_water < (ulg)curr + WIN_INIT) {
  14201. // /* High water mark at or above current data, but below current data
  14202. // * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up
  14203. // * to end of window, whichever is less.
  14204. // */
  14205. // init = (ulg)curr + WIN_INIT - s->high_water;
  14206. // if (init > s->window_size - s->high_water)
  14207. // init = s->window_size - s->high_water;
  14208. // zmemzero(s->window + s->high_water, (unsigned)init);
  14209. // s->high_water += init;
  14210. // }
  14211. // }
  14212. //
  14213. // Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD,
  14214. // "not enough room for search");
  14215. }
  14216. /* ===========================================================================
  14217. * Copy without compression as much as possible from the input stream, return
  14218. * the current block state.
  14219. * This function does not insert new strings in the dictionary since
  14220. * uncompressible data is probably not useful. This function is used
  14221. * only for the level=0 compression option.
  14222. * NOTE: this function should be optimized to avoid extra copying from
  14223. * window to pending_buf.
  14224. */
  14225. function deflate_stored(s, flush) {
  14226. /* Stored blocks are limited to 0xffff bytes, pending_buf is limited
  14227. * to pending_buf_size, and each stored block has a 5 byte header:
  14228. */
  14229. var max_block_size = 0xffff;
  14230. if (max_block_size > s.pending_buf_size - 5) {
  14231. max_block_size = s.pending_buf_size - 5;
  14232. }
  14233. /* Copy as much as possible from input to output: */
  14234. for (;;) {
  14235. /* Fill the window as much as possible: */
  14236. if (s.lookahead <= 1) {
  14237. //Assert(s->strstart < s->w_size+MAX_DIST(s) ||
  14238. // s->block_start >= (long)s->w_size, "slide too late");
  14239. // if (!(s.strstart < s.w_size + (s.w_size - MIN_LOOKAHEAD) ||
  14240. // s.block_start >= s.w_size)) {
  14241. // throw new Error("slide too late");
  14242. // }
  14243. fill_window(s);
  14244. if (s.lookahead === 0 && flush === Z_NO_FLUSH) {
  14245. return BS_NEED_MORE;
  14246. }
  14247. if (s.lookahead === 0) {
  14248. break;
  14249. }
  14250. /* flush the current block */
  14251. }
  14252. //Assert(s->block_start >= 0L, "block gone");
  14253. // if (s.block_start < 0) throw new Error("block gone");
  14254. s.strstart += s.lookahead;
  14255. s.lookahead = 0;
  14256. /* Emit a stored block if pending_buf will be full: */
  14257. var max_start = s.block_start + max_block_size;
  14258. if (s.strstart === 0 || s.strstart >= max_start) {
  14259. /* strstart == 0 is possible when wraparound on 16-bit machine */
  14260. s.lookahead = s.strstart - max_start;
  14261. s.strstart = max_start;
  14262. /*** FLUSH_BLOCK(s, 0); ***/
  14263. flush_block_only(s, false);
  14264. if (s.strm.avail_out === 0) {
  14265. return BS_NEED_MORE;
  14266. }
  14267. /***/
  14268. }
  14269. /* Flush if we may have to slide, otherwise block_start may become
  14270. * negative and the data will be gone:
  14271. */
  14272. if (s.strstart - s.block_start >= (s.w_size - MIN_LOOKAHEAD)) {
  14273. /*** FLUSH_BLOCK(s, 0); ***/
  14274. flush_block_only(s, false);
  14275. if (s.strm.avail_out === 0) {
  14276. return BS_NEED_MORE;
  14277. }
  14278. /***/
  14279. }
  14280. }
  14281. s.insert = 0;
  14282. if (flush === Z_FINISH) {
  14283. /*** FLUSH_BLOCK(s, 1); ***/
  14284. flush_block_only(s, true);
  14285. if (s.strm.avail_out === 0) {
  14286. return BS_FINISH_STARTED;
  14287. }
  14288. /***/
  14289. return BS_FINISH_DONE;
  14290. }
  14291. if (s.strstart > s.block_start) {
  14292. /*** FLUSH_BLOCK(s, 0); ***/
  14293. flush_block_only(s, false);
  14294. if (s.strm.avail_out === 0) {
  14295. return BS_NEED_MORE;
  14296. }
  14297. /***/
  14298. }
  14299. return BS_NEED_MORE;
  14300. }
  14301. /* ===========================================================================
  14302. * Compress as much as possible from the input stream, return the current
  14303. * block state.
  14304. * This function does not perform lazy evaluation of matches and inserts
  14305. * new strings in the dictionary only for unmatched strings or for short
  14306. * matches. It is used only for the fast compression options.
  14307. */
  14308. function deflate_fast(s, flush) {
  14309. var hash_head; /* head of the hash chain */
  14310. var bflush; /* set if current block must be flushed */
  14311. for (;;) {
  14312. /* Make sure that we always have enough lookahead, except
  14313. * at the end of the input file. We need MAX_MATCH bytes
  14314. * for the next match, plus MIN_MATCH bytes to insert the
  14315. * string following the next match.
  14316. */
  14317. if (s.lookahead < MIN_LOOKAHEAD) {
  14318. fill_window(s);
  14319. if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
  14320. return BS_NEED_MORE;
  14321. }
  14322. if (s.lookahead === 0) {
  14323. break; /* flush the current block */
  14324. }
  14325. }
  14326. /* Insert the string window[strstart .. strstart+2] in the
  14327. * dictionary, and set hash_head to the head of the hash chain:
  14328. */
  14329. hash_head = 0/*NIL*/;
  14330. if (s.lookahead >= MIN_MATCH) {
  14331. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  14332. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  14333. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  14334. s.head[s.ins_h] = s.strstart;
  14335. /***/
  14336. }
  14337. /* Find the longest match, discarding those <= prev_length.
  14338. * At this point we have always match_length < MIN_MATCH
  14339. */
  14340. if (hash_head !== 0/*NIL*/ && ((s.strstart - hash_head) <= (s.w_size - MIN_LOOKAHEAD))) {
  14341. /* To simplify the code, we prevent matches with the string
  14342. * of window index 0 (in particular we have to avoid a match
  14343. * of the string with itself at the start of the input file).
  14344. */
  14345. s.match_length = longest_match(s, hash_head);
  14346. /* longest_match() sets match_start */
  14347. }
  14348. if (s.match_length >= MIN_MATCH) {
  14349. // check_match(s, s.strstart, s.match_start, s.match_length); // for debug only
  14350. /*** _tr_tally_dist(s, s.strstart - s.match_start,
  14351. s.match_length - MIN_MATCH, bflush); ***/
  14352. bflush = trees._tr_tally(s, s.strstart - s.match_start, s.match_length - MIN_MATCH);
  14353. s.lookahead -= s.match_length;
  14354. /* Insert new strings in the hash table only if the match length
  14355. * is not too large. This saves time but degrades compression.
  14356. */
  14357. if (s.match_length <= s.max_lazy_match/*max_insert_length*/ && s.lookahead >= MIN_MATCH) {
  14358. s.match_length--; /* string at strstart already in table */
  14359. do {
  14360. s.strstart++;
  14361. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  14362. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  14363. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  14364. s.head[s.ins_h] = s.strstart;
  14365. /***/
  14366. /* strstart never exceeds WSIZE-MAX_MATCH, so there are
  14367. * always MIN_MATCH bytes ahead.
  14368. */
  14369. } while (--s.match_length !== 0);
  14370. s.strstart++;
  14371. } else
  14372. {
  14373. s.strstart += s.match_length;
  14374. s.match_length = 0;
  14375. s.ins_h = s.window[s.strstart];
  14376. /* UPDATE_HASH(s, s.ins_h, s.window[s.strstart+1]); */
  14377. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + 1]) & s.hash_mask;
  14378. //#if MIN_MATCH != 3
  14379. // Call UPDATE_HASH() MIN_MATCH-3 more times
  14380. //#endif
  14381. /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not
  14382. * matter since it will be recomputed at next deflate call.
  14383. */
  14384. }
  14385. } else {
  14386. /* No match, output a literal byte */
  14387. //Tracevv((stderr,"%c", s.window[s.strstart]));
  14388. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  14389. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  14390. s.lookahead--;
  14391. s.strstart++;
  14392. }
  14393. if (bflush) {
  14394. /*** FLUSH_BLOCK(s, 0); ***/
  14395. flush_block_only(s, false);
  14396. if (s.strm.avail_out === 0) {
  14397. return BS_NEED_MORE;
  14398. }
  14399. /***/
  14400. }
  14401. }
  14402. s.insert = ((s.strstart < (MIN_MATCH-1)) ? s.strstart : MIN_MATCH-1);
  14403. if (flush === Z_FINISH) {
  14404. /*** FLUSH_BLOCK(s, 1); ***/
  14405. flush_block_only(s, true);
  14406. if (s.strm.avail_out === 0) {
  14407. return BS_FINISH_STARTED;
  14408. }
  14409. /***/
  14410. return BS_FINISH_DONE;
  14411. }
  14412. if (s.last_lit) {
  14413. /*** FLUSH_BLOCK(s, 0); ***/
  14414. flush_block_only(s, false);
  14415. if (s.strm.avail_out === 0) {
  14416. return BS_NEED_MORE;
  14417. }
  14418. /***/
  14419. }
  14420. return BS_BLOCK_DONE;
  14421. }
  14422. /* ===========================================================================
  14423. * Same as above, but achieves better compression. We use a lazy
  14424. * evaluation for matches: a match is finally adopted only if there is
  14425. * no better match at the next window position.
  14426. */
  14427. function deflate_slow(s, flush) {
  14428. var hash_head; /* head of hash chain */
  14429. var bflush; /* set if current block must be flushed */
  14430. var max_insert;
  14431. /* Process the input block. */
  14432. for (;;) {
  14433. /* Make sure that we always have enough lookahead, except
  14434. * at the end of the input file. We need MAX_MATCH bytes
  14435. * for the next match, plus MIN_MATCH bytes to insert the
  14436. * string following the next match.
  14437. */
  14438. if (s.lookahead < MIN_LOOKAHEAD) {
  14439. fill_window(s);
  14440. if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
  14441. return BS_NEED_MORE;
  14442. }
  14443. if (s.lookahead === 0) { break; } /* flush the current block */
  14444. }
  14445. /* Insert the string window[strstart .. strstart+2] in the
  14446. * dictionary, and set hash_head to the head of the hash chain:
  14447. */
  14448. hash_head = 0/*NIL*/;
  14449. if (s.lookahead >= MIN_MATCH) {
  14450. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  14451. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  14452. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  14453. s.head[s.ins_h] = s.strstart;
  14454. /***/
  14455. }
  14456. /* Find the longest match, discarding those <= prev_length.
  14457. */
  14458. s.prev_length = s.match_length;
  14459. s.prev_match = s.match_start;
  14460. s.match_length = MIN_MATCH-1;
  14461. if (hash_head !== 0/*NIL*/ && s.prev_length < s.max_lazy_match &&
  14462. s.strstart - hash_head <= (s.w_size-MIN_LOOKAHEAD)/*MAX_DIST(s)*/) {
  14463. /* To simplify the code, we prevent matches with the string
  14464. * of window index 0 (in particular we have to avoid a match
  14465. * of the string with itself at the start of the input file).
  14466. */
  14467. s.match_length = longest_match(s, hash_head);
  14468. /* longest_match() sets match_start */
  14469. if (s.match_length <= 5 &&
  14470. (s.strategy === Z_FILTERED || (s.match_length === MIN_MATCH && s.strstart - s.match_start > 4096/*TOO_FAR*/))) {
  14471. /* If prev_match is also MIN_MATCH, match_start is garbage
  14472. * but we will ignore the current match anyway.
  14473. */
  14474. s.match_length = MIN_MATCH-1;
  14475. }
  14476. }
  14477. /* If there was a match at the previous step and the current
  14478. * match is not better, output the previous match:
  14479. */
  14480. if (s.prev_length >= MIN_MATCH && s.match_length <= s.prev_length) {
  14481. max_insert = s.strstart + s.lookahead - MIN_MATCH;
  14482. /* Do not insert strings in hash table beyond this. */
  14483. //check_match(s, s.strstart-1, s.prev_match, s.prev_length);
  14484. /***_tr_tally_dist(s, s.strstart - 1 - s.prev_match,
  14485. s.prev_length - MIN_MATCH, bflush);***/
  14486. bflush = trees._tr_tally(s, s.strstart - 1- s.prev_match, s.prev_length - MIN_MATCH);
  14487. /* Insert in hash table all strings up to the end of the match.
  14488. * strstart-1 and strstart are already inserted. If there is not
  14489. * enough lookahead, the last two strings are not inserted in
  14490. * the hash table.
  14491. */
  14492. s.lookahead -= s.prev_length-1;
  14493. s.prev_length -= 2;
  14494. do {
  14495. if (++s.strstart <= max_insert) {
  14496. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  14497. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  14498. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  14499. s.head[s.ins_h] = s.strstart;
  14500. /***/
  14501. }
  14502. } while (--s.prev_length !== 0);
  14503. s.match_available = 0;
  14504. s.match_length = MIN_MATCH-1;
  14505. s.strstart++;
  14506. if (bflush) {
  14507. /*** FLUSH_BLOCK(s, 0); ***/
  14508. flush_block_only(s, false);
  14509. if (s.strm.avail_out === 0) {
  14510. return BS_NEED_MORE;
  14511. }
  14512. /***/
  14513. }
  14514. } else if (s.match_available) {
  14515. /* If there was no match at the previous position, output a
  14516. * single literal. If there was a match but the current match
  14517. * is longer, truncate the previous match to a single literal.
  14518. */
  14519. //Tracevv((stderr,"%c", s->window[s->strstart-1]));
  14520. /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
  14521. bflush = trees._tr_tally(s, 0, s.window[s.strstart-1]);
  14522. if (bflush) {
  14523. /*** FLUSH_BLOCK_ONLY(s, 0) ***/
  14524. flush_block_only(s, false);
  14525. /***/
  14526. }
  14527. s.strstart++;
  14528. s.lookahead--;
  14529. if (s.strm.avail_out === 0) {
  14530. return BS_NEED_MORE;
  14531. }
  14532. } else {
  14533. /* There is no previous match to compare with, wait for
  14534. * the next step to decide.
  14535. */
  14536. s.match_available = 1;
  14537. s.strstart++;
  14538. s.lookahead--;
  14539. }
  14540. }
  14541. //Assert (flush != Z_NO_FLUSH, "no flush?");
  14542. if (s.match_available) {
  14543. //Tracevv((stderr,"%c", s->window[s->strstart-1]));
  14544. /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
  14545. bflush = trees._tr_tally(s, 0, s.window[s.strstart-1]);
  14546. s.match_available = 0;
  14547. }
  14548. s.insert = s.strstart < MIN_MATCH-1 ? s.strstart : MIN_MATCH-1;
  14549. if (flush === Z_FINISH) {
  14550. /*** FLUSH_BLOCK(s, 1); ***/
  14551. flush_block_only(s, true);
  14552. if (s.strm.avail_out === 0) {
  14553. return BS_FINISH_STARTED;
  14554. }
  14555. /***/
  14556. return BS_FINISH_DONE;
  14557. }
  14558. if (s.last_lit) {
  14559. /*** FLUSH_BLOCK(s, 0); ***/
  14560. flush_block_only(s, false);
  14561. if (s.strm.avail_out === 0) {
  14562. return BS_NEED_MORE;
  14563. }
  14564. /***/
  14565. }
  14566. return BS_BLOCK_DONE;
  14567. }
  14568. /* ===========================================================================
  14569. * For Z_RLE, simply look for runs of bytes, generate matches only of distance
  14570. * one. Do not maintain a hash table. (It will be regenerated if this run of
  14571. * deflate switches away from Z_RLE.)
  14572. */
  14573. function deflate_rle(s, flush) {
  14574. var bflush; /* set if current block must be flushed */
  14575. var prev; /* byte at distance one to match */
  14576. var scan, strend; /* scan goes up to strend for length of run */
  14577. var _win = s.window;
  14578. for (;;) {
  14579. /* Make sure that we always have enough lookahead, except
  14580. * at the end of the input file. We need MAX_MATCH bytes
  14581. * for the longest run, plus one for the unrolled loop.
  14582. */
  14583. if (s.lookahead <= MAX_MATCH) {
  14584. fill_window(s);
  14585. if (s.lookahead <= MAX_MATCH && flush === Z_NO_FLUSH) {
  14586. return BS_NEED_MORE;
  14587. }
  14588. if (s.lookahead === 0) { break; } /* flush the current block */
  14589. }
  14590. /* See how many times the previous byte repeats */
  14591. s.match_length = 0;
  14592. if (s.lookahead >= MIN_MATCH && s.strstart > 0) {
  14593. scan = s.strstart - 1;
  14594. prev = _win[scan];
  14595. if (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan]) {
  14596. strend = s.strstart + MAX_MATCH;
  14597. do {
  14598. /*jshint noempty:false*/
  14599. } while (prev === _win[++scan] && prev === _win[++scan] &&
  14600. prev === _win[++scan] && prev === _win[++scan] &&
  14601. prev === _win[++scan] && prev === _win[++scan] &&
  14602. prev === _win[++scan] && prev === _win[++scan] &&
  14603. scan < strend);
  14604. s.match_length = MAX_MATCH - (strend - scan);
  14605. if (s.match_length > s.lookahead) {
  14606. s.match_length = s.lookahead;
  14607. }
  14608. }
  14609. //Assert(scan <= s->window+(uInt)(s->window_size-1), "wild scan");
  14610. }
  14611. /* Emit match if have run of MIN_MATCH or longer, else emit literal */
  14612. if (s.match_length >= MIN_MATCH) {
  14613. //check_match(s, s.strstart, s.strstart - 1, s.match_length);
  14614. /*** _tr_tally_dist(s, 1, s.match_length - MIN_MATCH, bflush); ***/
  14615. bflush = trees._tr_tally(s, 1, s.match_length - MIN_MATCH);
  14616. s.lookahead -= s.match_length;
  14617. s.strstart += s.match_length;
  14618. s.match_length = 0;
  14619. } else {
  14620. /* No match, output a literal byte */
  14621. //Tracevv((stderr,"%c", s->window[s->strstart]));
  14622. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  14623. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  14624. s.lookahead--;
  14625. s.strstart++;
  14626. }
  14627. if (bflush) {
  14628. /*** FLUSH_BLOCK(s, 0); ***/
  14629. flush_block_only(s, false);
  14630. if (s.strm.avail_out === 0) {
  14631. return BS_NEED_MORE;
  14632. }
  14633. /***/
  14634. }
  14635. }
  14636. s.insert = 0;
  14637. if (flush === Z_FINISH) {
  14638. /*** FLUSH_BLOCK(s, 1); ***/
  14639. flush_block_only(s, true);
  14640. if (s.strm.avail_out === 0) {
  14641. return BS_FINISH_STARTED;
  14642. }
  14643. /***/
  14644. return BS_FINISH_DONE;
  14645. }
  14646. if (s.last_lit) {
  14647. /*** FLUSH_BLOCK(s, 0); ***/
  14648. flush_block_only(s, false);
  14649. if (s.strm.avail_out === 0) {
  14650. return BS_NEED_MORE;
  14651. }
  14652. /***/
  14653. }
  14654. return BS_BLOCK_DONE;
  14655. }
  14656. /* ===========================================================================
  14657. * For Z_HUFFMAN_ONLY, do not look for matches. Do not maintain a hash table.
  14658. * (It will be regenerated if this run of deflate switches away from Huffman.)
  14659. */
  14660. function deflate_huff(s, flush) {
  14661. var bflush; /* set if current block must be flushed */
  14662. for (;;) {
  14663. /* Make sure that we have a literal to write. */
  14664. if (s.lookahead === 0) {
  14665. fill_window(s);
  14666. if (s.lookahead === 0) {
  14667. if (flush === Z_NO_FLUSH) {
  14668. return BS_NEED_MORE;
  14669. }
  14670. break; /* flush the current block */
  14671. }
  14672. }
  14673. /* Output a literal byte */
  14674. s.match_length = 0;
  14675. //Tracevv((stderr,"%c", s->window[s->strstart]));
  14676. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  14677. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  14678. s.lookahead--;
  14679. s.strstart++;
  14680. if (bflush) {
  14681. /*** FLUSH_BLOCK(s, 0); ***/
  14682. flush_block_only(s, false);
  14683. if (s.strm.avail_out === 0) {
  14684. return BS_NEED_MORE;
  14685. }
  14686. /***/
  14687. }
  14688. }
  14689. s.insert = 0;
  14690. if (flush === Z_FINISH) {
  14691. /*** FLUSH_BLOCK(s, 1); ***/
  14692. flush_block_only(s, true);
  14693. if (s.strm.avail_out === 0) {
  14694. return BS_FINISH_STARTED;
  14695. }
  14696. /***/
  14697. return BS_FINISH_DONE;
  14698. }
  14699. if (s.last_lit) {
  14700. /*** FLUSH_BLOCK(s, 0); ***/
  14701. flush_block_only(s, false);
  14702. if (s.strm.avail_out === 0) {
  14703. return BS_NEED_MORE;
  14704. }
  14705. /***/
  14706. }
  14707. return BS_BLOCK_DONE;
  14708. }
  14709. /* Values for max_lazy_match, good_match and max_chain_length, depending on
  14710. * the desired pack level (0..9). The values given below have been tuned to
  14711. * exclude worst case performance for pathological files. Better values may be
  14712. * found for specific files.
  14713. */
  14714. var Config = function (good_length, max_lazy, nice_length, max_chain, func) {
  14715. this.good_length = good_length;
  14716. this.max_lazy = max_lazy;
  14717. this.nice_length = nice_length;
  14718. this.max_chain = max_chain;
  14719. this.func = func;
  14720. };
  14721. var configuration_table;
  14722. configuration_table = [
  14723. /* good lazy nice chain */
  14724. new Config(0, 0, 0, 0, deflate_stored), /* 0 store only */
  14725. new Config(4, 4, 8, 4, deflate_fast), /* 1 max speed, no lazy matches */
  14726. new Config(4, 5, 16, 8, deflate_fast), /* 2 */
  14727. new Config(4, 6, 32, 32, deflate_fast), /* 3 */
  14728. new Config(4, 4, 16, 16, deflate_slow), /* 4 lazy matches */
  14729. new Config(8, 16, 32, 32, deflate_slow), /* 5 */
  14730. new Config(8, 16, 128, 128, deflate_slow), /* 6 */
  14731. new Config(8, 32, 128, 256, deflate_slow), /* 7 */
  14732. new Config(32, 128, 258, 1024, deflate_slow), /* 8 */
  14733. new Config(32, 258, 258, 4096, deflate_slow) /* 9 max compression */
  14734. ];
  14735. /* ===========================================================================
  14736. * Initialize the "longest match" routines for a new zlib stream
  14737. */
  14738. function lm_init(s) {
  14739. s.window_size = 2 * s.w_size;
  14740. /*** CLEAR_HASH(s); ***/
  14741. zero(s.head); // Fill with NIL (= 0);
  14742. /* Set the default configuration parameters:
  14743. */
  14744. s.max_lazy_match = configuration_table[s.level].max_lazy;
  14745. s.good_match = configuration_table[s.level].good_length;
  14746. s.nice_match = configuration_table[s.level].nice_length;
  14747. s.max_chain_length = configuration_table[s.level].max_chain;
  14748. s.strstart = 0;
  14749. s.block_start = 0;
  14750. s.lookahead = 0;
  14751. s.insert = 0;
  14752. s.match_length = s.prev_length = MIN_MATCH - 1;
  14753. s.match_available = 0;
  14754. s.ins_h = 0;
  14755. }
  14756. function DeflateState() {
  14757. this.strm = null; /* pointer back to this zlib stream */
  14758. this.status = 0; /* as the name implies */
  14759. this.pending_buf = null; /* output still pending */
  14760. this.pending_buf_size = 0; /* size of pending_buf */
  14761. this.pending_out = 0; /* next pending byte to output to the stream */
  14762. this.pending = 0; /* nb of bytes in the pending buffer */
  14763. this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
  14764. this.gzhead = null; /* gzip header information to write */
  14765. this.gzindex = 0; /* where in extra, name, or comment */
  14766. this.method = Z_DEFLATED; /* can only be DEFLATED */
  14767. this.last_flush = -1; /* value of flush param for previous deflate call */
  14768. this.w_size = 0; /* LZ77 window size (32K by default) */
  14769. this.w_bits = 0; /* log2(w_size) (8..16) */
  14770. this.w_mask = 0; /* w_size - 1 */
  14771. this.window = null;
  14772. /* Sliding window. Input bytes are read into the second half of the window,
  14773. * and move to the first half later to keep a dictionary of at least wSize
  14774. * bytes. With this organization, matches are limited to a distance of
  14775. * wSize-MAX_MATCH bytes, but this ensures that IO is always
  14776. * performed with a length multiple of the block size.
  14777. */
  14778. this.window_size = 0;
  14779. /* Actual size of window: 2*wSize, except when the user input buffer
  14780. * is directly used as sliding window.
  14781. */
  14782. this.prev = null;
  14783. /* Link to older string with same hash index. To limit the size of this
  14784. * array to 64K, this link is maintained only for the last 32K strings.
  14785. * An index in this array is thus a window index modulo 32K.
  14786. */
  14787. this.head = null; /* Heads of the hash chains or NIL. */
  14788. this.ins_h = 0; /* hash index of string to be inserted */
  14789. this.hash_size = 0; /* number of elements in hash table */
  14790. this.hash_bits = 0; /* log2(hash_size) */
  14791. this.hash_mask = 0; /* hash_size-1 */
  14792. this.hash_shift = 0;
  14793. /* Number of bits by which ins_h must be shifted at each input
  14794. * step. It must be such that after MIN_MATCH steps, the oldest
  14795. * byte no longer takes part in the hash key, that is:
  14796. * hash_shift * MIN_MATCH >= hash_bits
  14797. */
  14798. this.block_start = 0;
  14799. /* Window position at the beginning of the current output block. Gets
  14800. * negative when the window is moved backwards.
  14801. */
  14802. this.match_length = 0; /* length of best match */
  14803. this.prev_match = 0; /* previous match */
  14804. this.match_available = 0; /* set if previous match exists */
  14805. this.strstart = 0; /* start of string to insert */
  14806. this.match_start = 0; /* start of matching string */
  14807. this.lookahead = 0; /* number of valid bytes ahead in window */
  14808. this.prev_length = 0;
  14809. /* Length of the best match at previous step. Matches not greater than this
  14810. * are discarded. This is used in the lazy match evaluation.
  14811. */
  14812. this.max_chain_length = 0;
  14813. /* To speed up deflation, hash chains are never searched beyond this
  14814. * length. A higher limit improves compression ratio but degrades the
  14815. * speed.
  14816. */
  14817. this.max_lazy_match = 0;
  14818. /* Attempt to find a better match only when the current match is strictly
  14819. * smaller than this value. This mechanism is used only for compression
  14820. * levels >= 4.
  14821. */
  14822. // That's alias to max_lazy_match, don't use directly
  14823. //this.max_insert_length = 0;
  14824. /* Insert new strings in the hash table only if the match length is not
  14825. * greater than this length. This saves time but degrades compression.
  14826. * max_insert_length is used only for compression levels <= 3.
  14827. */
  14828. this.level = 0; /* compression level (1..9) */
  14829. this.strategy = 0; /* favor or force Huffman coding*/
  14830. this.good_match = 0;
  14831. /* Use a faster search when the previous match is longer than this */
  14832. this.nice_match = 0; /* Stop searching when current match exceeds this */
  14833. /* used by trees.c: */
  14834. /* Didn't use ct_data typedef below to suppress compiler warning */
  14835. // struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */
  14836. // struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */
  14837. // struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */
  14838. // Use flat array of DOUBLE size, with interleaved fata,
  14839. // because JS does not support effective
  14840. this.dyn_ltree = new utils.Buf16(HEAP_SIZE * 2);
  14841. this.dyn_dtree = new utils.Buf16((2*D_CODES+1) * 2);
  14842. this.bl_tree = new utils.Buf16((2*BL_CODES+1) * 2);
  14843. zero(this.dyn_ltree);
  14844. zero(this.dyn_dtree);
  14845. zero(this.bl_tree);
  14846. this.l_desc = null; /* desc. for literal tree */
  14847. this.d_desc = null; /* desc. for distance tree */
  14848. this.bl_desc = null; /* desc. for bit length tree */
  14849. //ush bl_count[MAX_BITS+1];
  14850. this.bl_count = new utils.Buf16(MAX_BITS+1);
  14851. /* number of codes at each bit length for an optimal tree */
  14852. //int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */
  14853. this.heap = new utils.Buf16(2*L_CODES+1); /* heap used to build the Huffman trees */
  14854. zero(this.heap);
  14855. this.heap_len = 0; /* number of elements in the heap */
  14856. this.heap_max = 0; /* element of largest frequency */
  14857. /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.
  14858. * The same heap array is used to build all trees.
  14859. */
  14860. this.depth = new utils.Buf16(2*L_CODES+1); //uch depth[2*L_CODES+1];
  14861. zero(this.depth);
  14862. /* Depth of each subtree used as tie breaker for trees of equal frequency
  14863. */
  14864. this.l_buf = 0; /* buffer index for literals or lengths */
  14865. this.lit_bufsize = 0;
  14866. /* Size of match buffer for literals/lengths. There are 4 reasons for
  14867. * limiting lit_bufsize to 64K:
  14868. * - frequencies can be kept in 16 bit counters
  14869. * - if compression is not successful for the first block, all input
  14870. * data is still in the window so we can still emit a stored block even
  14871. * when input comes from standard input. (This can also be done for
  14872. * all blocks if lit_bufsize is not greater than 32K.)
  14873. * - if compression is not successful for a file smaller than 64K, we can
  14874. * even emit a stored file instead of a stored block (saving 5 bytes).
  14875. * This is applicable only for zip (not gzip or zlib).
  14876. * - creating new Huffman trees less frequently may not provide fast
  14877. * adaptation to changes in the input data statistics. (Take for
  14878. * example a binary file with poorly compressible code followed by
  14879. * a highly compressible string table.) Smaller buffer sizes give
  14880. * fast adaptation but have of course the overhead of transmitting
  14881. * trees more frequently.
  14882. * - I can't count above 4
  14883. */
  14884. this.last_lit = 0; /* running index in l_buf */
  14885. this.d_buf = 0;
  14886. /* Buffer index for distances. To simplify the code, d_buf and l_buf have
  14887. * the same number of elements. To use different lengths, an extra flag
  14888. * array would be necessary.
  14889. */
  14890. this.opt_len = 0; /* bit length of current block with optimal trees */
  14891. this.static_len = 0; /* bit length of current block with static trees */
  14892. this.matches = 0; /* number of string matches in current block */
  14893. this.insert = 0; /* bytes at end of window left to insert */
  14894. this.bi_buf = 0;
  14895. /* Output buffer. bits are inserted starting at the bottom (least
  14896. * significant bits).
  14897. */
  14898. this.bi_valid = 0;
  14899. /* Number of valid bits in bi_buf. All bits above the last valid bit
  14900. * are always zero.
  14901. */
  14902. // Used for window memory init. We safely ignore it for JS. That makes
  14903. // sense only for pointers and memory check tools.
  14904. //this.high_water = 0;
  14905. /* High water mark offset in window for initialized bytes -- bytes above
  14906. * this are set to zero in order to avoid memory check warnings when
  14907. * longest match routines access bytes past the input. This is then
  14908. * updated to the new high water mark.
  14909. */
  14910. }
  14911. function deflateResetKeep(strm) {
  14912. var s;
  14913. if (!strm || !strm.state) {
  14914. return err(strm, Z_STREAM_ERROR);
  14915. }
  14916. strm.total_in = strm.total_out = 0;
  14917. strm.data_type = Z_UNKNOWN;
  14918. s = strm.state;
  14919. s.pending = 0;
  14920. s.pending_out = 0;
  14921. if (s.wrap < 0) {
  14922. s.wrap = -s.wrap;
  14923. /* was made negative by deflate(..., Z_FINISH); */
  14924. }
  14925. s.status = (s.wrap ? INIT_STATE : BUSY_STATE);
  14926. strm.adler = (s.wrap === 2) ?
  14927. 0 // crc32(0, Z_NULL, 0)
  14928. :
  14929. 1; // adler32(0, Z_NULL, 0)
  14930. s.last_flush = Z_NO_FLUSH;
  14931. trees._tr_init(s);
  14932. return Z_OK;
  14933. }
  14934. function deflateReset(strm) {
  14935. var ret = deflateResetKeep(strm);
  14936. if (ret === Z_OK) {
  14937. lm_init(strm.state);
  14938. }
  14939. return ret;
  14940. }
  14941. function deflateSetHeader(strm, head) {
  14942. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  14943. if (strm.state.wrap !== 2) { return Z_STREAM_ERROR; }
  14944. strm.state.gzhead = head;
  14945. return Z_OK;
  14946. }
  14947. function deflateInit2(strm, level, method, windowBits, memLevel, strategy) {
  14948. if (!strm) { // === Z_NULL
  14949. return Z_STREAM_ERROR;
  14950. }
  14951. var wrap = 1;
  14952. if (level === Z_DEFAULT_COMPRESSION) {
  14953. level = 6;
  14954. }
  14955. if (windowBits < 0) { /* suppress zlib wrapper */
  14956. wrap = 0;
  14957. windowBits = -windowBits;
  14958. }
  14959. else if (windowBits > 15) {
  14960. wrap = 2; /* write gzip wrapper instead */
  14961. windowBits -= 16;
  14962. }
  14963. if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method !== Z_DEFLATED ||
  14964. windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||
  14965. strategy < 0 || strategy > Z_FIXED) {
  14966. return err(strm, Z_STREAM_ERROR);
  14967. }
  14968. if (windowBits === 8) {
  14969. windowBits = 9;
  14970. }
  14971. /* until 256-byte window bug fixed */
  14972. var s = new DeflateState();
  14973. strm.state = s;
  14974. s.strm = strm;
  14975. s.wrap = wrap;
  14976. s.gzhead = null;
  14977. s.w_bits = windowBits;
  14978. s.w_size = 1 << s.w_bits;
  14979. s.w_mask = s.w_size - 1;
  14980. s.hash_bits = memLevel + 7;
  14981. s.hash_size = 1 << s.hash_bits;
  14982. s.hash_mask = s.hash_size - 1;
  14983. s.hash_shift = ~~((s.hash_bits + MIN_MATCH - 1) / MIN_MATCH);
  14984. s.window = new utils.Buf8(s.w_size * 2);
  14985. s.head = new utils.Buf16(s.hash_size);
  14986. s.prev = new utils.Buf16(s.w_size);
  14987. // Don't need mem init magic for JS.
  14988. //s.high_water = 0; /* nothing written to s->window yet */
  14989. s.lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */
  14990. s.pending_buf_size = s.lit_bufsize * 4;
  14991. s.pending_buf = new utils.Buf8(s.pending_buf_size);
  14992. s.d_buf = s.lit_bufsize >> 1;
  14993. s.l_buf = (1 + 2) * s.lit_bufsize;
  14994. s.level = level;
  14995. s.strategy = strategy;
  14996. s.method = method;
  14997. return deflateReset(strm);
  14998. }
  14999. function deflateInit(strm, level) {
  15000. return deflateInit2(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY);
  15001. }
  15002. function deflate(strm, flush) {
  15003. var old_flush, s;
  15004. var beg, val; // for gzip header write only
  15005. if (!strm || !strm.state ||
  15006. flush > Z_BLOCK || flush < 0) {
  15007. return strm ? err(strm, Z_STREAM_ERROR) : Z_STREAM_ERROR;
  15008. }
  15009. s = strm.state;
  15010. if (!strm.output ||
  15011. (!strm.input && strm.avail_in !== 0) ||
  15012. (s.status === FINISH_STATE && flush !== Z_FINISH)) {
  15013. return err(strm, (strm.avail_out === 0) ? Z_BUF_ERROR : Z_STREAM_ERROR);
  15014. }
  15015. s.strm = strm; /* just in case */
  15016. old_flush = s.last_flush;
  15017. s.last_flush = flush;
  15018. /* Write the header */
  15019. if (s.status === INIT_STATE) {
  15020. if (s.wrap === 2) { // GZIP header
  15021. strm.adler = 0; //crc32(0L, Z_NULL, 0);
  15022. put_byte(s, 31);
  15023. put_byte(s, 139);
  15024. put_byte(s, 8);
  15025. if (!s.gzhead) { // s->gzhead == Z_NULL
  15026. put_byte(s, 0);
  15027. put_byte(s, 0);
  15028. put_byte(s, 0);
  15029. put_byte(s, 0);
  15030. put_byte(s, 0);
  15031. put_byte(s, s.level === 9 ? 2 :
  15032. (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
  15033. 4 : 0));
  15034. put_byte(s, OS_CODE);
  15035. s.status = BUSY_STATE;
  15036. }
  15037. else {
  15038. put_byte(s, (s.gzhead.text ? 1 : 0) +
  15039. (s.gzhead.hcrc ? 2 : 0) +
  15040. (!s.gzhead.extra ? 0 : 4) +
  15041. (!s.gzhead.name ? 0 : 8) +
  15042. (!s.gzhead.comment ? 0 : 16)
  15043. );
  15044. put_byte(s, s.gzhead.time & 0xff);
  15045. put_byte(s, (s.gzhead.time >> 8) & 0xff);
  15046. put_byte(s, (s.gzhead.time >> 16) & 0xff);
  15047. put_byte(s, (s.gzhead.time >> 24) & 0xff);
  15048. put_byte(s, s.level === 9 ? 2 :
  15049. (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
  15050. 4 : 0));
  15051. put_byte(s, s.gzhead.os & 0xff);
  15052. if (s.gzhead.extra && s.gzhead.extra.length) {
  15053. put_byte(s, s.gzhead.extra.length & 0xff);
  15054. put_byte(s, (s.gzhead.extra.length >> 8) & 0xff);
  15055. }
  15056. if (s.gzhead.hcrc) {
  15057. strm.adler = crc32(strm.adler, s.pending_buf, s.pending, 0);
  15058. }
  15059. s.gzindex = 0;
  15060. s.status = EXTRA_STATE;
  15061. }
  15062. }
  15063. else // DEFLATE header
  15064. {
  15065. var header = (Z_DEFLATED + ((s.w_bits - 8) << 4)) << 8;
  15066. var level_flags = -1;
  15067. if (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2) {
  15068. level_flags = 0;
  15069. } else if (s.level < 6) {
  15070. level_flags = 1;
  15071. } else if (s.level === 6) {
  15072. level_flags = 2;
  15073. } else {
  15074. level_flags = 3;
  15075. }
  15076. header |= (level_flags << 6);
  15077. if (s.strstart !== 0) { header |= PRESET_DICT; }
  15078. header += 31 - (header % 31);
  15079. s.status = BUSY_STATE;
  15080. putShortMSB(s, header);
  15081. /* Save the adler32 of the preset dictionary: */
  15082. if (s.strstart !== 0) {
  15083. putShortMSB(s, strm.adler >>> 16);
  15084. putShortMSB(s, strm.adler & 0xffff);
  15085. }
  15086. strm.adler = 1; // adler32(0L, Z_NULL, 0);
  15087. }
  15088. }
  15089. //#ifdef GZIP
  15090. if (s.status === EXTRA_STATE) {
  15091. if (s.gzhead.extra/* != Z_NULL*/) {
  15092. beg = s.pending; /* start of bytes to update crc */
  15093. while (s.gzindex < (s.gzhead.extra.length & 0xffff)) {
  15094. if (s.pending === s.pending_buf_size) {
  15095. if (s.gzhead.hcrc && s.pending > beg) {
  15096. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  15097. }
  15098. flush_pending(strm);
  15099. beg = s.pending;
  15100. if (s.pending === s.pending_buf_size) {
  15101. break;
  15102. }
  15103. }
  15104. put_byte(s, s.gzhead.extra[s.gzindex] & 0xff);
  15105. s.gzindex++;
  15106. }
  15107. if (s.gzhead.hcrc && s.pending > beg) {
  15108. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  15109. }
  15110. if (s.gzindex === s.gzhead.extra.length) {
  15111. s.gzindex = 0;
  15112. s.status = NAME_STATE;
  15113. }
  15114. }
  15115. else {
  15116. s.status = NAME_STATE;
  15117. }
  15118. }
  15119. if (s.status === NAME_STATE) {
  15120. if (s.gzhead.name/* != Z_NULL*/) {
  15121. beg = s.pending; /* start of bytes to update crc */
  15122. //int val;
  15123. do {
  15124. if (s.pending === s.pending_buf_size) {
  15125. if (s.gzhead.hcrc && s.pending > beg) {
  15126. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  15127. }
  15128. flush_pending(strm);
  15129. beg = s.pending;
  15130. if (s.pending === s.pending_buf_size) {
  15131. val = 1;
  15132. break;
  15133. }
  15134. }
  15135. // JS specific: little magic to add zero terminator to end of string
  15136. if (s.gzindex < s.gzhead.name.length) {
  15137. val = s.gzhead.name.charCodeAt(s.gzindex++) & 0xff;
  15138. } else {
  15139. val = 0;
  15140. }
  15141. put_byte(s, val);
  15142. } while (val !== 0);
  15143. if (s.gzhead.hcrc && s.pending > beg) {
  15144. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  15145. }
  15146. if (val === 0) {
  15147. s.gzindex = 0;
  15148. s.status = COMMENT_STATE;
  15149. }
  15150. }
  15151. else {
  15152. s.status = COMMENT_STATE;
  15153. }
  15154. }
  15155. if (s.status === COMMENT_STATE) {
  15156. if (s.gzhead.comment/* != Z_NULL*/) {
  15157. beg = s.pending; /* start of bytes to update crc */
  15158. //int val;
  15159. do {
  15160. if (s.pending === s.pending_buf_size) {
  15161. if (s.gzhead.hcrc && s.pending > beg) {
  15162. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  15163. }
  15164. flush_pending(strm);
  15165. beg = s.pending;
  15166. if (s.pending === s.pending_buf_size) {
  15167. val = 1;
  15168. break;
  15169. }
  15170. }
  15171. // JS specific: little magic to add zero terminator to end of string
  15172. if (s.gzindex < s.gzhead.comment.length) {
  15173. val = s.gzhead.comment.charCodeAt(s.gzindex++) & 0xff;
  15174. } else {
  15175. val = 0;
  15176. }
  15177. put_byte(s, val);
  15178. } while (val !== 0);
  15179. if (s.gzhead.hcrc && s.pending > beg) {
  15180. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  15181. }
  15182. if (val === 0) {
  15183. s.status = HCRC_STATE;
  15184. }
  15185. }
  15186. else {
  15187. s.status = HCRC_STATE;
  15188. }
  15189. }
  15190. if (s.status === HCRC_STATE) {
  15191. if (s.gzhead.hcrc) {
  15192. if (s.pending + 2 > s.pending_buf_size) {
  15193. flush_pending(strm);
  15194. }
  15195. if (s.pending + 2 <= s.pending_buf_size) {
  15196. put_byte(s, strm.adler & 0xff);
  15197. put_byte(s, (strm.adler >> 8) & 0xff);
  15198. strm.adler = 0; //crc32(0L, Z_NULL, 0);
  15199. s.status = BUSY_STATE;
  15200. }
  15201. }
  15202. else {
  15203. s.status = BUSY_STATE;
  15204. }
  15205. }
  15206. //#endif
  15207. /* Flush as much pending output as possible */
  15208. if (s.pending !== 0) {
  15209. flush_pending(strm);
  15210. if (strm.avail_out === 0) {
  15211. /* Since avail_out is 0, deflate will be called again with
  15212. * more output space, but possibly with both pending and
  15213. * avail_in equal to zero. There won't be anything to do,
  15214. * but this is not an error situation so make sure we
  15215. * return OK instead of BUF_ERROR at next call of deflate:
  15216. */
  15217. s.last_flush = -1;
  15218. return Z_OK;
  15219. }
  15220. /* Make sure there is something to do and avoid duplicate consecutive
  15221. * flushes. For repeated and useless calls with Z_FINISH, we keep
  15222. * returning Z_STREAM_END instead of Z_BUF_ERROR.
  15223. */
  15224. } else if (strm.avail_in === 0 && rank(flush) <= rank(old_flush) &&
  15225. flush !== Z_FINISH) {
  15226. return err(strm, Z_BUF_ERROR);
  15227. }
  15228. /* User must not provide more input after the first FINISH: */
  15229. if (s.status === FINISH_STATE && strm.avail_in !== 0) {
  15230. return err(strm, Z_BUF_ERROR);
  15231. }
  15232. /* Start a new block or continue the current one.
  15233. */
  15234. if (strm.avail_in !== 0 || s.lookahead !== 0 ||
  15235. (flush !== Z_NO_FLUSH && s.status !== FINISH_STATE)) {
  15236. var bstate = (s.strategy === Z_HUFFMAN_ONLY) ? deflate_huff(s, flush) :
  15237. (s.strategy === Z_RLE ? deflate_rle(s, flush) :
  15238. configuration_table[s.level].func(s, flush));
  15239. if (bstate === BS_FINISH_STARTED || bstate === BS_FINISH_DONE) {
  15240. s.status = FINISH_STATE;
  15241. }
  15242. if (bstate === BS_NEED_MORE || bstate === BS_FINISH_STARTED) {
  15243. if (strm.avail_out === 0) {
  15244. s.last_flush = -1;
  15245. /* avoid BUF_ERROR next call, see above */
  15246. }
  15247. return Z_OK;
  15248. /* If flush != Z_NO_FLUSH && avail_out == 0, the next call
  15249. * of deflate should use the same flush parameter to make sure
  15250. * that the flush is complete. So we don't have to output an
  15251. * empty block here, this will be done at next call. This also
  15252. * ensures that for a very small output buffer, we emit at most
  15253. * one empty block.
  15254. */
  15255. }
  15256. if (bstate === BS_BLOCK_DONE) {
  15257. if (flush === Z_PARTIAL_FLUSH) {
  15258. trees._tr_align(s);
  15259. }
  15260. else if (flush !== Z_BLOCK) { /* FULL_FLUSH or SYNC_FLUSH */
  15261. trees._tr_stored_block(s, 0, 0, false);
  15262. /* For a full flush, this empty block will be recognized
  15263. * as a special marker by inflate_sync().
  15264. */
  15265. if (flush === Z_FULL_FLUSH) {
  15266. /*** CLEAR_HASH(s); ***/ /* forget history */
  15267. zero(s.head); // Fill with NIL (= 0);
  15268. if (s.lookahead === 0) {
  15269. s.strstart = 0;
  15270. s.block_start = 0;
  15271. s.insert = 0;
  15272. }
  15273. }
  15274. }
  15275. flush_pending(strm);
  15276. if (strm.avail_out === 0) {
  15277. s.last_flush = -1; /* avoid BUF_ERROR at next call, see above */
  15278. return Z_OK;
  15279. }
  15280. }
  15281. }
  15282. //Assert(strm->avail_out > 0, "bug2");
  15283. //if (strm.avail_out <= 0) { throw new Error("bug2");}
  15284. if (flush !== Z_FINISH) { return Z_OK; }
  15285. if (s.wrap <= 0) { return Z_STREAM_END; }
  15286. /* Write the trailer */
  15287. if (s.wrap === 2) {
  15288. put_byte(s, strm.adler & 0xff);
  15289. put_byte(s, (strm.adler >> 8) & 0xff);
  15290. put_byte(s, (strm.adler >> 16) & 0xff);
  15291. put_byte(s, (strm.adler >> 24) & 0xff);
  15292. put_byte(s, strm.total_in & 0xff);
  15293. put_byte(s, (strm.total_in >> 8) & 0xff);
  15294. put_byte(s, (strm.total_in >> 16) & 0xff);
  15295. put_byte(s, (strm.total_in >> 24) & 0xff);
  15296. }
  15297. else
  15298. {
  15299. putShortMSB(s, strm.adler >>> 16);
  15300. putShortMSB(s, strm.adler & 0xffff);
  15301. }
  15302. flush_pending(strm);
  15303. /* If avail_out is zero, the application will call deflate again
  15304. * to flush the rest.
  15305. */
  15306. if (s.wrap > 0) { s.wrap = -s.wrap; }
  15307. /* write the trailer only once! */
  15308. return s.pending !== 0 ? Z_OK : Z_STREAM_END;
  15309. }
  15310. function deflateEnd(strm) {
  15311. var status;
  15312. if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) {
  15313. return Z_STREAM_ERROR;
  15314. }
  15315. status = strm.state.status;
  15316. if (status !== INIT_STATE &&
  15317. status !== EXTRA_STATE &&
  15318. status !== NAME_STATE &&
  15319. status !== COMMENT_STATE &&
  15320. status !== HCRC_STATE &&
  15321. status !== BUSY_STATE &&
  15322. status !== FINISH_STATE
  15323. ) {
  15324. return err(strm, Z_STREAM_ERROR);
  15325. }
  15326. strm.state = null;
  15327. return status === BUSY_STATE ? err(strm, Z_DATA_ERROR) : Z_OK;
  15328. }
  15329. /* =========================================================================
  15330. * Copy the source state to the destination state
  15331. */
  15332. //function deflateCopy(dest, source) {
  15333. //
  15334. //}
  15335. exports.deflateInit = deflateInit;
  15336. exports.deflateInit2 = deflateInit2;
  15337. exports.deflateReset = deflateReset;
  15338. exports.deflateResetKeep = deflateResetKeep;
  15339. exports.deflateSetHeader = deflateSetHeader;
  15340. exports.deflate = deflate;
  15341. exports.deflateEnd = deflateEnd;
  15342. exports.deflateInfo = 'pako deflate (from Nodeca project)';
  15343. /* Not implemented
  15344. exports.deflateBound = deflateBound;
  15345. exports.deflateCopy = deflateCopy;
  15346. exports.deflateSetDictionary = deflateSetDictionary;
  15347. exports.deflateParams = deflateParams;
  15348. exports.deflatePending = deflatePending;
  15349. exports.deflatePrime = deflatePrime;
  15350. exports.deflateTune = deflateTune;
  15351. */
  15352. },{"../utils/common":51,"./adler32":53,"./crc32":55,"./messages":61,"./trees":62}],57:[function(require,module,exports){
  15353. 'use strict';
  15354. function GZheader() {
  15355. /* true if compressed data believed to be text */
  15356. this.text = 0;
  15357. /* modification time */
  15358. this.time = 0;
  15359. /* extra flags (not used when writing a gzip file) */
  15360. this.xflags = 0;
  15361. /* operating system */
  15362. this.os = 0;
  15363. /* pointer to extra field or Z_NULL if none */
  15364. this.extra = null;
  15365. /* extra field length (valid if extra != Z_NULL) */
  15366. this.extra_len = 0; // Actually, we don't need it in JS,
  15367. // but leave for few code modifications
  15368. //
  15369. // Setup limits is not necessary because in js we should not preallocate memory
  15370. // for inflate use constant limit in 65536 bytes
  15371. //
  15372. /* space at extra (only when reading header) */
  15373. // this.extra_max = 0;
  15374. /* pointer to zero-terminated file name or Z_NULL */
  15375. this.name = '';
  15376. /* space at name (only when reading header) */
  15377. // this.name_max = 0;
  15378. /* pointer to zero-terminated comment or Z_NULL */
  15379. this.comment = '';
  15380. /* space at comment (only when reading header) */
  15381. // this.comm_max = 0;
  15382. /* true if there was or will be a header crc */
  15383. this.hcrc = 0;
  15384. /* true when done reading gzip header (not used when writing a gzip file) */
  15385. this.done = false;
  15386. }
  15387. module.exports = GZheader;
  15388. },{}],58:[function(require,module,exports){
  15389. 'use strict';
  15390. // See state defs from inflate.js
  15391. var BAD = 30; /* got a data error -- remain here until reset */
  15392. var TYPE = 12; /* i: waiting for type bits, including last-flag bit */
  15393. /*
  15394. Decode literal, length, and distance codes and write out the resulting
  15395. literal and match bytes until either not enough input or output is
  15396. available, an end-of-block is encountered, or a data error is encountered.
  15397. When large enough input and output buffers are supplied to inflate(), for
  15398. example, a 16K input buffer and a 64K output buffer, more than 95% of the
  15399. inflate execution time is spent in this routine.
  15400. Entry assumptions:
  15401. state.mode === LEN
  15402. strm.avail_in >= 6
  15403. strm.avail_out >= 258
  15404. start >= strm.avail_out
  15405. state.bits < 8
  15406. On return, state.mode is one of:
  15407. LEN -- ran out of enough output space or enough available input
  15408. TYPE -- reached end of block code, inflate() to interpret next block
  15409. BAD -- error in block data
  15410. Notes:
  15411. - The maximum input bits used by a length/distance pair is 15 bits for the
  15412. length code, 5 bits for the length extra, 15 bits for the distance code,
  15413. and 13 bits for the distance extra. This totals 48 bits, or six bytes.
  15414. Therefore if strm.avail_in >= 6, then there is enough input to avoid
  15415. checking for available input while decoding.
  15416. - The maximum bytes that a single length/distance pair can output is 258
  15417. bytes, which is the maximum length that can be coded. inflate_fast()
  15418. requires strm.avail_out >= 258 for each loop to avoid checking for
  15419. output space.
  15420. */
  15421. module.exports = function inflate_fast(strm, start) {
  15422. var state;
  15423. var _in; /* local strm.input */
  15424. var last; /* have enough input while in < last */
  15425. var _out; /* local strm.output */
  15426. var beg; /* inflate()'s initial strm.output */
  15427. var end; /* while out < end, enough space available */
  15428. //#ifdef INFLATE_STRICT
  15429. var dmax; /* maximum distance from zlib header */
  15430. //#endif
  15431. var wsize; /* window size or zero if not using window */
  15432. var whave; /* valid bytes in the window */
  15433. var wnext; /* window write index */
  15434. // Use `s_window` instead `window`, avoid conflict with instrumentation tools
  15435. var s_window; /* allocated sliding window, if wsize != 0 */
  15436. var hold; /* local strm.hold */
  15437. var bits; /* local strm.bits */
  15438. var lcode; /* local strm.lencode */
  15439. var dcode; /* local strm.distcode */
  15440. var lmask; /* mask for first level of length codes */
  15441. var dmask; /* mask for first level of distance codes */
  15442. var here; /* retrieved table entry */
  15443. var op; /* code bits, operation, extra bits, or */
  15444. /* window position, window bytes to copy */
  15445. var len; /* match length, unused bytes */
  15446. var dist; /* match distance */
  15447. var from; /* where to copy match from */
  15448. var from_source;
  15449. var input, output; // JS specific, because we have no pointers
  15450. /* copy state to local variables */
  15451. state = strm.state;
  15452. //here = state.here;
  15453. _in = strm.next_in;
  15454. input = strm.input;
  15455. last = _in + (strm.avail_in - 5);
  15456. _out = strm.next_out;
  15457. output = strm.output;
  15458. beg = _out - (start - strm.avail_out);
  15459. end = _out + (strm.avail_out - 257);
  15460. //#ifdef INFLATE_STRICT
  15461. dmax = state.dmax;
  15462. //#endif
  15463. wsize = state.wsize;
  15464. whave = state.whave;
  15465. wnext = state.wnext;
  15466. s_window = state.window;
  15467. hold = state.hold;
  15468. bits = state.bits;
  15469. lcode = state.lencode;
  15470. dcode = state.distcode;
  15471. lmask = (1 << state.lenbits) - 1;
  15472. dmask = (1 << state.distbits) - 1;
  15473. /* decode literals and length/distances until end-of-block or not enough
  15474. input data or output space */
  15475. top:
  15476. do {
  15477. if (bits < 15) {
  15478. hold += input[_in++] << bits;
  15479. bits += 8;
  15480. hold += input[_in++] << bits;
  15481. bits += 8;
  15482. }
  15483. here = lcode[hold & lmask];
  15484. dolen:
  15485. for (;;) { // Goto emulation
  15486. op = here >>> 24/*here.bits*/;
  15487. hold >>>= op;
  15488. bits -= op;
  15489. op = (here >>> 16) & 0xff/*here.op*/;
  15490. if (op === 0) { /* literal */
  15491. //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
  15492. // "inflate: literal '%c'\n" :
  15493. // "inflate: literal 0x%02x\n", here.val));
  15494. output[_out++] = here & 0xffff/*here.val*/;
  15495. }
  15496. else if (op & 16) { /* length base */
  15497. len = here & 0xffff/*here.val*/;
  15498. op &= 15; /* number of extra bits */
  15499. if (op) {
  15500. if (bits < op) {
  15501. hold += input[_in++] << bits;
  15502. bits += 8;
  15503. }
  15504. len += hold & ((1 << op) - 1);
  15505. hold >>>= op;
  15506. bits -= op;
  15507. }
  15508. //Tracevv((stderr, "inflate: length %u\n", len));
  15509. if (bits < 15) {
  15510. hold += input[_in++] << bits;
  15511. bits += 8;
  15512. hold += input[_in++] << bits;
  15513. bits += 8;
  15514. }
  15515. here = dcode[hold & dmask];
  15516. dodist:
  15517. for (;;) { // goto emulation
  15518. op = here >>> 24/*here.bits*/;
  15519. hold >>>= op;
  15520. bits -= op;
  15521. op = (here >>> 16) & 0xff/*here.op*/;
  15522. if (op & 16) { /* distance base */
  15523. dist = here & 0xffff/*here.val*/;
  15524. op &= 15; /* number of extra bits */
  15525. if (bits < op) {
  15526. hold += input[_in++] << bits;
  15527. bits += 8;
  15528. if (bits < op) {
  15529. hold += input[_in++] << bits;
  15530. bits += 8;
  15531. }
  15532. }
  15533. dist += hold & ((1 << op) - 1);
  15534. //#ifdef INFLATE_STRICT
  15535. if (dist > dmax) {
  15536. strm.msg = 'invalid distance too far back';
  15537. state.mode = BAD;
  15538. break top;
  15539. }
  15540. //#endif
  15541. hold >>>= op;
  15542. bits -= op;
  15543. //Tracevv((stderr, "inflate: distance %u\n", dist));
  15544. op = _out - beg; /* max distance in output */
  15545. if (dist > op) { /* see if copy from window */
  15546. op = dist - op; /* distance back in window */
  15547. if (op > whave) {
  15548. if (state.sane) {
  15549. strm.msg = 'invalid distance too far back';
  15550. state.mode = BAD;
  15551. break top;
  15552. }
  15553. // (!) This block is disabled in zlib defailts,
  15554. // don't enable it for binary compatibility
  15555. //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
  15556. // if (len <= op - whave) {
  15557. // do {
  15558. // output[_out++] = 0;
  15559. // } while (--len);
  15560. // continue top;
  15561. // }
  15562. // len -= op - whave;
  15563. // do {
  15564. // output[_out++] = 0;
  15565. // } while (--op > whave);
  15566. // if (op === 0) {
  15567. // from = _out - dist;
  15568. // do {
  15569. // output[_out++] = output[from++];
  15570. // } while (--len);
  15571. // continue top;
  15572. // }
  15573. //#endif
  15574. }
  15575. from = 0; // window index
  15576. from_source = s_window;
  15577. if (wnext === 0) { /* very common case */
  15578. from += wsize - op;
  15579. if (op < len) { /* some from window */
  15580. len -= op;
  15581. do {
  15582. output[_out++] = s_window[from++];
  15583. } while (--op);
  15584. from = _out - dist; /* rest from output */
  15585. from_source = output;
  15586. }
  15587. }
  15588. else if (wnext < op) { /* wrap around window */
  15589. from += wsize + wnext - op;
  15590. op -= wnext;
  15591. if (op < len) { /* some from end of window */
  15592. len -= op;
  15593. do {
  15594. output[_out++] = s_window[from++];
  15595. } while (--op);
  15596. from = 0;
  15597. if (wnext < len) { /* some from start of window */
  15598. op = wnext;
  15599. len -= op;
  15600. do {
  15601. output[_out++] = s_window[from++];
  15602. } while (--op);
  15603. from = _out - dist; /* rest from output */
  15604. from_source = output;
  15605. }
  15606. }
  15607. }
  15608. else { /* contiguous in window */
  15609. from += wnext - op;
  15610. if (op < len) { /* some from window */
  15611. len -= op;
  15612. do {
  15613. output[_out++] = s_window[from++];
  15614. } while (--op);
  15615. from = _out - dist; /* rest from output */
  15616. from_source = output;
  15617. }
  15618. }
  15619. while (len > 2) {
  15620. output[_out++] = from_source[from++];
  15621. output[_out++] = from_source[from++];
  15622. output[_out++] = from_source[from++];
  15623. len -= 3;
  15624. }
  15625. if (len) {
  15626. output[_out++] = from_source[from++];
  15627. if (len > 1) {
  15628. output[_out++] = from_source[from++];
  15629. }
  15630. }
  15631. }
  15632. else {
  15633. from = _out - dist; /* copy direct from output */
  15634. do { /* minimum length is three */
  15635. output[_out++] = output[from++];
  15636. output[_out++] = output[from++];
  15637. output[_out++] = output[from++];
  15638. len -= 3;
  15639. } while (len > 2);
  15640. if (len) {
  15641. output[_out++] = output[from++];
  15642. if (len > 1) {
  15643. output[_out++] = output[from++];
  15644. }
  15645. }
  15646. }
  15647. }
  15648. else if ((op & 64) === 0) { /* 2nd level distance code */
  15649. here = dcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
  15650. continue dodist;
  15651. }
  15652. else {
  15653. strm.msg = 'invalid distance code';
  15654. state.mode = BAD;
  15655. break top;
  15656. }
  15657. break; // need to emulate goto via "continue"
  15658. }
  15659. }
  15660. else if ((op & 64) === 0) { /* 2nd level length code */
  15661. here = lcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
  15662. continue dolen;
  15663. }
  15664. else if (op & 32) { /* end-of-block */
  15665. //Tracevv((stderr, "inflate: end of block\n"));
  15666. state.mode = TYPE;
  15667. break top;
  15668. }
  15669. else {
  15670. strm.msg = 'invalid literal/length code';
  15671. state.mode = BAD;
  15672. break top;
  15673. }
  15674. break; // need to emulate goto via "continue"
  15675. }
  15676. } while (_in < last && _out < end);
  15677. /* return unused bytes (on entry, bits < 8, so in won't go too far back) */
  15678. len = bits >> 3;
  15679. _in -= len;
  15680. bits -= len << 3;
  15681. hold &= (1 << bits) - 1;
  15682. /* update state and return */
  15683. strm.next_in = _in;
  15684. strm.next_out = _out;
  15685. strm.avail_in = (_in < last ? 5 + (last - _in) : 5 - (_in - last));
  15686. strm.avail_out = (_out < end ? 257 + (end - _out) : 257 - (_out - end));
  15687. state.hold = hold;
  15688. state.bits = bits;
  15689. return;
  15690. };
  15691. },{}],59:[function(require,module,exports){
  15692. 'use strict';
  15693. var utils = require('../utils/common');
  15694. var adler32 = require('./adler32');
  15695. var crc32 = require('./crc32');
  15696. var inflate_fast = require('./inffast');
  15697. var inflate_table = require('./inftrees');
  15698. var CODES = 0;
  15699. var LENS = 1;
  15700. var DISTS = 2;
  15701. /* Public constants ==========================================================*/
  15702. /* ===========================================================================*/
  15703. /* Allowed flush values; see deflate() and inflate() below for details */
  15704. //var Z_NO_FLUSH = 0;
  15705. //var Z_PARTIAL_FLUSH = 1;
  15706. //var Z_SYNC_FLUSH = 2;
  15707. //var Z_FULL_FLUSH = 3;
  15708. var Z_FINISH = 4;
  15709. var Z_BLOCK = 5;
  15710. var Z_TREES = 6;
  15711. /* Return codes for the compression/decompression functions. Negative values
  15712. * are errors, positive values are used for special but normal events.
  15713. */
  15714. var Z_OK = 0;
  15715. var Z_STREAM_END = 1;
  15716. var Z_NEED_DICT = 2;
  15717. //var Z_ERRNO = -1;
  15718. var Z_STREAM_ERROR = -2;
  15719. var Z_DATA_ERROR = -3;
  15720. var Z_MEM_ERROR = -4;
  15721. var Z_BUF_ERROR = -5;
  15722. //var Z_VERSION_ERROR = -6;
  15723. /* The deflate compression method */
  15724. var Z_DEFLATED = 8;
  15725. /* STATES ====================================================================*/
  15726. /* ===========================================================================*/
  15727. var HEAD = 1; /* i: waiting for magic header */
  15728. var FLAGS = 2; /* i: waiting for method and flags (gzip) */
  15729. var TIME = 3; /* i: waiting for modification time (gzip) */
  15730. var OS = 4; /* i: waiting for extra flags and operating system (gzip) */
  15731. var EXLEN = 5; /* i: waiting for extra length (gzip) */
  15732. var EXTRA = 6; /* i: waiting for extra bytes (gzip) */
  15733. var NAME = 7; /* i: waiting for end of file name (gzip) */
  15734. var COMMENT = 8; /* i: waiting for end of comment (gzip) */
  15735. var HCRC = 9; /* i: waiting for header crc (gzip) */
  15736. var DICTID = 10; /* i: waiting for dictionary check value */
  15737. var DICT = 11; /* waiting for inflateSetDictionary() call */
  15738. var TYPE = 12; /* i: waiting for type bits, including last-flag bit */
  15739. var TYPEDO = 13; /* i: same, but skip check to exit inflate on new block */
  15740. var STORED = 14; /* i: waiting for stored size (length and complement) */
  15741. var COPY_ = 15; /* i/o: same as COPY below, but only first time in */
  15742. var COPY = 16; /* i/o: waiting for input or output to copy stored block */
  15743. var TABLE = 17; /* i: waiting for dynamic block table lengths */
  15744. var LENLENS = 18; /* i: waiting for code length code lengths */
  15745. var CODELENS = 19; /* i: waiting for length/lit and distance code lengths */
  15746. var LEN_ = 20; /* i: same as LEN below, but only first time in */
  15747. var LEN = 21; /* i: waiting for length/lit/eob code */
  15748. var LENEXT = 22; /* i: waiting for length extra bits */
  15749. var DIST = 23; /* i: waiting for distance code */
  15750. var DISTEXT = 24; /* i: waiting for distance extra bits */
  15751. var MATCH = 25; /* o: waiting for output space to copy string */
  15752. var LIT = 26; /* o: waiting for output space to write literal */
  15753. var CHECK = 27; /* i: waiting for 32-bit check value */
  15754. var LENGTH = 28; /* i: waiting for 32-bit length (gzip) */
  15755. var DONE = 29; /* finished check, done -- remain here until reset */
  15756. var BAD = 30; /* got a data error -- remain here until reset */
  15757. var MEM = 31; /* got an inflate() memory error -- remain here until reset */
  15758. var SYNC = 32; /* looking for synchronization bytes to restart inflate() */
  15759. /* ===========================================================================*/
  15760. var ENOUGH_LENS = 852;
  15761. var ENOUGH_DISTS = 592;
  15762. //var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
  15763. var MAX_WBITS = 15;
  15764. /* 32K LZ77 window */
  15765. var DEF_WBITS = MAX_WBITS;
  15766. function ZSWAP32(q) {
  15767. return (((q >>> 24) & 0xff) +
  15768. ((q >>> 8) & 0xff00) +
  15769. ((q & 0xff00) << 8) +
  15770. ((q & 0xff) << 24));
  15771. }
  15772. function InflateState() {
  15773. this.mode = 0; /* current inflate mode */
  15774. this.last = false; /* true if processing last block */
  15775. this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
  15776. this.havedict = false; /* true if dictionary provided */
  15777. this.flags = 0; /* gzip header method and flags (0 if zlib) */
  15778. this.dmax = 0; /* zlib header max distance (INFLATE_STRICT) */
  15779. this.check = 0; /* protected copy of check value */
  15780. this.total = 0; /* protected copy of output count */
  15781. // TODO: may be {}
  15782. this.head = null; /* where to save gzip header information */
  15783. /* sliding window */
  15784. this.wbits = 0; /* log base 2 of requested window size */
  15785. this.wsize = 0; /* window size or zero if not using window */
  15786. this.whave = 0; /* valid bytes in the window */
  15787. this.wnext = 0; /* window write index */
  15788. this.window = null; /* allocated sliding window, if needed */
  15789. /* bit accumulator */
  15790. this.hold = 0; /* input bit accumulator */
  15791. this.bits = 0; /* number of bits in "in" */
  15792. /* for string and stored block copying */
  15793. this.length = 0; /* literal or length of data to copy */
  15794. this.offset = 0; /* distance back to copy string from */
  15795. /* for table and code decoding */
  15796. this.extra = 0; /* extra bits needed */
  15797. /* fixed and dynamic code tables */
  15798. this.lencode = null; /* starting table for length/literal codes */
  15799. this.distcode = null; /* starting table for distance codes */
  15800. this.lenbits = 0; /* index bits for lencode */
  15801. this.distbits = 0; /* index bits for distcode */
  15802. /* dynamic table building */
  15803. this.ncode = 0; /* number of code length code lengths */
  15804. this.nlen = 0; /* number of length code lengths */
  15805. this.ndist = 0; /* number of distance code lengths */
  15806. this.have = 0; /* number of code lengths in lens[] */
  15807. this.next = null; /* next available space in codes[] */
  15808. this.lens = new utils.Buf16(320); /* temporary storage for code lengths */
  15809. this.work = new utils.Buf16(288); /* work area for code table building */
  15810. /*
  15811. because we don't have pointers in js, we use lencode and distcode directly
  15812. as buffers so we don't need codes
  15813. */
  15814. //this.codes = new utils.Buf32(ENOUGH); /* space for code tables */
  15815. this.lendyn = null; /* dynamic table for length/literal codes (JS specific) */
  15816. this.distdyn = null; /* dynamic table for distance codes (JS specific) */
  15817. this.sane = 0; /* if false, allow invalid distance too far */
  15818. this.back = 0; /* bits back of last unprocessed length/lit */
  15819. this.was = 0; /* initial length of match */
  15820. }
  15821. function inflateResetKeep(strm) {
  15822. var state;
  15823. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  15824. state = strm.state;
  15825. strm.total_in = strm.total_out = state.total = 0;
  15826. strm.msg = ''; /*Z_NULL*/
  15827. if (state.wrap) { /* to support ill-conceived Java test suite */
  15828. strm.adler = state.wrap & 1;
  15829. }
  15830. state.mode = HEAD;
  15831. state.last = 0;
  15832. state.havedict = 0;
  15833. state.dmax = 32768;
  15834. state.head = null/*Z_NULL*/;
  15835. state.hold = 0;
  15836. state.bits = 0;
  15837. //state.lencode = state.distcode = state.next = state.codes;
  15838. state.lencode = state.lendyn = new utils.Buf32(ENOUGH_LENS);
  15839. state.distcode = state.distdyn = new utils.Buf32(ENOUGH_DISTS);
  15840. state.sane = 1;
  15841. state.back = -1;
  15842. //Tracev((stderr, "inflate: reset\n"));
  15843. return Z_OK;
  15844. }
  15845. function inflateReset(strm) {
  15846. var state;
  15847. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  15848. state = strm.state;
  15849. state.wsize = 0;
  15850. state.whave = 0;
  15851. state.wnext = 0;
  15852. return inflateResetKeep(strm);
  15853. }
  15854. function inflateReset2(strm, windowBits) {
  15855. var wrap;
  15856. var state;
  15857. /* get the state */
  15858. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  15859. state = strm.state;
  15860. /* extract wrap request from windowBits parameter */
  15861. if (windowBits < 0) {
  15862. wrap = 0;
  15863. windowBits = -windowBits;
  15864. }
  15865. else {
  15866. wrap = (windowBits >> 4) + 1;
  15867. if (windowBits < 48) {
  15868. windowBits &= 15;
  15869. }
  15870. }
  15871. /* set number of window bits, free window if different */
  15872. if (windowBits && (windowBits < 8 || windowBits > 15)) {
  15873. return Z_STREAM_ERROR;
  15874. }
  15875. if (state.window !== null && state.wbits !== windowBits) {
  15876. state.window = null;
  15877. }
  15878. /* update state and reset the rest of it */
  15879. state.wrap = wrap;
  15880. state.wbits = windowBits;
  15881. return inflateReset(strm);
  15882. }
  15883. function inflateInit2(strm, windowBits) {
  15884. var ret;
  15885. var state;
  15886. if (!strm) { return Z_STREAM_ERROR; }
  15887. //strm.msg = Z_NULL; /* in case we return an error */
  15888. state = new InflateState();
  15889. //if (state === Z_NULL) return Z_MEM_ERROR;
  15890. //Tracev((stderr, "inflate: allocated\n"));
  15891. strm.state = state;
  15892. state.window = null/*Z_NULL*/;
  15893. ret = inflateReset2(strm, windowBits);
  15894. if (ret !== Z_OK) {
  15895. strm.state = null/*Z_NULL*/;
  15896. }
  15897. return ret;
  15898. }
  15899. function inflateInit(strm) {
  15900. return inflateInit2(strm, DEF_WBITS);
  15901. }
  15902. /*
  15903. Return state with length and distance decoding tables and index sizes set to
  15904. fixed code decoding. Normally this returns fixed tables from inffixed.h.
  15905. If BUILDFIXED is defined, then instead this routine builds the tables the
  15906. first time it's called, and returns those tables the first time and
  15907. thereafter. This reduces the size of the code by about 2K bytes, in
  15908. exchange for a little execution time. However, BUILDFIXED should not be
  15909. used for threaded applications, since the rewriting of the tables and virgin
  15910. may not be thread-safe.
  15911. */
  15912. var virgin = true;
  15913. var lenfix, distfix; // We have no pointers in JS, so keep tables separate
  15914. function fixedtables(state) {
  15915. /* build fixed huffman tables if first call (may not be thread safe) */
  15916. if (virgin) {
  15917. var sym;
  15918. lenfix = new utils.Buf32(512);
  15919. distfix = new utils.Buf32(32);
  15920. /* literal/length table */
  15921. sym = 0;
  15922. while (sym < 144) { state.lens[sym++] = 8; }
  15923. while (sym < 256) { state.lens[sym++] = 9; }
  15924. while (sym < 280) { state.lens[sym++] = 7; }
  15925. while (sym < 288) { state.lens[sym++] = 8; }
  15926. inflate_table(LENS, state.lens, 0, 288, lenfix, 0, state.work, {bits: 9});
  15927. /* distance table */
  15928. sym = 0;
  15929. while (sym < 32) { state.lens[sym++] = 5; }
  15930. inflate_table(DISTS, state.lens, 0, 32, distfix, 0, state.work, {bits: 5});
  15931. /* do this just once */
  15932. virgin = false;
  15933. }
  15934. state.lencode = lenfix;
  15935. state.lenbits = 9;
  15936. state.distcode = distfix;
  15937. state.distbits = 5;
  15938. }
  15939. /*
  15940. Update the window with the last wsize (normally 32K) bytes written before
  15941. returning. If window does not exist yet, create it. This is only called
  15942. when a window is already in use, or when output has been written during this
  15943. inflate call, but the end of the deflate stream has not been reached yet.
  15944. It is also called to create a window for dictionary data when a dictionary
  15945. is loaded.
  15946. Providing output buffers larger than 32K to inflate() should provide a speed
  15947. advantage, since only the last 32K of output is copied to the sliding window
  15948. upon return from inflate(), and since all distances after the first 32K of
  15949. output will fall in the output data, making match copies simpler and faster.
  15950. The advantage may be dependent on the size of the processor's data caches.
  15951. */
  15952. function updatewindow(strm, src, end, copy) {
  15953. var dist;
  15954. var state = strm.state;
  15955. /* if it hasn't been done already, allocate space for the window */
  15956. if (state.window === null) {
  15957. state.wsize = 1 << state.wbits;
  15958. state.wnext = 0;
  15959. state.whave = 0;
  15960. state.window = new utils.Buf8(state.wsize);
  15961. }
  15962. /* copy state->wsize or less output bytes into the circular window */
  15963. if (copy >= state.wsize) {
  15964. utils.arraySet(state.window,src, end - state.wsize, state.wsize, 0);
  15965. state.wnext = 0;
  15966. state.whave = state.wsize;
  15967. }
  15968. else {
  15969. dist = state.wsize - state.wnext;
  15970. if (dist > copy) {
  15971. dist = copy;
  15972. }
  15973. //zmemcpy(state->window + state->wnext, end - copy, dist);
  15974. utils.arraySet(state.window,src, end - copy, dist, state.wnext);
  15975. copy -= dist;
  15976. if (copy) {
  15977. //zmemcpy(state->window, end - copy, copy);
  15978. utils.arraySet(state.window,src, end - copy, copy, 0);
  15979. state.wnext = copy;
  15980. state.whave = state.wsize;
  15981. }
  15982. else {
  15983. state.wnext += dist;
  15984. if (state.wnext === state.wsize) { state.wnext = 0; }
  15985. if (state.whave < state.wsize) { state.whave += dist; }
  15986. }
  15987. }
  15988. return 0;
  15989. }
  15990. function inflate(strm, flush) {
  15991. var state;
  15992. var input, output; // input/output buffers
  15993. var next; /* next input INDEX */
  15994. var put; /* next output INDEX */
  15995. var have, left; /* available input and output */
  15996. var hold; /* bit buffer */
  15997. var bits; /* bits in bit buffer */
  15998. var _in, _out; /* save starting available input and output */
  15999. var copy; /* number of stored or match bytes to copy */
  16000. var from; /* where to copy match bytes from */
  16001. var from_source;
  16002. var here = 0; /* current decoding table entry */
  16003. var here_bits, here_op, here_val; // paked "here" denormalized (JS specific)
  16004. //var last; /* parent table entry */
  16005. var last_bits, last_op, last_val; // paked "last" denormalized (JS specific)
  16006. var len; /* length to copy for repeats, bits to drop */
  16007. var ret; /* return code */
  16008. var hbuf = new utils.Buf8(4); /* buffer for gzip header crc calculation */
  16009. var opts;
  16010. var n; // temporary var for NEED_BITS
  16011. var order = /* permutation of code lengths */
  16012. [16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15];
  16013. if (!strm || !strm.state || !strm.output ||
  16014. (!strm.input && strm.avail_in !== 0)) {
  16015. return Z_STREAM_ERROR;
  16016. }
  16017. state = strm.state;
  16018. if (state.mode === TYPE) { state.mode = TYPEDO; } /* skip check */
  16019. //--- LOAD() ---
  16020. put = strm.next_out;
  16021. output = strm.output;
  16022. left = strm.avail_out;
  16023. next = strm.next_in;
  16024. input = strm.input;
  16025. have = strm.avail_in;
  16026. hold = state.hold;
  16027. bits = state.bits;
  16028. //---
  16029. _in = have;
  16030. _out = left;
  16031. ret = Z_OK;
  16032. inf_leave: // goto emulation
  16033. for (;;) {
  16034. switch (state.mode) {
  16035. case HEAD:
  16036. if (state.wrap === 0) {
  16037. state.mode = TYPEDO;
  16038. break;
  16039. }
  16040. //=== NEEDBITS(16);
  16041. while (bits < 16) {
  16042. if (have === 0) { break inf_leave; }
  16043. have--;
  16044. hold += input[next++] << bits;
  16045. bits += 8;
  16046. }
  16047. //===//
  16048. if ((state.wrap & 2) && hold === 0x8b1f) { /* gzip header */
  16049. state.check = 0/*crc32(0L, Z_NULL, 0)*/;
  16050. //=== CRC2(state.check, hold);
  16051. hbuf[0] = hold & 0xff;
  16052. hbuf[1] = (hold >>> 8) & 0xff;
  16053. state.check = crc32(state.check, hbuf, 2, 0);
  16054. //===//
  16055. //=== INITBITS();
  16056. hold = 0;
  16057. bits = 0;
  16058. //===//
  16059. state.mode = FLAGS;
  16060. break;
  16061. }
  16062. state.flags = 0; /* expect zlib header */
  16063. if (state.head) {
  16064. state.head.done = false;
  16065. }
  16066. if (!(state.wrap & 1) || /* check if zlib header allowed */
  16067. (((hold & 0xff)/*BITS(8)*/ << 8) + (hold >> 8)) % 31) {
  16068. strm.msg = 'incorrect header check';
  16069. state.mode = BAD;
  16070. break;
  16071. }
  16072. if ((hold & 0x0f)/*BITS(4)*/ !== Z_DEFLATED) {
  16073. strm.msg = 'unknown compression method';
  16074. state.mode = BAD;
  16075. break;
  16076. }
  16077. //--- DROPBITS(4) ---//
  16078. hold >>>= 4;
  16079. bits -= 4;
  16080. //---//
  16081. len = (hold & 0x0f)/*BITS(4)*/ + 8;
  16082. if (state.wbits === 0) {
  16083. state.wbits = len;
  16084. }
  16085. else if (len > state.wbits) {
  16086. strm.msg = 'invalid window size';
  16087. state.mode = BAD;
  16088. break;
  16089. }
  16090. state.dmax = 1 << len;
  16091. //Tracev((stderr, "inflate: zlib header ok\n"));
  16092. strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
  16093. state.mode = hold & 0x200 ? DICTID : TYPE;
  16094. //=== INITBITS();
  16095. hold = 0;
  16096. bits = 0;
  16097. //===//
  16098. break;
  16099. case FLAGS:
  16100. //=== NEEDBITS(16); */
  16101. while (bits < 16) {
  16102. if (have === 0) { break inf_leave; }
  16103. have--;
  16104. hold += input[next++] << bits;
  16105. bits += 8;
  16106. }
  16107. //===//
  16108. state.flags = hold;
  16109. if ((state.flags & 0xff) !== Z_DEFLATED) {
  16110. strm.msg = 'unknown compression method';
  16111. state.mode = BAD;
  16112. break;
  16113. }
  16114. if (state.flags & 0xe000) {
  16115. strm.msg = 'unknown header flags set';
  16116. state.mode = BAD;
  16117. break;
  16118. }
  16119. if (state.head) {
  16120. state.head.text = ((hold >> 8) & 1);
  16121. }
  16122. if (state.flags & 0x0200) {
  16123. //=== CRC2(state.check, hold);
  16124. hbuf[0] = hold & 0xff;
  16125. hbuf[1] = (hold >>> 8) & 0xff;
  16126. state.check = crc32(state.check, hbuf, 2, 0);
  16127. //===//
  16128. }
  16129. //=== INITBITS();
  16130. hold = 0;
  16131. bits = 0;
  16132. //===//
  16133. state.mode = TIME;
  16134. /* falls through */
  16135. case TIME:
  16136. //=== NEEDBITS(32); */
  16137. while (bits < 32) {
  16138. if (have === 0) { break inf_leave; }
  16139. have--;
  16140. hold += input[next++] << bits;
  16141. bits += 8;
  16142. }
  16143. //===//
  16144. if (state.head) {
  16145. state.head.time = hold;
  16146. }
  16147. if (state.flags & 0x0200) {
  16148. //=== CRC4(state.check, hold)
  16149. hbuf[0] = hold & 0xff;
  16150. hbuf[1] = (hold >>> 8) & 0xff;
  16151. hbuf[2] = (hold >>> 16) & 0xff;
  16152. hbuf[3] = (hold >>> 24) & 0xff;
  16153. state.check = crc32(state.check, hbuf, 4, 0);
  16154. //===
  16155. }
  16156. //=== INITBITS();
  16157. hold = 0;
  16158. bits = 0;
  16159. //===//
  16160. state.mode = OS;
  16161. /* falls through */
  16162. case OS:
  16163. //=== NEEDBITS(16); */
  16164. while (bits < 16) {
  16165. if (have === 0) { break inf_leave; }
  16166. have--;
  16167. hold += input[next++] << bits;
  16168. bits += 8;
  16169. }
  16170. //===//
  16171. if (state.head) {
  16172. state.head.xflags = (hold & 0xff);
  16173. state.head.os = (hold >> 8);
  16174. }
  16175. if (state.flags & 0x0200) {
  16176. //=== CRC2(state.check, hold);
  16177. hbuf[0] = hold & 0xff;
  16178. hbuf[1] = (hold >>> 8) & 0xff;
  16179. state.check = crc32(state.check, hbuf, 2, 0);
  16180. //===//
  16181. }
  16182. //=== INITBITS();
  16183. hold = 0;
  16184. bits = 0;
  16185. //===//
  16186. state.mode = EXLEN;
  16187. /* falls through */
  16188. case EXLEN:
  16189. if (state.flags & 0x0400) {
  16190. //=== NEEDBITS(16); */
  16191. while (bits < 16) {
  16192. if (have === 0) { break inf_leave; }
  16193. have--;
  16194. hold += input[next++] << bits;
  16195. bits += 8;
  16196. }
  16197. //===//
  16198. state.length = hold;
  16199. if (state.head) {
  16200. state.head.extra_len = hold;
  16201. }
  16202. if (state.flags & 0x0200) {
  16203. //=== CRC2(state.check, hold);
  16204. hbuf[0] = hold & 0xff;
  16205. hbuf[1] = (hold >>> 8) & 0xff;
  16206. state.check = crc32(state.check, hbuf, 2, 0);
  16207. //===//
  16208. }
  16209. //=== INITBITS();
  16210. hold = 0;
  16211. bits = 0;
  16212. //===//
  16213. }
  16214. else if (state.head) {
  16215. state.head.extra = null/*Z_NULL*/;
  16216. }
  16217. state.mode = EXTRA;
  16218. /* falls through */
  16219. case EXTRA:
  16220. if (state.flags & 0x0400) {
  16221. copy = state.length;
  16222. if (copy > have) { copy = have; }
  16223. if (copy) {
  16224. if (state.head) {
  16225. len = state.head.extra_len - state.length;
  16226. if (!state.head.extra) {
  16227. // Use untyped array for more conveniend processing later
  16228. state.head.extra = new Array(state.head.extra_len);
  16229. }
  16230. utils.arraySet(
  16231. state.head.extra,
  16232. input,
  16233. next,
  16234. // extra field is limited to 65536 bytes
  16235. // - no need for additional size check
  16236. copy,
  16237. /*len + copy > state.head.extra_max - len ? state.head.extra_max : copy,*/
  16238. len
  16239. );
  16240. //zmemcpy(state.head.extra + len, next,
  16241. // len + copy > state.head.extra_max ?
  16242. // state.head.extra_max - len : copy);
  16243. }
  16244. if (state.flags & 0x0200) {
  16245. state.check = crc32(state.check, input, copy, next);
  16246. }
  16247. have -= copy;
  16248. next += copy;
  16249. state.length -= copy;
  16250. }
  16251. if (state.length) { break inf_leave; }
  16252. }
  16253. state.length = 0;
  16254. state.mode = NAME;
  16255. /* falls through */
  16256. case NAME:
  16257. if (state.flags & 0x0800) {
  16258. if (have === 0) { break inf_leave; }
  16259. copy = 0;
  16260. do {
  16261. // TODO: 2 or 1 bytes?
  16262. len = input[next + copy++];
  16263. /* use constant limit because in js we should not preallocate memory */
  16264. if (state.head && len &&
  16265. (state.length < 65536 /*state.head.name_max*/)) {
  16266. state.head.name += String.fromCharCode(len);
  16267. }
  16268. } while (len && copy < have);
  16269. if (state.flags & 0x0200) {
  16270. state.check = crc32(state.check, input, copy, next);
  16271. }
  16272. have -= copy;
  16273. next += copy;
  16274. if (len) { break inf_leave; }
  16275. }
  16276. else if (state.head) {
  16277. state.head.name = null;
  16278. }
  16279. state.length = 0;
  16280. state.mode = COMMENT;
  16281. /* falls through */
  16282. case COMMENT:
  16283. if (state.flags & 0x1000) {
  16284. if (have === 0) { break inf_leave; }
  16285. copy = 0;
  16286. do {
  16287. len = input[next + copy++];
  16288. /* use constant limit because in js we should not preallocate memory */
  16289. if (state.head && len &&
  16290. (state.length < 65536 /*state.head.comm_max*/)) {
  16291. state.head.comment += String.fromCharCode(len);
  16292. }
  16293. } while (len && copy < have);
  16294. if (state.flags & 0x0200) {
  16295. state.check = crc32(state.check, input, copy, next);
  16296. }
  16297. have -= copy;
  16298. next += copy;
  16299. if (len) { break inf_leave; }
  16300. }
  16301. else if (state.head) {
  16302. state.head.comment = null;
  16303. }
  16304. state.mode = HCRC;
  16305. /* falls through */
  16306. case HCRC:
  16307. if (state.flags & 0x0200) {
  16308. //=== NEEDBITS(16); */
  16309. while (bits < 16) {
  16310. if (have === 0) { break inf_leave; }
  16311. have--;
  16312. hold += input[next++] << bits;
  16313. bits += 8;
  16314. }
  16315. //===//
  16316. if (hold !== (state.check & 0xffff)) {
  16317. strm.msg = 'header crc mismatch';
  16318. state.mode = BAD;
  16319. break;
  16320. }
  16321. //=== INITBITS();
  16322. hold = 0;
  16323. bits = 0;
  16324. //===//
  16325. }
  16326. if (state.head) {
  16327. state.head.hcrc = ((state.flags >> 9) & 1);
  16328. state.head.done = true;
  16329. }
  16330. strm.adler = state.check = 0 /*crc32(0L, Z_NULL, 0)*/;
  16331. state.mode = TYPE;
  16332. break;
  16333. case DICTID:
  16334. //=== NEEDBITS(32); */
  16335. while (bits < 32) {
  16336. if (have === 0) { break inf_leave; }
  16337. have--;
  16338. hold += input[next++] << bits;
  16339. bits += 8;
  16340. }
  16341. //===//
  16342. strm.adler = state.check = ZSWAP32(hold);
  16343. //=== INITBITS();
  16344. hold = 0;
  16345. bits = 0;
  16346. //===//
  16347. state.mode = DICT;
  16348. /* falls through */
  16349. case DICT:
  16350. if (state.havedict === 0) {
  16351. //--- RESTORE() ---
  16352. strm.next_out = put;
  16353. strm.avail_out = left;
  16354. strm.next_in = next;
  16355. strm.avail_in = have;
  16356. state.hold = hold;
  16357. state.bits = bits;
  16358. //---
  16359. return Z_NEED_DICT;
  16360. }
  16361. strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
  16362. state.mode = TYPE;
  16363. /* falls through */
  16364. case TYPE:
  16365. if (flush === Z_BLOCK || flush === Z_TREES) { break inf_leave; }
  16366. /* falls through */
  16367. case TYPEDO:
  16368. if (state.last) {
  16369. //--- BYTEBITS() ---//
  16370. hold >>>= bits & 7;
  16371. bits -= bits & 7;
  16372. //---//
  16373. state.mode = CHECK;
  16374. break;
  16375. }
  16376. //=== NEEDBITS(3); */
  16377. while (bits < 3) {
  16378. if (have === 0) { break inf_leave; }
  16379. have--;
  16380. hold += input[next++] << bits;
  16381. bits += 8;
  16382. }
  16383. //===//
  16384. state.last = (hold & 0x01)/*BITS(1)*/;
  16385. //--- DROPBITS(1) ---//
  16386. hold >>>= 1;
  16387. bits -= 1;
  16388. //---//
  16389. switch ((hold & 0x03)/*BITS(2)*/) {
  16390. case 0: /* stored block */
  16391. //Tracev((stderr, "inflate: stored block%s\n",
  16392. // state.last ? " (last)" : ""));
  16393. state.mode = STORED;
  16394. break;
  16395. case 1: /* fixed block */
  16396. fixedtables(state);
  16397. //Tracev((stderr, "inflate: fixed codes block%s\n",
  16398. // state.last ? " (last)" : ""));
  16399. state.mode = LEN_; /* decode codes */
  16400. if (flush === Z_TREES) {
  16401. //--- DROPBITS(2) ---//
  16402. hold >>>= 2;
  16403. bits -= 2;
  16404. //---//
  16405. break inf_leave;
  16406. }
  16407. break;
  16408. case 2: /* dynamic block */
  16409. //Tracev((stderr, "inflate: dynamic codes block%s\n",
  16410. // state.last ? " (last)" : ""));
  16411. state.mode = TABLE;
  16412. break;
  16413. case 3:
  16414. strm.msg = 'invalid block type';
  16415. state.mode = BAD;
  16416. }
  16417. //--- DROPBITS(2) ---//
  16418. hold >>>= 2;
  16419. bits -= 2;
  16420. //---//
  16421. break;
  16422. case STORED:
  16423. //--- BYTEBITS() ---// /* go to byte boundary */
  16424. hold >>>= bits & 7;
  16425. bits -= bits & 7;
  16426. //---//
  16427. //=== NEEDBITS(32); */
  16428. while (bits < 32) {
  16429. if (have === 0) { break inf_leave; }
  16430. have--;
  16431. hold += input[next++] << bits;
  16432. bits += 8;
  16433. }
  16434. //===//
  16435. if ((hold & 0xffff) !== ((hold >>> 16) ^ 0xffff)) {
  16436. strm.msg = 'invalid stored block lengths';
  16437. state.mode = BAD;
  16438. break;
  16439. }
  16440. state.length = hold & 0xffff;
  16441. //Tracev((stderr, "inflate: stored length %u\n",
  16442. // state.length));
  16443. //=== INITBITS();
  16444. hold = 0;
  16445. bits = 0;
  16446. //===//
  16447. state.mode = COPY_;
  16448. if (flush === Z_TREES) { break inf_leave; }
  16449. /* falls through */
  16450. case COPY_:
  16451. state.mode = COPY;
  16452. /* falls through */
  16453. case COPY:
  16454. copy = state.length;
  16455. if (copy) {
  16456. if (copy > have) { copy = have; }
  16457. if (copy > left) { copy = left; }
  16458. if (copy === 0) { break inf_leave; }
  16459. //--- zmemcpy(put, next, copy); ---
  16460. utils.arraySet(output, input, next, copy, put);
  16461. //---//
  16462. have -= copy;
  16463. next += copy;
  16464. left -= copy;
  16465. put += copy;
  16466. state.length -= copy;
  16467. break;
  16468. }
  16469. //Tracev((stderr, "inflate: stored end\n"));
  16470. state.mode = TYPE;
  16471. break;
  16472. case TABLE:
  16473. //=== NEEDBITS(14); */
  16474. while (bits < 14) {
  16475. if (have === 0) { break inf_leave; }
  16476. have--;
  16477. hold += input[next++] << bits;
  16478. bits += 8;
  16479. }
  16480. //===//
  16481. state.nlen = (hold & 0x1f)/*BITS(5)*/ + 257;
  16482. //--- DROPBITS(5) ---//
  16483. hold >>>= 5;
  16484. bits -= 5;
  16485. //---//
  16486. state.ndist = (hold & 0x1f)/*BITS(5)*/ + 1;
  16487. //--- DROPBITS(5) ---//
  16488. hold >>>= 5;
  16489. bits -= 5;
  16490. //---//
  16491. state.ncode = (hold & 0x0f)/*BITS(4)*/ + 4;
  16492. //--- DROPBITS(4) ---//
  16493. hold >>>= 4;
  16494. bits -= 4;
  16495. //---//
  16496. //#ifndef PKZIP_BUG_WORKAROUND
  16497. if (state.nlen > 286 || state.ndist > 30) {
  16498. strm.msg = 'too many length or distance symbols';
  16499. state.mode = BAD;
  16500. break;
  16501. }
  16502. //#endif
  16503. //Tracev((stderr, "inflate: table sizes ok\n"));
  16504. state.have = 0;
  16505. state.mode = LENLENS;
  16506. /* falls through */
  16507. case LENLENS:
  16508. while (state.have < state.ncode) {
  16509. //=== NEEDBITS(3);
  16510. while (bits < 3) {
  16511. if (have === 0) { break inf_leave; }
  16512. have--;
  16513. hold += input[next++] << bits;
  16514. bits += 8;
  16515. }
  16516. //===//
  16517. state.lens[order[state.have++]] = (hold & 0x07);//BITS(3);
  16518. //--- DROPBITS(3) ---//
  16519. hold >>>= 3;
  16520. bits -= 3;
  16521. //---//
  16522. }
  16523. while (state.have < 19) {
  16524. state.lens[order[state.have++]] = 0;
  16525. }
  16526. // We have separate tables & no pointers. 2 commented lines below not needed.
  16527. //state.next = state.codes;
  16528. //state.lencode = state.next;
  16529. // Switch to use dynamic table
  16530. state.lencode = state.lendyn;
  16531. state.lenbits = 7;
  16532. opts = {bits: state.lenbits};
  16533. ret = inflate_table(CODES, state.lens, 0, 19, state.lencode, 0, state.work, opts);
  16534. state.lenbits = opts.bits;
  16535. if (ret) {
  16536. strm.msg = 'invalid code lengths set';
  16537. state.mode = BAD;
  16538. break;
  16539. }
  16540. //Tracev((stderr, "inflate: code lengths ok\n"));
  16541. state.have = 0;
  16542. state.mode = CODELENS;
  16543. /* falls through */
  16544. case CODELENS:
  16545. while (state.have < state.nlen + state.ndist) {
  16546. for (;;) {
  16547. here = state.lencode[hold & ((1 << state.lenbits) - 1)];/*BITS(state.lenbits)*/
  16548. here_bits = here >>> 24;
  16549. here_op = (here >>> 16) & 0xff;
  16550. here_val = here & 0xffff;
  16551. if ((here_bits) <= bits) { break; }
  16552. //--- PULLBYTE() ---//
  16553. if (have === 0) { break inf_leave; }
  16554. have--;
  16555. hold += input[next++] << bits;
  16556. bits += 8;
  16557. //---//
  16558. }
  16559. if (here_val < 16) {
  16560. //--- DROPBITS(here.bits) ---//
  16561. hold >>>= here_bits;
  16562. bits -= here_bits;
  16563. //---//
  16564. state.lens[state.have++] = here_val;
  16565. }
  16566. else {
  16567. if (here_val === 16) {
  16568. //=== NEEDBITS(here.bits + 2);
  16569. n = here_bits + 2;
  16570. while (bits < n) {
  16571. if (have === 0) { break inf_leave; }
  16572. have--;
  16573. hold += input[next++] << bits;
  16574. bits += 8;
  16575. }
  16576. //===//
  16577. //--- DROPBITS(here.bits) ---//
  16578. hold >>>= here_bits;
  16579. bits -= here_bits;
  16580. //---//
  16581. if (state.have === 0) {
  16582. strm.msg = 'invalid bit length repeat';
  16583. state.mode = BAD;
  16584. break;
  16585. }
  16586. len = state.lens[state.have - 1];
  16587. copy = 3 + (hold & 0x03);//BITS(2);
  16588. //--- DROPBITS(2) ---//
  16589. hold >>>= 2;
  16590. bits -= 2;
  16591. //---//
  16592. }
  16593. else if (here_val === 17) {
  16594. //=== NEEDBITS(here.bits + 3);
  16595. n = here_bits + 3;
  16596. while (bits < n) {
  16597. if (have === 0) { break inf_leave; }
  16598. have--;
  16599. hold += input[next++] << bits;
  16600. bits += 8;
  16601. }
  16602. //===//
  16603. //--- DROPBITS(here.bits) ---//
  16604. hold >>>= here_bits;
  16605. bits -= here_bits;
  16606. //---//
  16607. len = 0;
  16608. copy = 3 + (hold & 0x07);//BITS(3);
  16609. //--- DROPBITS(3) ---//
  16610. hold >>>= 3;
  16611. bits -= 3;
  16612. //---//
  16613. }
  16614. else {
  16615. //=== NEEDBITS(here.bits + 7);
  16616. n = here_bits + 7;
  16617. while (bits < n) {
  16618. if (have === 0) { break inf_leave; }
  16619. have--;
  16620. hold += input[next++] << bits;
  16621. bits += 8;
  16622. }
  16623. //===//
  16624. //--- DROPBITS(here.bits) ---//
  16625. hold >>>= here_bits;
  16626. bits -= here_bits;
  16627. //---//
  16628. len = 0;
  16629. copy = 11 + (hold & 0x7f);//BITS(7);
  16630. //--- DROPBITS(7) ---//
  16631. hold >>>= 7;
  16632. bits -= 7;
  16633. //---//
  16634. }
  16635. if (state.have + copy > state.nlen + state.ndist) {
  16636. strm.msg = 'invalid bit length repeat';
  16637. state.mode = BAD;
  16638. break;
  16639. }
  16640. while (copy--) {
  16641. state.lens[state.have++] = len;
  16642. }
  16643. }
  16644. }
  16645. /* handle error breaks in while */
  16646. if (state.mode === BAD) { break; }
  16647. /* check for end-of-block code (better have one) */
  16648. if (state.lens[256] === 0) {
  16649. strm.msg = 'invalid code -- missing end-of-block';
  16650. state.mode = BAD;
  16651. break;
  16652. }
  16653. /* build code tables -- note: do not change the lenbits or distbits
  16654. values here (9 and 6) without reading the comments in inftrees.h
  16655. concerning the ENOUGH constants, which depend on those values */
  16656. state.lenbits = 9;
  16657. opts = {bits: state.lenbits};
  16658. ret = inflate_table(LENS, state.lens, 0, state.nlen, state.lencode, 0, state.work, opts);
  16659. // We have separate tables & no pointers. 2 commented lines below not needed.
  16660. // state.next_index = opts.table_index;
  16661. state.lenbits = opts.bits;
  16662. // state.lencode = state.next;
  16663. if (ret) {
  16664. strm.msg = 'invalid literal/lengths set';
  16665. state.mode = BAD;
  16666. break;
  16667. }
  16668. state.distbits = 6;
  16669. //state.distcode.copy(state.codes);
  16670. // Switch to use dynamic table
  16671. state.distcode = state.distdyn;
  16672. opts = {bits: state.distbits};
  16673. ret = inflate_table(DISTS, state.lens, state.nlen, state.ndist, state.distcode, 0, state.work, opts);
  16674. // We have separate tables & no pointers. 2 commented lines below not needed.
  16675. // state.next_index = opts.table_index;
  16676. state.distbits = opts.bits;
  16677. // state.distcode = state.next;
  16678. if (ret) {
  16679. strm.msg = 'invalid distances set';
  16680. state.mode = BAD;
  16681. break;
  16682. }
  16683. //Tracev((stderr, 'inflate: codes ok\n'));
  16684. state.mode = LEN_;
  16685. if (flush === Z_TREES) { break inf_leave; }
  16686. /* falls through */
  16687. case LEN_:
  16688. state.mode = LEN;
  16689. /* falls through */
  16690. case LEN:
  16691. if (have >= 6 && left >= 258) {
  16692. //--- RESTORE() ---
  16693. strm.next_out = put;
  16694. strm.avail_out = left;
  16695. strm.next_in = next;
  16696. strm.avail_in = have;
  16697. state.hold = hold;
  16698. state.bits = bits;
  16699. //---
  16700. inflate_fast(strm, _out);
  16701. //--- LOAD() ---
  16702. put = strm.next_out;
  16703. output = strm.output;
  16704. left = strm.avail_out;
  16705. next = strm.next_in;
  16706. input = strm.input;
  16707. have = strm.avail_in;
  16708. hold = state.hold;
  16709. bits = state.bits;
  16710. //---
  16711. if (state.mode === TYPE) {
  16712. state.back = -1;
  16713. }
  16714. break;
  16715. }
  16716. state.back = 0;
  16717. for (;;) {
  16718. here = state.lencode[hold & ((1 << state.lenbits) -1)]; /*BITS(state.lenbits)*/
  16719. here_bits = here >>> 24;
  16720. here_op = (here >>> 16) & 0xff;
  16721. here_val = here & 0xffff;
  16722. if (here_bits <= bits) { break; }
  16723. //--- PULLBYTE() ---//
  16724. if (have === 0) { break inf_leave; }
  16725. have--;
  16726. hold += input[next++] << bits;
  16727. bits += 8;
  16728. //---//
  16729. }
  16730. if (here_op && (here_op & 0xf0) === 0) {
  16731. last_bits = here_bits;
  16732. last_op = here_op;
  16733. last_val = here_val;
  16734. for (;;) {
  16735. here = state.lencode[last_val +
  16736. ((hold & ((1 << (last_bits + last_op)) -1))/*BITS(last.bits + last.op)*/ >> last_bits)];
  16737. here_bits = here >>> 24;
  16738. here_op = (here >>> 16) & 0xff;
  16739. here_val = here & 0xffff;
  16740. if ((last_bits + here_bits) <= bits) { break; }
  16741. //--- PULLBYTE() ---//
  16742. if (have === 0) { break inf_leave; }
  16743. have--;
  16744. hold += input[next++] << bits;
  16745. bits += 8;
  16746. //---//
  16747. }
  16748. //--- DROPBITS(last.bits) ---//
  16749. hold >>>= last_bits;
  16750. bits -= last_bits;
  16751. //---//
  16752. state.back += last_bits;
  16753. }
  16754. //--- DROPBITS(here.bits) ---//
  16755. hold >>>= here_bits;
  16756. bits -= here_bits;
  16757. //---//
  16758. state.back += here_bits;
  16759. state.length = here_val;
  16760. if (here_op === 0) {
  16761. //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
  16762. // "inflate: literal '%c'\n" :
  16763. // "inflate: literal 0x%02x\n", here.val));
  16764. state.mode = LIT;
  16765. break;
  16766. }
  16767. if (here_op & 32) {
  16768. //Tracevv((stderr, "inflate: end of block\n"));
  16769. state.back = -1;
  16770. state.mode = TYPE;
  16771. break;
  16772. }
  16773. if (here_op & 64) {
  16774. strm.msg = 'invalid literal/length code';
  16775. state.mode = BAD;
  16776. break;
  16777. }
  16778. state.extra = here_op & 15;
  16779. state.mode = LENEXT;
  16780. /* falls through */
  16781. case LENEXT:
  16782. if (state.extra) {
  16783. //=== NEEDBITS(state.extra);
  16784. n = state.extra;
  16785. while (bits < n) {
  16786. if (have === 0) { break inf_leave; }
  16787. have--;
  16788. hold += input[next++] << bits;
  16789. bits += 8;
  16790. }
  16791. //===//
  16792. state.length += hold & ((1 << state.extra) -1)/*BITS(state.extra)*/;
  16793. //--- DROPBITS(state.extra) ---//
  16794. hold >>>= state.extra;
  16795. bits -= state.extra;
  16796. //---//
  16797. state.back += state.extra;
  16798. }
  16799. //Tracevv((stderr, "inflate: length %u\n", state.length));
  16800. state.was = state.length;
  16801. state.mode = DIST;
  16802. /* falls through */
  16803. case DIST:
  16804. for (;;) {
  16805. here = state.distcode[hold & ((1 << state.distbits) -1)];/*BITS(state.distbits)*/
  16806. here_bits = here >>> 24;
  16807. here_op = (here >>> 16) & 0xff;
  16808. here_val = here & 0xffff;
  16809. if ((here_bits) <= bits) { break; }
  16810. //--- PULLBYTE() ---//
  16811. if (have === 0) { break inf_leave; }
  16812. have--;
  16813. hold += input[next++] << bits;
  16814. bits += 8;
  16815. //---//
  16816. }
  16817. if ((here_op & 0xf0) === 0) {
  16818. last_bits = here_bits;
  16819. last_op = here_op;
  16820. last_val = here_val;
  16821. for (;;) {
  16822. here = state.distcode[last_val +
  16823. ((hold & ((1 << (last_bits + last_op)) -1))/*BITS(last.bits + last.op)*/ >> last_bits)];
  16824. here_bits = here >>> 24;
  16825. here_op = (here >>> 16) & 0xff;
  16826. here_val = here & 0xffff;
  16827. if ((last_bits + here_bits) <= bits) { break; }
  16828. //--- PULLBYTE() ---//
  16829. if (have === 0) { break inf_leave; }
  16830. have--;
  16831. hold += input[next++] << bits;
  16832. bits += 8;
  16833. //---//
  16834. }
  16835. //--- DROPBITS(last.bits) ---//
  16836. hold >>>= last_bits;
  16837. bits -= last_bits;
  16838. //---//
  16839. state.back += last_bits;
  16840. }
  16841. //--- DROPBITS(here.bits) ---//
  16842. hold >>>= here_bits;
  16843. bits -= here_bits;
  16844. //---//
  16845. state.back += here_bits;
  16846. if (here_op & 64) {
  16847. strm.msg = 'invalid distance code';
  16848. state.mode = BAD;
  16849. break;
  16850. }
  16851. state.offset = here_val;
  16852. state.extra = (here_op) & 15;
  16853. state.mode = DISTEXT;
  16854. /* falls through */
  16855. case DISTEXT:
  16856. if (state.extra) {
  16857. //=== NEEDBITS(state.extra);
  16858. n = state.extra;
  16859. while (bits < n) {
  16860. if (have === 0) { break inf_leave; }
  16861. have--;
  16862. hold += input[next++] << bits;
  16863. bits += 8;
  16864. }
  16865. //===//
  16866. state.offset += hold & ((1 << state.extra) -1)/*BITS(state.extra)*/;
  16867. //--- DROPBITS(state.extra) ---//
  16868. hold >>>= state.extra;
  16869. bits -= state.extra;
  16870. //---//
  16871. state.back += state.extra;
  16872. }
  16873. //#ifdef INFLATE_STRICT
  16874. if (state.offset > state.dmax) {
  16875. strm.msg = 'invalid distance too far back';
  16876. state.mode = BAD;
  16877. break;
  16878. }
  16879. //#endif
  16880. //Tracevv((stderr, "inflate: distance %u\n", state.offset));
  16881. state.mode = MATCH;
  16882. /* falls through */
  16883. case MATCH:
  16884. if (left === 0) { break inf_leave; }
  16885. copy = _out - left;
  16886. if (state.offset > copy) { /* copy from window */
  16887. copy = state.offset - copy;
  16888. if (copy > state.whave) {
  16889. if (state.sane) {
  16890. strm.msg = 'invalid distance too far back';
  16891. state.mode = BAD;
  16892. break;
  16893. }
  16894. // (!) This block is disabled in zlib defailts,
  16895. // don't enable it for binary compatibility
  16896. //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
  16897. // Trace((stderr, "inflate.c too far\n"));
  16898. // copy -= state.whave;
  16899. // if (copy > state.length) { copy = state.length; }
  16900. // if (copy > left) { copy = left; }
  16901. // left -= copy;
  16902. // state.length -= copy;
  16903. // do {
  16904. // output[put++] = 0;
  16905. // } while (--copy);
  16906. // if (state.length === 0) { state.mode = LEN; }
  16907. // break;
  16908. //#endif
  16909. }
  16910. if (copy > state.wnext) {
  16911. copy -= state.wnext;
  16912. from = state.wsize - copy;
  16913. }
  16914. else {
  16915. from = state.wnext - copy;
  16916. }
  16917. if (copy > state.length) { copy = state.length; }
  16918. from_source = state.window;
  16919. }
  16920. else { /* copy from output */
  16921. from_source = output;
  16922. from = put - state.offset;
  16923. copy = state.length;
  16924. }
  16925. if (copy > left) { copy = left; }
  16926. left -= copy;
  16927. state.length -= copy;
  16928. do {
  16929. output[put++] = from_source[from++];
  16930. } while (--copy);
  16931. if (state.length === 0) { state.mode = LEN; }
  16932. break;
  16933. case LIT:
  16934. if (left === 0) { break inf_leave; }
  16935. output[put++] = state.length;
  16936. left--;
  16937. state.mode = LEN;
  16938. break;
  16939. case CHECK:
  16940. if (state.wrap) {
  16941. //=== NEEDBITS(32);
  16942. while (bits < 32) {
  16943. if (have === 0) { break inf_leave; }
  16944. have--;
  16945. // Use '|' insdead of '+' to make sure that result is signed
  16946. hold |= input[next++] << bits;
  16947. bits += 8;
  16948. }
  16949. //===//
  16950. _out -= left;
  16951. strm.total_out += _out;
  16952. state.total += _out;
  16953. if (_out) {
  16954. strm.adler = state.check =
  16955. /*UPDATE(state.check, put - _out, _out);*/
  16956. (state.flags ? crc32(state.check, output, _out, put - _out) : adler32(state.check, output, _out, put - _out));
  16957. }
  16958. _out = left;
  16959. // NB: crc32 stored as signed 32-bit int, ZSWAP32 returns signed too
  16960. if ((state.flags ? hold : ZSWAP32(hold)) !== state.check) {
  16961. strm.msg = 'incorrect data check';
  16962. state.mode = BAD;
  16963. break;
  16964. }
  16965. //=== INITBITS();
  16966. hold = 0;
  16967. bits = 0;
  16968. //===//
  16969. //Tracev((stderr, "inflate: check matches trailer\n"));
  16970. }
  16971. state.mode = LENGTH;
  16972. /* falls through */
  16973. case LENGTH:
  16974. if (state.wrap && state.flags) {
  16975. //=== NEEDBITS(32);
  16976. while (bits < 32) {
  16977. if (have === 0) { break inf_leave; }
  16978. have--;
  16979. hold += input[next++] << bits;
  16980. bits += 8;
  16981. }
  16982. //===//
  16983. if (hold !== (state.total & 0xffffffff)) {
  16984. strm.msg = 'incorrect length check';
  16985. state.mode = BAD;
  16986. break;
  16987. }
  16988. //=== INITBITS();
  16989. hold = 0;
  16990. bits = 0;
  16991. //===//
  16992. //Tracev((stderr, "inflate: length matches trailer\n"));
  16993. }
  16994. state.mode = DONE;
  16995. /* falls through */
  16996. case DONE:
  16997. ret = Z_STREAM_END;
  16998. break inf_leave;
  16999. case BAD:
  17000. ret = Z_DATA_ERROR;
  17001. break inf_leave;
  17002. case MEM:
  17003. return Z_MEM_ERROR;
  17004. case SYNC:
  17005. /* falls through */
  17006. default:
  17007. return Z_STREAM_ERROR;
  17008. }
  17009. }
  17010. // inf_leave <- here is real place for "goto inf_leave", emulated via "break inf_leave"
  17011. /*
  17012. Return from inflate(), updating the total counts and the check value.
  17013. If there was no progress during the inflate() call, return a buffer
  17014. error. Call updatewindow() to create and/or update the window state.
  17015. Note: a memory error from inflate() is non-recoverable.
  17016. */
  17017. //--- RESTORE() ---
  17018. strm.next_out = put;
  17019. strm.avail_out = left;
  17020. strm.next_in = next;
  17021. strm.avail_in = have;
  17022. state.hold = hold;
  17023. state.bits = bits;
  17024. //---
  17025. if (state.wsize || (_out !== strm.avail_out && state.mode < BAD &&
  17026. (state.mode < CHECK || flush !== Z_FINISH))) {
  17027. if (updatewindow(strm, strm.output, strm.next_out, _out - strm.avail_out)) {
  17028. state.mode = MEM;
  17029. return Z_MEM_ERROR;
  17030. }
  17031. }
  17032. _in -= strm.avail_in;
  17033. _out -= strm.avail_out;
  17034. strm.total_in += _in;
  17035. strm.total_out += _out;
  17036. state.total += _out;
  17037. if (state.wrap && _out) {
  17038. strm.adler = state.check = /*UPDATE(state.check, strm.next_out - _out, _out);*/
  17039. (state.flags ? crc32(state.check, output, _out, strm.next_out - _out) : adler32(state.check, output, _out, strm.next_out - _out));
  17040. }
  17041. strm.data_type = state.bits + (state.last ? 64 : 0) +
  17042. (state.mode === TYPE ? 128 : 0) +
  17043. (state.mode === LEN_ || state.mode === COPY_ ? 256 : 0);
  17044. if (((_in === 0 && _out === 0) || flush === Z_FINISH) && ret === Z_OK) {
  17045. ret = Z_BUF_ERROR;
  17046. }
  17047. return ret;
  17048. }
  17049. function inflateEnd(strm) {
  17050. if (!strm || !strm.state /*|| strm->zfree == (free_func)0*/) {
  17051. return Z_STREAM_ERROR;
  17052. }
  17053. var state = strm.state;
  17054. if (state.window) {
  17055. state.window = null;
  17056. }
  17057. strm.state = null;
  17058. return Z_OK;
  17059. }
  17060. function inflateGetHeader(strm, head) {
  17061. var state;
  17062. /* check state */
  17063. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  17064. state = strm.state;
  17065. if ((state.wrap & 2) === 0) { return Z_STREAM_ERROR; }
  17066. /* save header structure */
  17067. state.head = head;
  17068. head.done = false;
  17069. return Z_OK;
  17070. }
  17071. exports.inflateReset = inflateReset;
  17072. exports.inflateReset2 = inflateReset2;
  17073. exports.inflateResetKeep = inflateResetKeep;
  17074. exports.inflateInit = inflateInit;
  17075. exports.inflateInit2 = inflateInit2;
  17076. exports.inflate = inflate;
  17077. exports.inflateEnd = inflateEnd;
  17078. exports.inflateGetHeader = inflateGetHeader;
  17079. exports.inflateInfo = 'pako inflate (from Nodeca project)';
  17080. /* Not implemented
  17081. exports.inflateCopy = inflateCopy;
  17082. exports.inflateGetDictionary = inflateGetDictionary;
  17083. exports.inflateMark = inflateMark;
  17084. exports.inflatePrime = inflatePrime;
  17085. exports.inflateSetDictionary = inflateSetDictionary;
  17086. exports.inflateSync = inflateSync;
  17087. exports.inflateSyncPoint = inflateSyncPoint;
  17088. exports.inflateUndermine = inflateUndermine;
  17089. */
  17090. },{"../utils/common":51,"./adler32":53,"./crc32":55,"./inffast":58,"./inftrees":60}],60:[function(require,module,exports){
  17091. 'use strict';
  17092. var utils = require('../utils/common');
  17093. var MAXBITS = 15;
  17094. var ENOUGH_LENS = 852;
  17095. var ENOUGH_DISTS = 592;
  17096. //var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
  17097. var CODES = 0;
  17098. var LENS = 1;
  17099. var DISTS = 2;
  17100. var lbase = [ /* Length codes 257..285 base */
  17101. 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
  17102. 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0
  17103. ];
  17104. var lext = [ /* Length codes 257..285 extra */
  17105. 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,
  17106. 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 72, 78
  17107. ];
  17108. var dbase = [ /* Distance codes 0..29 base */
  17109. 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
  17110. 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
  17111. 8193, 12289, 16385, 24577, 0, 0
  17112. ];
  17113. var dext = [ /* Distance codes 0..29 extra */
  17114. 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,
  17115. 23, 23, 24, 24, 25, 25, 26, 26, 27, 27,
  17116. 28, 28, 29, 29, 64, 64
  17117. ];
  17118. module.exports = function inflate_table(type, lens, lens_index, codes, table, table_index, work, opts)
  17119. {
  17120. var bits = opts.bits;
  17121. //here = opts.here; /* table entry for duplication */
  17122. var len = 0; /* a code's length in bits */
  17123. var sym = 0; /* index of code symbols */
  17124. var min = 0, max = 0; /* minimum and maximum code lengths */
  17125. var root = 0; /* number of index bits for root table */
  17126. var curr = 0; /* number of index bits for current table */
  17127. var drop = 0; /* code bits to drop for sub-table */
  17128. var left = 0; /* number of prefix codes available */
  17129. var used = 0; /* code entries in table used */
  17130. var huff = 0; /* Huffman code */
  17131. var incr; /* for incrementing code, index */
  17132. var fill; /* index for replicating entries */
  17133. var low; /* low bits for current root entry */
  17134. var mask; /* mask for low root bits */
  17135. var next; /* next available space in table */
  17136. var base = null; /* base value table to use */
  17137. var base_index = 0;
  17138. // var shoextra; /* extra bits table to use */
  17139. var end; /* use base and extra for symbol > end */
  17140. var count = new utils.Buf16(MAXBITS+1); //[MAXBITS+1]; /* number of codes of each length */
  17141. var offs = new utils.Buf16(MAXBITS+1); //[MAXBITS+1]; /* offsets in table for each length */
  17142. var extra = null;
  17143. var extra_index = 0;
  17144. var here_bits, here_op, here_val;
  17145. /*
  17146. Process a set of code lengths to create a canonical Huffman code. The
  17147. code lengths are lens[0..codes-1]. Each length corresponds to the
  17148. symbols 0..codes-1. The Huffman code is generated by first sorting the
  17149. symbols by length from short to long, and retaining the symbol order
  17150. for codes with equal lengths. Then the code starts with all zero bits
  17151. for the first code of the shortest length, and the codes are integer
  17152. increments for the same length, and zeros are appended as the length
  17153. increases. For the deflate format, these bits are stored backwards
  17154. from their more natural integer increment ordering, and so when the
  17155. decoding tables are built in the large loop below, the integer codes
  17156. are incremented backwards.
  17157. This routine assumes, but does not check, that all of the entries in
  17158. lens[] are in the range 0..MAXBITS. The caller must assure this.
  17159. 1..MAXBITS is interpreted as that code length. zero means that that
  17160. symbol does not occur in this code.
  17161. The codes are sorted by computing a count of codes for each length,
  17162. creating from that a table of starting indices for each length in the
  17163. sorted table, and then entering the symbols in order in the sorted
  17164. table. The sorted table is work[], with that space being provided by
  17165. the caller.
  17166. The length counts are used for other purposes as well, i.e. finding
  17167. the minimum and maximum length codes, determining if there are any
  17168. codes at all, checking for a valid set of lengths, and looking ahead
  17169. at length counts to determine sub-table sizes when building the
  17170. decoding tables.
  17171. */
  17172. /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */
  17173. for (len = 0; len <= MAXBITS; len++) {
  17174. count[len] = 0;
  17175. }
  17176. for (sym = 0; sym < codes; sym++) {
  17177. count[lens[lens_index + sym]]++;
  17178. }
  17179. /* bound code lengths, force root to be within code lengths */
  17180. root = bits;
  17181. for (max = MAXBITS; max >= 1; max--) {
  17182. if (count[max] !== 0) { break; }
  17183. }
  17184. if (root > max) {
  17185. root = max;
  17186. }
  17187. if (max === 0) { /* no symbols to code at all */
  17188. //table.op[opts.table_index] = 64; //here.op = (var char)64; /* invalid code marker */
  17189. //table.bits[opts.table_index] = 1; //here.bits = (var char)1;
  17190. //table.val[opts.table_index++] = 0; //here.val = (var short)0;
  17191. table[table_index++] = (1 << 24) | (64 << 16) | 0;
  17192. //table.op[opts.table_index] = 64;
  17193. //table.bits[opts.table_index] = 1;
  17194. //table.val[opts.table_index++] = 0;
  17195. table[table_index++] = (1 << 24) | (64 << 16) | 0;
  17196. opts.bits = 1;
  17197. return 0; /* no symbols, but wait for decoding to report error */
  17198. }
  17199. for (min = 1; min < max; min++) {
  17200. if (count[min] !== 0) { break; }
  17201. }
  17202. if (root < min) {
  17203. root = min;
  17204. }
  17205. /* check for an over-subscribed or incomplete set of lengths */
  17206. left = 1;
  17207. for (len = 1; len <= MAXBITS; len++) {
  17208. left <<= 1;
  17209. left -= count[len];
  17210. if (left < 0) {
  17211. return -1;
  17212. } /* over-subscribed */
  17213. }
  17214. if (left > 0 && (type === CODES || max !== 1)) {
  17215. return -1; /* incomplete set */
  17216. }
  17217. /* generate offsets into symbol table for each length for sorting */
  17218. offs[1] = 0;
  17219. for (len = 1; len < MAXBITS; len++) {
  17220. offs[len + 1] = offs[len] + count[len];
  17221. }
  17222. /* sort symbols by length, by symbol order within each length */
  17223. for (sym = 0; sym < codes; sym++) {
  17224. if (lens[lens_index + sym] !== 0) {
  17225. work[offs[lens[lens_index + sym]]++] = sym;
  17226. }
  17227. }
  17228. /*
  17229. Create and fill in decoding tables. In this loop, the table being
  17230. filled is at next and has curr index bits. The code being used is huff
  17231. with length len. That code is converted to an index by dropping drop
  17232. bits off of the bottom. For codes where len is less than drop + curr,
  17233. those top drop + curr - len bits are incremented through all values to
  17234. fill the table with replicated entries.
  17235. root is the number of index bits for the root table. When len exceeds
  17236. root, sub-tables are created pointed to by the root entry with an index
  17237. of the low root bits of huff. This is saved in low to check for when a
  17238. new sub-table should be started. drop is zero when the root table is
  17239. being filled, and drop is root when sub-tables are being filled.
  17240. When a new sub-table is needed, it is necessary to look ahead in the
  17241. code lengths to determine what size sub-table is needed. The length
  17242. counts are used for this, and so count[] is decremented as codes are
  17243. entered in the tables.
  17244. used keeps track of how many table entries have been allocated from the
  17245. provided *table space. It is checked for LENS and DIST tables against
  17246. the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in
  17247. the initial root table size constants. See the comments in inftrees.h
  17248. for more information.
  17249. sym increments through all symbols, and the loop terminates when
  17250. all codes of length max, i.e. all codes, have been processed. This
  17251. routine permits incomplete codes, so another loop after this one fills
  17252. in the rest of the decoding tables with invalid code markers.
  17253. */
  17254. /* set up for code type */
  17255. // poor man optimization - use if-else instead of switch,
  17256. // to avoid deopts in old v8
  17257. if (type === CODES) {
  17258. base = extra = work; /* dummy value--not used */
  17259. end = 19;
  17260. } else if (type === LENS) {
  17261. base = lbase;
  17262. base_index -= 257;
  17263. extra = lext;
  17264. extra_index -= 257;
  17265. end = 256;
  17266. } else { /* DISTS */
  17267. base = dbase;
  17268. extra = dext;
  17269. end = -1;
  17270. }
  17271. /* initialize opts for loop */
  17272. huff = 0; /* starting code */
  17273. sym = 0; /* starting code symbol */
  17274. len = min; /* starting code length */
  17275. next = table_index; /* current table to fill in */
  17276. curr = root; /* current table index bits */
  17277. drop = 0; /* current bits to drop from code for index */
  17278. low = -1; /* trigger new sub-table when len > root */
  17279. used = 1 << root; /* use root table entries */
  17280. mask = used - 1; /* mask for comparing low */
  17281. /* check available table space */
  17282. if ((type === LENS && used > ENOUGH_LENS) ||
  17283. (type === DISTS && used > ENOUGH_DISTS)) {
  17284. return 1;
  17285. }
  17286. var i=0;
  17287. /* process all codes and make table entries */
  17288. for (;;) {
  17289. i++;
  17290. /* create table entry */
  17291. here_bits = len - drop;
  17292. if (work[sym] < end) {
  17293. here_op = 0;
  17294. here_val = work[sym];
  17295. }
  17296. else if (work[sym] > end) {
  17297. here_op = extra[extra_index + work[sym]];
  17298. here_val = base[base_index + work[sym]];
  17299. }
  17300. else {
  17301. here_op = 32 + 64; /* end of block */
  17302. here_val = 0;
  17303. }
  17304. /* replicate for those indices with low len bits equal to huff */
  17305. incr = 1 << (len - drop);
  17306. fill = 1 << curr;
  17307. min = fill; /* save offset to next table */
  17308. do {
  17309. fill -= incr;
  17310. table[next + (huff >> drop) + fill] = (here_bits << 24) | (here_op << 16) | here_val |0;
  17311. } while (fill !== 0);
  17312. /* backwards increment the len-bit code huff */
  17313. incr = 1 << (len - 1);
  17314. while (huff & incr) {
  17315. incr >>= 1;
  17316. }
  17317. if (incr !== 0) {
  17318. huff &= incr - 1;
  17319. huff += incr;
  17320. } else {
  17321. huff = 0;
  17322. }
  17323. /* go to next symbol, update count, len */
  17324. sym++;
  17325. if (--count[len] === 0) {
  17326. if (len === max) { break; }
  17327. len = lens[lens_index + work[sym]];
  17328. }
  17329. /* create new sub-table if needed */
  17330. if (len > root && (huff & mask) !== low) {
  17331. /* if first time, transition to sub-tables */
  17332. if (drop === 0) {
  17333. drop = root;
  17334. }
  17335. /* increment past last table */
  17336. next += min; /* here min is 1 << curr */
  17337. /* determine length of next table */
  17338. curr = len - drop;
  17339. left = 1 << curr;
  17340. while (curr + drop < max) {
  17341. left -= count[curr + drop];
  17342. if (left <= 0) { break; }
  17343. curr++;
  17344. left <<= 1;
  17345. }
  17346. /* check for enough space */
  17347. used += 1 << curr;
  17348. if ((type === LENS && used > ENOUGH_LENS) ||
  17349. (type === DISTS && used > ENOUGH_DISTS)) {
  17350. return 1;
  17351. }
  17352. /* point entry in root table to sub-table */
  17353. low = huff & mask;
  17354. /*table.op[low] = curr;
  17355. table.bits[low] = root;
  17356. table.val[low] = next - opts.table_index;*/
  17357. table[low] = (root << 24) | (curr << 16) | (next - table_index) |0;
  17358. }
  17359. }
  17360. /* fill in remaining table entry if code is incomplete (guaranteed to have
  17361. at most one remaining entry, since if the code is incomplete, the
  17362. maximum code length that was allowed to get this far is one bit) */
  17363. if (huff !== 0) {
  17364. //table.op[next + huff] = 64; /* invalid code marker */
  17365. //table.bits[next + huff] = len - drop;
  17366. //table.val[next + huff] = 0;
  17367. table[next + huff] = ((len - drop) << 24) | (64 << 16) |0;
  17368. }
  17369. /* set return parameters */
  17370. //opts.table_index += used;
  17371. opts.bits = root;
  17372. return 0;
  17373. };
  17374. },{"../utils/common":51}],61:[function(require,module,exports){
  17375. 'use strict';
  17376. module.exports = {
  17377. '2': 'need dictionary', /* Z_NEED_DICT 2 */
  17378. '1': 'stream end', /* Z_STREAM_END 1 */
  17379. '0': '', /* Z_OK 0 */
  17380. '-1': 'file error', /* Z_ERRNO (-1) */
  17381. '-2': 'stream error', /* Z_STREAM_ERROR (-2) */
  17382. '-3': 'data error', /* Z_DATA_ERROR (-3) */
  17383. '-4': 'insufficient memory', /* Z_MEM_ERROR (-4) */
  17384. '-5': 'buffer error', /* Z_BUF_ERROR (-5) */
  17385. '-6': 'incompatible version' /* Z_VERSION_ERROR (-6) */
  17386. };
  17387. },{}],62:[function(require,module,exports){
  17388. 'use strict';
  17389. var utils = require('../utils/common');
  17390. /* Public constants ==========================================================*/
  17391. /* ===========================================================================*/
  17392. //var Z_FILTERED = 1;
  17393. //var Z_HUFFMAN_ONLY = 2;
  17394. //var Z_RLE = 3;
  17395. var Z_FIXED = 4;
  17396. //var Z_DEFAULT_STRATEGY = 0;
  17397. /* Possible values of the data_type field (though see inflate()) */
  17398. var Z_BINARY = 0;
  17399. var Z_TEXT = 1;
  17400. //var Z_ASCII = 1; // = Z_TEXT
  17401. var Z_UNKNOWN = 2;
  17402. /*============================================================================*/
  17403. function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
  17404. // From zutil.h
  17405. var STORED_BLOCK = 0;
  17406. var STATIC_TREES = 1;
  17407. var DYN_TREES = 2;
  17408. /* The three kinds of block type */
  17409. var MIN_MATCH = 3;
  17410. var MAX_MATCH = 258;
  17411. /* The minimum and maximum match lengths */
  17412. // From deflate.h
  17413. /* ===========================================================================
  17414. * Internal compression state.
  17415. */
  17416. var LENGTH_CODES = 29;
  17417. /* number of length codes, not counting the special END_BLOCK code */
  17418. var LITERALS = 256;
  17419. /* number of literal bytes 0..255 */
  17420. var L_CODES = LITERALS + 1 + LENGTH_CODES;
  17421. /* number of Literal or Length codes, including the END_BLOCK code */
  17422. var D_CODES = 30;
  17423. /* number of distance codes */
  17424. var BL_CODES = 19;
  17425. /* number of codes used to transfer the bit lengths */
  17426. var HEAP_SIZE = 2*L_CODES + 1;
  17427. /* maximum heap size */
  17428. var MAX_BITS = 15;
  17429. /* All codes must not exceed MAX_BITS bits */
  17430. var Buf_size = 16;
  17431. /* size of bit buffer in bi_buf */
  17432. /* ===========================================================================
  17433. * Constants
  17434. */
  17435. var MAX_BL_BITS = 7;
  17436. /* Bit length codes must not exceed MAX_BL_BITS bits */
  17437. var END_BLOCK = 256;
  17438. /* end of block literal code */
  17439. var REP_3_6 = 16;
  17440. /* repeat previous bit length 3-6 times (2 bits of repeat count) */
  17441. var REPZ_3_10 = 17;
  17442. /* repeat a zero length 3-10 times (3 bits of repeat count) */
  17443. var REPZ_11_138 = 18;
  17444. /* repeat a zero length 11-138 times (7 bits of repeat count) */
  17445. var extra_lbits = /* extra bits for each length code */
  17446. [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];
  17447. var extra_dbits = /* extra bits for each distance code */
  17448. [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];
  17449. var extra_blbits = /* extra bits for each bit length code */
  17450. [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7];
  17451. var bl_order =
  17452. [16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];
  17453. /* The lengths of the bit length codes are sent in order of decreasing
  17454. * probability, to avoid transmitting the lengths for unused bit length codes.
  17455. */
  17456. /* ===========================================================================
  17457. * Local data. These are initialized only once.
  17458. */
  17459. // We pre-fill arrays with 0 to avoid uninitialized gaps
  17460. var DIST_CODE_LEN = 512; /* see definition of array dist_code below */
  17461. // !!!! Use flat array insdead of structure, Freq = i*2, Len = i*2+1
  17462. var static_ltree = new Array((L_CODES+2) * 2);
  17463. zero(static_ltree);
  17464. /* The static literal tree. Since the bit lengths are imposed, there is no
  17465. * need for the L_CODES extra codes used during heap construction. However
  17466. * The codes 286 and 287 are needed to build a canonical tree (see _tr_init
  17467. * below).
  17468. */
  17469. var static_dtree = new Array(D_CODES * 2);
  17470. zero(static_dtree);
  17471. /* The static distance tree. (Actually a trivial tree since all codes use
  17472. * 5 bits.)
  17473. */
  17474. var _dist_code = new Array(DIST_CODE_LEN);
  17475. zero(_dist_code);
  17476. /* Distance codes. The first 256 values correspond to the distances
  17477. * 3 .. 258, the last 256 values correspond to the top 8 bits of
  17478. * the 15 bit distances.
  17479. */
  17480. var _length_code = new Array(MAX_MATCH-MIN_MATCH+1);
  17481. zero(_length_code);
  17482. /* length code for each normalized match length (0 == MIN_MATCH) */
  17483. var base_length = new Array(LENGTH_CODES);
  17484. zero(base_length);
  17485. /* First normalized length for each code (0 = MIN_MATCH) */
  17486. var base_dist = new Array(D_CODES);
  17487. zero(base_dist);
  17488. /* First normalized distance for each code (0 = distance of 1) */
  17489. var StaticTreeDesc = function (static_tree, extra_bits, extra_base, elems, max_length) {
  17490. this.static_tree = static_tree; /* static tree or NULL */
  17491. this.extra_bits = extra_bits; /* extra bits for each code or NULL */
  17492. this.extra_base = extra_base; /* base index for extra_bits */
  17493. this.elems = elems; /* max number of elements in the tree */
  17494. this.max_length = max_length; /* max bit length for the codes */
  17495. // show if `static_tree` has data or dummy - needed for monomorphic objects
  17496. this.has_stree = static_tree && static_tree.length;
  17497. };
  17498. var static_l_desc;
  17499. var static_d_desc;
  17500. var static_bl_desc;
  17501. var TreeDesc = function(dyn_tree, stat_desc) {
  17502. this.dyn_tree = dyn_tree; /* the dynamic tree */
  17503. this.max_code = 0; /* largest code with non zero frequency */
  17504. this.stat_desc = stat_desc; /* the corresponding static tree */
  17505. };
  17506. function d_code(dist) {
  17507. return dist < 256 ? _dist_code[dist] : _dist_code[256 + (dist >>> 7)];
  17508. }
  17509. /* ===========================================================================
  17510. * Output a short LSB first on the stream.
  17511. * IN assertion: there is enough room in pendingBuf.
  17512. */
  17513. function put_short (s, w) {
  17514. // put_byte(s, (uch)((w) & 0xff));
  17515. // put_byte(s, (uch)((ush)(w) >> 8));
  17516. s.pending_buf[s.pending++] = (w) & 0xff;
  17517. s.pending_buf[s.pending++] = (w >>> 8) & 0xff;
  17518. }
  17519. /* ===========================================================================
  17520. * Send a value on a given number of bits.
  17521. * IN assertion: length <= 16 and value fits in length bits.
  17522. */
  17523. function send_bits(s, value, length) {
  17524. if (s.bi_valid > (Buf_size - length)) {
  17525. s.bi_buf |= (value << s.bi_valid) & 0xffff;
  17526. put_short(s, s.bi_buf);
  17527. s.bi_buf = value >> (Buf_size - s.bi_valid);
  17528. s.bi_valid += length - Buf_size;
  17529. } else {
  17530. s.bi_buf |= (value << s.bi_valid) & 0xffff;
  17531. s.bi_valid += length;
  17532. }
  17533. }
  17534. function send_code(s, c, tree) {
  17535. send_bits(s, tree[c*2]/*.Code*/, tree[c*2 + 1]/*.Len*/);
  17536. }
  17537. /* ===========================================================================
  17538. * Reverse the first len bits of a code, using straightforward code (a faster
  17539. * method would use a table)
  17540. * IN assertion: 1 <= len <= 15
  17541. */
  17542. function bi_reverse(code, len) {
  17543. var res = 0;
  17544. do {
  17545. res |= code & 1;
  17546. code >>>= 1;
  17547. res <<= 1;
  17548. } while (--len > 0);
  17549. return res >>> 1;
  17550. }
  17551. /* ===========================================================================
  17552. * Flush the bit buffer, keeping at most 7 bits in it.
  17553. */
  17554. function bi_flush(s) {
  17555. if (s.bi_valid === 16) {
  17556. put_short(s, s.bi_buf);
  17557. s.bi_buf = 0;
  17558. s.bi_valid = 0;
  17559. } else if (s.bi_valid >= 8) {
  17560. s.pending_buf[s.pending++] = s.bi_buf & 0xff;
  17561. s.bi_buf >>= 8;
  17562. s.bi_valid -= 8;
  17563. }
  17564. }
  17565. /* ===========================================================================
  17566. * Compute the optimal bit lengths for a tree and update the total bit length
  17567. * for the current block.
  17568. * IN assertion: the fields freq and dad are set, heap[heap_max] and
  17569. * above are the tree nodes sorted by increasing frequency.
  17570. * OUT assertions: the field len is set to the optimal bit length, the
  17571. * array bl_count contains the frequencies for each bit length.
  17572. * The length opt_len is updated; static_len is also updated if stree is
  17573. * not null.
  17574. */
  17575. function gen_bitlen(s, desc)
  17576. // deflate_state *s;
  17577. // tree_desc *desc; /* the tree descriptor */
  17578. {
  17579. var tree = desc.dyn_tree;
  17580. var max_code = desc.max_code;
  17581. var stree = desc.stat_desc.static_tree;
  17582. var has_stree = desc.stat_desc.has_stree;
  17583. var extra = desc.stat_desc.extra_bits;
  17584. var base = desc.stat_desc.extra_base;
  17585. var max_length = desc.stat_desc.max_length;
  17586. var h; /* heap index */
  17587. var n, m; /* iterate over the tree elements */
  17588. var bits; /* bit length */
  17589. var xbits; /* extra bits */
  17590. var f; /* frequency */
  17591. var overflow = 0; /* number of elements with bit length too large */
  17592. for (bits = 0; bits <= MAX_BITS; bits++) {
  17593. s.bl_count[bits] = 0;
  17594. }
  17595. /* In a first pass, compute the optimal bit lengths (which may
  17596. * overflow in the case of the bit length tree).
  17597. */
  17598. tree[s.heap[s.heap_max]*2 + 1]/*.Len*/ = 0; /* root of the heap */
  17599. for (h = s.heap_max+1; h < HEAP_SIZE; h++) {
  17600. n = s.heap[h];
  17601. bits = tree[tree[n*2 +1]/*.Dad*/ * 2 + 1]/*.Len*/ + 1;
  17602. if (bits > max_length) {
  17603. bits = max_length;
  17604. overflow++;
  17605. }
  17606. tree[n*2 + 1]/*.Len*/ = bits;
  17607. /* We overwrite tree[n].Dad which is no longer needed */
  17608. if (n > max_code) { continue; } /* not a leaf node */
  17609. s.bl_count[bits]++;
  17610. xbits = 0;
  17611. if (n >= base) {
  17612. xbits = extra[n-base];
  17613. }
  17614. f = tree[n * 2]/*.Freq*/;
  17615. s.opt_len += f * (bits + xbits);
  17616. if (has_stree) {
  17617. s.static_len += f * (stree[n*2 + 1]/*.Len*/ + xbits);
  17618. }
  17619. }
  17620. if (overflow === 0) { return; }
  17621. // Trace((stderr,"\nbit length overflow\n"));
  17622. /* This happens for example on obj2 and pic of the Calgary corpus */
  17623. /* Find the first bit length which could increase: */
  17624. do {
  17625. bits = max_length-1;
  17626. while (s.bl_count[bits] === 0) { bits--; }
  17627. s.bl_count[bits]--; /* move one leaf down the tree */
  17628. s.bl_count[bits+1] += 2; /* move one overflow item as its brother */
  17629. s.bl_count[max_length]--;
  17630. /* The brother of the overflow item also moves one step up,
  17631. * but this does not affect bl_count[max_length]
  17632. */
  17633. overflow -= 2;
  17634. } while (overflow > 0);
  17635. /* Now recompute all bit lengths, scanning in increasing frequency.
  17636. * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all
  17637. * lengths instead of fixing only the wrong ones. This idea is taken
  17638. * from 'ar' written by Haruhiko Okumura.)
  17639. */
  17640. for (bits = max_length; bits !== 0; bits--) {
  17641. n = s.bl_count[bits];
  17642. while (n !== 0) {
  17643. m = s.heap[--h];
  17644. if (m > max_code) { continue; }
  17645. if (tree[m*2 + 1]/*.Len*/ !== bits) {
  17646. // Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits));
  17647. s.opt_len += (bits - tree[m*2 + 1]/*.Len*/)*tree[m*2]/*.Freq*/;
  17648. tree[m*2 + 1]/*.Len*/ = bits;
  17649. }
  17650. n--;
  17651. }
  17652. }
  17653. }
  17654. /* ===========================================================================
  17655. * Generate the codes for a given tree and bit counts (which need not be
  17656. * optimal).
  17657. * IN assertion: the array bl_count contains the bit length statistics for
  17658. * the given tree and the field len is set for all tree elements.
  17659. * OUT assertion: the field code is set for all tree elements of non
  17660. * zero code length.
  17661. */
  17662. function gen_codes(tree, max_code, bl_count)
  17663. // ct_data *tree; /* the tree to decorate */
  17664. // int max_code; /* largest code with non zero frequency */
  17665. // ushf *bl_count; /* number of codes at each bit length */
  17666. {
  17667. var next_code = new Array(MAX_BITS+1); /* next code value for each bit length */
  17668. var code = 0; /* running code value */
  17669. var bits; /* bit index */
  17670. var n; /* code index */
  17671. /* The distribution counts are first used to generate the code values
  17672. * without bit reversal.
  17673. */
  17674. for (bits = 1; bits <= MAX_BITS; bits++) {
  17675. next_code[bits] = code = (code + bl_count[bits-1]) << 1;
  17676. }
  17677. /* Check that the bit counts in bl_count are consistent. The last code
  17678. * must be all ones.
  17679. */
  17680. //Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,
  17681. // "inconsistent bit counts");
  17682. //Tracev((stderr,"\ngen_codes: max_code %d ", max_code));
  17683. for (n = 0; n <= max_code; n++) {
  17684. var len = tree[n*2 + 1]/*.Len*/;
  17685. if (len === 0) { continue; }
  17686. /* Now reverse the bits */
  17687. tree[n*2]/*.Code*/ = bi_reverse(next_code[len]++, len);
  17688. //Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ",
  17689. // n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1));
  17690. }
  17691. }
  17692. /* ===========================================================================
  17693. * Initialize the various 'constant' tables.
  17694. */
  17695. function tr_static_init() {
  17696. var n; /* iterates over tree elements */
  17697. var bits; /* bit counter */
  17698. var length; /* length value */
  17699. var code; /* code value */
  17700. var dist; /* distance index */
  17701. var bl_count = new Array(MAX_BITS+1);
  17702. /* number of codes at each bit length for an optimal tree */
  17703. // do check in _tr_init()
  17704. //if (static_init_done) return;
  17705. /* For some embedded targets, global variables are not initialized: */
  17706. /*#ifdef NO_INIT_GLOBAL_POINTERS
  17707. static_l_desc.static_tree = static_ltree;
  17708. static_l_desc.extra_bits = extra_lbits;
  17709. static_d_desc.static_tree = static_dtree;
  17710. static_d_desc.extra_bits = extra_dbits;
  17711. static_bl_desc.extra_bits = extra_blbits;
  17712. #endif*/
  17713. /* Initialize the mapping length (0..255) -> length code (0..28) */
  17714. length = 0;
  17715. for (code = 0; code < LENGTH_CODES-1; code++) {
  17716. base_length[code] = length;
  17717. for (n = 0; n < (1<<extra_lbits[code]); n++) {
  17718. _length_code[length++] = code;
  17719. }
  17720. }
  17721. //Assert (length == 256, "tr_static_init: length != 256");
  17722. /* Note that the length 255 (match length 258) can be represented
  17723. * in two different ways: code 284 + 5 bits or code 285, so we
  17724. * overwrite length_code[255] to use the best encoding:
  17725. */
  17726. _length_code[length-1] = code;
  17727. /* Initialize the mapping dist (0..32K) -> dist code (0..29) */
  17728. dist = 0;
  17729. for (code = 0 ; code < 16; code++) {
  17730. base_dist[code] = dist;
  17731. for (n = 0; n < (1<<extra_dbits[code]); n++) {
  17732. _dist_code[dist++] = code;
  17733. }
  17734. }
  17735. //Assert (dist == 256, "tr_static_init: dist != 256");
  17736. dist >>= 7; /* from now on, all distances are divided by 128 */
  17737. for (; code < D_CODES; code++) {
  17738. base_dist[code] = dist << 7;
  17739. for (n = 0; n < (1<<(extra_dbits[code]-7)); n++) {
  17740. _dist_code[256 + dist++] = code;
  17741. }
  17742. }
  17743. //Assert (dist == 256, "tr_static_init: 256+dist != 512");
  17744. /* Construct the codes of the static literal tree */
  17745. for (bits = 0; bits <= MAX_BITS; bits++) {
  17746. bl_count[bits] = 0;
  17747. }
  17748. n = 0;
  17749. while (n <= 143) {
  17750. static_ltree[n*2 + 1]/*.Len*/ = 8;
  17751. n++;
  17752. bl_count[8]++;
  17753. }
  17754. while (n <= 255) {
  17755. static_ltree[n*2 + 1]/*.Len*/ = 9;
  17756. n++;
  17757. bl_count[9]++;
  17758. }
  17759. while (n <= 279) {
  17760. static_ltree[n*2 + 1]/*.Len*/ = 7;
  17761. n++;
  17762. bl_count[7]++;
  17763. }
  17764. while (n <= 287) {
  17765. static_ltree[n*2 + 1]/*.Len*/ = 8;
  17766. n++;
  17767. bl_count[8]++;
  17768. }
  17769. /* Codes 286 and 287 do not exist, but we must include them in the
  17770. * tree construction to get a canonical Huffman tree (longest code
  17771. * all ones)
  17772. */
  17773. gen_codes(static_ltree, L_CODES+1, bl_count);
  17774. /* The static distance tree is trivial: */
  17775. for (n = 0; n < D_CODES; n++) {
  17776. static_dtree[n*2 + 1]/*.Len*/ = 5;
  17777. static_dtree[n*2]/*.Code*/ = bi_reverse(n, 5);
  17778. }
  17779. // Now data ready and we can init static trees
  17780. static_l_desc = new StaticTreeDesc(static_ltree, extra_lbits, LITERALS+1, L_CODES, MAX_BITS);
  17781. static_d_desc = new StaticTreeDesc(static_dtree, extra_dbits, 0, D_CODES, MAX_BITS);
  17782. static_bl_desc =new StaticTreeDesc(new Array(0), extra_blbits, 0, BL_CODES, MAX_BL_BITS);
  17783. //static_init_done = true;
  17784. }
  17785. /* ===========================================================================
  17786. * Initialize a new block.
  17787. */
  17788. function init_block(s) {
  17789. var n; /* iterates over tree elements */
  17790. /* Initialize the trees. */
  17791. for (n = 0; n < L_CODES; n++) { s.dyn_ltree[n*2]/*.Freq*/ = 0; }
  17792. for (n = 0; n < D_CODES; n++) { s.dyn_dtree[n*2]/*.Freq*/ = 0; }
  17793. for (n = 0; n < BL_CODES; n++) { s.bl_tree[n*2]/*.Freq*/ = 0; }
  17794. s.dyn_ltree[END_BLOCK*2]/*.Freq*/ = 1;
  17795. s.opt_len = s.static_len = 0;
  17796. s.last_lit = s.matches = 0;
  17797. }
  17798. /* ===========================================================================
  17799. * Flush the bit buffer and align the output on a byte boundary
  17800. */
  17801. function bi_windup(s)
  17802. {
  17803. if (s.bi_valid > 8) {
  17804. put_short(s, s.bi_buf);
  17805. } else if (s.bi_valid > 0) {
  17806. //put_byte(s, (Byte)s->bi_buf);
  17807. s.pending_buf[s.pending++] = s.bi_buf;
  17808. }
  17809. s.bi_buf = 0;
  17810. s.bi_valid = 0;
  17811. }
  17812. /* ===========================================================================
  17813. * Copy a stored block, storing first the length and its
  17814. * one's complement if requested.
  17815. */
  17816. function copy_block(s, buf, len, header)
  17817. //DeflateState *s;
  17818. //charf *buf; /* the input data */
  17819. //unsigned len; /* its length */
  17820. //int header; /* true if block header must be written */
  17821. {
  17822. bi_windup(s); /* align on byte boundary */
  17823. if (header) {
  17824. put_short(s, len);
  17825. put_short(s, ~len);
  17826. }
  17827. // while (len--) {
  17828. // put_byte(s, *buf++);
  17829. // }
  17830. utils.arraySet(s.pending_buf, s.window, buf, len, s.pending);
  17831. s.pending += len;
  17832. }
  17833. /* ===========================================================================
  17834. * Compares to subtrees, using the tree depth as tie breaker when
  17835. * the subtrees have equal frequency. This minimizes the worst case length.
  17836. */
  17837. function smaller(tree, n, m, depth) {
  17838. var _n2 = n*2;
  17839. var _m2 = m*2;
  17840. return (tree[_n2]/*.Freq*/ < tree[_m2]/*.Freq*/ ||
  17841. (tree[_n2]/*.Freq*/ === tree[_m2]/*.Freq*/ && depth[n] <= depth[m]));
  17842. }
  17843. /* ===========================================================================
  17844. * Restore the heap property by moving down the tree starting at node k,
  17845. * exchanging a node with the smallest of its two sons if necessary, stopping
  17846. * when the heap property is re-established (each father smaller than its
  17847. * two sons).
  17848. */
  17849. function pqdownheap(s, tree, k)
  17850. // deflate_state *s;
  17851. // ct_data *tree; /* the tree to restore */
  17852. // int k; /* node to move down */
  17853. {
  17854. var v = s.heap[k];
  17855. var j = k << 1; /* left son of k */
  17856. while (j <= s.heap_len) {
  17857. /* Set j to the smallest of the two sons: */
  17858. if (j < s.heap_len &&
  17859. smaller(tree, s.heap[j+1], s.heap[j], s.depth)) {
  17860. j++;
  17861. }
  17862. /* Exit if v is smaller than both sons */
  17863. if (smaller(tree, v, s.heap[j], s.depth)) { break; }
  17864. /* Exchange v with the smallest son */
  17865. s.heap[k] = s.heap[j];
  17866. k = j;
  17867. /* And continue down the tree, setting j to the left son of k */
  17868. j <<= 1;
  17869. }
  17870. s.heap[k] = v;
  17871. }
  17872. // inlined manually
  17873. // var SMALLEST = 1;
  17874. /* ===========================================================================
  17875. * Send the block data compressed using the given Huffman trees
  17876. */
  17877. function compress_block(s, ltree, dtree)
  17878. // deflate_state *s;
  17879. // const ct_data *ltree; /* literal tree */
  17880. // const ct_data *dtree; /* distance tree */
  17881. {
  17882. var dist; /* distance of matched string */
  17883. var lc; /* match length or unmatched char (if dist == 0) */
  17884. var lx = 0; /* running index in l_buf */
  17885. var code; /* the code to send */
  17886. var extra; /* number of extra bits to send */
  17887. if (s.last_lit !== 0) {
  17888. do {
  17889. dist = (s.pending_buf[s.d_buf + lx*2] << 8) | (s.pending_buf[s.d_buf + lx*2 + 1]);
  17890. lc = s.pending_buf[s.l_buf + lx];
  17891. lx++;
  17892. if (dist === 0) {
  17893. send_code(s, lc, ltree); /* send a literal byte */
  17894. //Tracecv(isgraph(lc), (stderr," '%c' ", lc));
  17895. } else {
  17896. /* Here, lc is the match length - MIN_MATCH */
  17897. code = _length_code[lc];
  17898. send_code(s, code+LITERALS+1, ltree); /* send the length code */
  17899. extra = extra_lbits[code];
  17900. if (extra !== 0) {
  17901. lc -= base_length[code];
  17902. send_bits(s, lc, extra); /* send the extra length bits */
  17903. }
  17904. dist--; /* dist is now the match distance - 1 */
  17905. code = d_code(dist);
  17906. //Assert (code < D_CODES, "bad d_code");
  17907. send_code(s, code, dtree); /* send the distance code */
  17908. extra = extra_dbits[code];
  17909. if (extra !== 0) {
  17910. dist -= base_dist[code];
  17911. send_bits(s, dist, extra); /* send the extra distance bits */
  17912. }
  17913. } /* literal or match pair ? */
  17914. /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */
  17915. //Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx,
  17916. // "pendingBuf overflow");
  17917. } while (lx < s.last_lit);
  17918. }
  17919. send_code(s, END_BLOCK, ltree);
  17920. }
  17921. /* ===========================================================================
  17922. * Construct one Huffman tree and assigns the code bit strings and lengths.
  17923. * Update the total bit length for the current block.
  17924. * IN assertion: the field freq is set for all tree elements.
  17925. * OUT assertions: the fields len and code are set to the optimal bit length
  17926. * and corresponding code. The length opt_len is updated; static_len is
  17927. * also updated if stree is not null. The field max_code is set.
  17928. */
  17929. function build_tree(s, desc)
  17930. // deflate_state *s;
  17931. // tree_desc *desc; /* the tree descriptor */
  17932. {
  17933. var tree = desc.dyn_tree;
  17934. var stree = desc.stat_desc.static_tree;
  17935. var has_stree = desc.stat_desc.has_stree;
  17936. var elems = desc.stat_desc.elems;
  17937. var n, m; /* iterate over heap elements */
  17938. var max_code = -1; /* largest code with non zero frequency */
  17939. var node; /* new node being created */
  17940. /* Construct the initial heap, with least frequent element in
  17941. * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
  17942. * heap[0] is not used.
  17943. */
  17944. s.heap_len = 0;
  17945. s.heap_max = HEAP_SIZE;
  17946. for (n = 0; n < elems; n++) {
  17947. if (tree[n * 2]/*.Freq*/ !== 0) {
  17948. s.heap[++s.heap_len] = max_code = n;
  17949. s.depth[n] = 0;
  17950. } else {
  17951. tree[n*2 + 1]/*.Len*/ = 0;
  17952. }
  17953. }
  17954. /* The pkzip format requires that at least one distance code exists,
  17955. * and that at least one bit should be sent even if there is only one
  17956. * possible code. So to avoid special checks later on we force at least
  17957. * two codes of non zero frequency.
  17958. */
  17959. while (s.heap_len < 2) {
  17960. node = s.heap[++s.heap_len] = (max_code < 2 ? ++max_code : 0);
  17961. tree[node * 2]/*.Freq*/ = 1;
  17962. s.depth[node] = 0;
  17963. s.opt_len--;
  17964. if (has_stree) {
  17965. s.static_len -= stree[node*2 + 1]/*.Len*/;
  17966. }
  17967. /* node is 0 or 1 so it does not have extra bits */
  17968. }
  17969. desc.max_code = max_code;
  17970. /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
  17971. * establish sub-heaps of increasing lengths:
  17972. */
  17973. for (n = (s.heap_len >> 1/*int /2*/); n >= 1; n--) { pqdownheap(s, tree, n); }
  17974. /* Construct the Huffman tree by repeatedly combining the least two
  17975. * frequent nodes.
  17976. */
  17977. node = elems; /* next internal node of the tree */
  17978. do {
  17979. //pqremove(s, tree, n); /* n = node of least frequency */
  17980. /*** pqremove ***/
  17981. n = s.heap[1/*SMALLEST*/];
  17982. s.heap[1/*SMALLEST*/] = s.heap[s.heap_len--];
  17983. pqdownheap(s, tree, 1/*SMALLEST*/);
  17984. /***/
  17985. m = s.heap[1/*SMALLEST*/]; /* m = node of next least frequency */
  17986. s.heap[--s.heap_max] = n; /* keep the nodes sorted by frequency */
  17987. s.heap[--s.heap_max] = m;
  17988. /* Create a new node father of n and m */
  17989. tree[node * 2]/*.Freq*/ = tree[n * 2]/*.Freq*/ + tree[m * 2]/*.Freq*/;
  17990. s.depth[node] = (s.depth[n] >= s.depth[m] ? s.depth[n] : s.depth[m]) + 1;
  17991. tree[n*2 + 1]/*.Dad*/ = tree[m*2 + 1]/*.Dad*/ = node;
  17992. /* and insert the new node in the heap */
  17993. s.heap[1/*SMALLEST*/] = node++;
  17994. pqdownheap(s, tree, 1/*SMALLEST*/);
  17995. } while (s.heap_len >= 2);
  17996. s.heap[--s.heap_max] = s.heap[1/*SMALLEST*/];
  17997. /* At this point, the fields freq and dad are set. We can now
  17998. * generate the bit lengths.
  17999. */
  18000. gen_bitlen(s, desc);
  18001. /* The field len is now set, we can generate the bit codes */
  18002. gen_codes(tree, max_code, s.bl_count);
  18003. }
  18004. /* ===========================================================================
  18005. * Scan a literal or distance tree to determine the frequencies of the codes
  18006. * in the bit length tree.
  18007. */
  18008. function scan_tree(s, tree, max_code)
  18009. // deflate_state *s;
  18010. // ct_data *tree; /* the tree to be scanned */
  18011. // int max_code; /* and its largest code of non zero frequency */
  18012. {
  18013. var n; /* iterates over all tree elements */
  18014. var prevlen = -1; /* last emitted length */
  18015. var curlen; /* length of current code */
  18016. var nextlen = tree[0*2 + 1]/*.Len*/; /* length of next code */
  18017. var count = 0; /* repeat count of the current code */
  18018. var max_count = 7; /* max repeat count */
  18019. var min_count = 4; /* min repeat count */
  18020. if (nextlen === 0) {
  18021. max_count = 138;
  18022. min_count = 3;
  18023. }
  18024. tree[(max_code+1)*2 + 1]/*.Len*/ = 0xffff; /* guard */
  18025. for (n = 0; n <= max_code; n++) {
  18026. curlen = nextlen;
  18027. nextlen = tree[(n+1)*2 + 1]/*.Len*/;
  18028. if (++count < max_count && curlen === nextlen) {
  18029. continue;
  18030. } else if (count < min_count) {
  18031. s.bl_tree[curlen * 2]/*.Freq*/ += count;
  18032. } else if (curlen !== 0) {
  18033. if (curlen !== prevlen) { s.bl_tree[curlen * 2]/*.Freq*/++; }
  18034. s.bl_tree[REP_3_6*2]/*.Freq*/++;
  18035. } else if (count <= 10) {
  18036. s.bl_tree[REPZ_3_10*2]/*.Freq*/++;
  18037. } else {
  18038. s.bl_tree[REPZ_11_138*2]/*.Freq*/++;
  18039. }
  18040. count = 0;
  18041. prevlen = curlen;
  18042. if (nextlen === 0) {
  18043. max_count = 138;
  18044. min_count = 3;
  18045. } else if (curlen === nextlen) {
  18046. max_count = 6;
  18047. min_count = 3;
  18048. } else {
  18049. max_count = 7;
  18050. min_count = 4;
  18051. }
  18052. }
  18053. }
  18054. /* ===========================================================================
  18055. * Send a literal or distance tree in compressed form, using the codes in
  18056. * bl_tree.
  18057. */
  18058. function send_tree(s, tree, max_code)
  18059. // deflate_state *s;
  18060. // ct_data *tree; /* the tree to be scanned */
  18061. // int max_code; /* and its largest code of non zero frequency */
  18062. {
  18063. var n; /* iterates over all tree elements */
  18064. var prevlen = -1; /* last emitted length */
  18065. var curlen; /* length of current code */
  18066. var nextlen = tree[0*2 + 1]/*.Len*/; /* length of next code */
  18067. var count = 0; /* repeat count of the current code */
  18068. var max_count = 7; /* max repeat count */
  18069. var min_count = 4; /* min repeat count */
  18070. /* tree[max_code+1].Len = -1; */ /* guard already set */
  18071. if (nextlen === 0) {
  18072. max_count = 138;
  18073. min_count = 3;
  18074. }
  18075. for (n = 0; n <= max_code; n++) {
  18076. curlen = nextlen;
  18077. nextlen = tree[(n+1)*2 + 1]/*.Len*/;
  18078. if (++count < max_count && curlen === nextlen) {
  18079. continue;
  18080. } else if (count < min_count) {
  18081. do { send_code(s, curlen, s.bl_tree); } while (--count !== 0);
  18082. } else if (curlen !== 0) {
  18083. if (curlen !== prevlen) {
  18084. send_code(s, curlen, s.bl_tree);
  18085. count--;
  18086. }
  18087. //Assert(count >= 3 && count <= 6, " 3_6?");
  18088. send_code(s, REP_3_6, s.bl_tree);
  18089. send_bits(s, count-3, 2);
  18090. } else if (count <= 10) {
  18091. send_code(s, REPZ_3_10, s.bl_tree);
  18092. send_bits(s, count-3, 3);
  18093. } else {
  18094. send_code(s, REPZ_11_138, s.bl_tree);
  18095. send_bits(s, count-11, 7);
  18096. }
  18097. count = 0;
  18098. prevlen = curlen;
  18099. if (nextlen === 0) {
  18100. max_count = 138;
  18101. min_count = 3;
  18102. } else if (curlen === nextlen) {
  18103. max_count = 6;
  18104. min_count = 3;
  18105. } else {
  18106. max_count = 7;
  18107. min_count = 4;
  18108. }
  18109. }
  18110. }
  18111. /* ===========================================================================
  18112. * Construct the Huffman tree for the bit lengths and return the index in
  18113. * bl_order of the last bit length code to send.
  18114. */
  18115. function build_bl_tree(s) {
  18116. var max_blindex; /* index of last bit length code of non zero freq */
  18117. /* Determine the bit length frequencies for literal and distance trees */
  18118. scan_tree(s, s.dyn_ltree, s.l_desc.max_code);
  18119. scan_tree(s, s.dyn_dtree, s.d_desc.max_code);
  18120. /* Build the bit length tree: */
  18121. build_tree(s, s.bl_desc);
  18122. /* opt_len now includes the length of the tree representations, except
  18123. * the lengths of the bit lengths codes and the 5+5+4 bits for the counts.
  18124. */
  18125. /* Determine the number of bit length codes to send. The pkzip format
  18126. * requires that at least 4 bit length codes be sent. (appnote.txt says
  18127. * 3 but the actual value used is 4.)
  18128. */
  18129. for (max_blindex = BL_CODES-1; max_blindex >= 3; max_blindex--) {
  18130. if (s.bl_tree[bl_order[max_blindex]*2 + 1]/*.Len*/ !== 0) {
  18131. break;
  18132. }
  18133. }
  18134. /* Update opt_len to include the bit length tree and counts */
  18135. s.opt_len += 3*(max_blindex+1) + 5+5+4;
  18136. //Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld",
  18137. // s->opt_len, s->static_len));
  18138. return max_blindex;
  18139. }
  18140. /* ===========================================================================
  18141. * Send the header for a block using dynamic Huffman trees: the counts, the
  18142. * lengths of the bit length codes, the literal tree and the distance tree.
  18143. * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
  18144. */
  18145. function send_all_trees(s, lcodes, dcodes, blcodes)
  18146. // deflate_state *s;
  18147. // int lcodes, dcodes, blcodes; /* number of codes for each tree */
  18148. {
  18149. var rank; /* index in bl_order */
  18150. //Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes");
  18151. //Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,
  18152. // "too many codes");
  18153. //Tracev((stderr, "\nbl counts: "));
  18154. send_bits(s, lcodes-257, 5); /* not +255 as stated in appnote.txt */
  18155. send_bits(s, dcodes-1, 5);
  18156. send_bits(s, blcodes-4, 4); /* not -3 as stated in appnote.txt */
  18157. for (rank = 0; rank < blcodes; rank++) {
  18158. //Tracev((stderr, "\nbl code %2d ", bl_order[rank]));
  18159. send_bits(s, s.bl_tree[bl_order[rank]*2 + 1]/*.Len*/, 3);
  18160. }
  18161. //Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent));
  18162. send_tree(s, s.dyn_ltree, lcodes-1); /* literal tree */
  18163. //Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent));
  18164. send_tree(s, s.dyn_dtree, dcodes-1); /* distance tree */
  18165. //Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent));
  18166. }
  18167. /* ===========================================================================
  18168. * Check if the data type is TEXT or BINARY, using the following algorithm:
  18169. * - TEXT if the two conditions below are satisfied:
  18170. * a) There are no non-portable control characters belonging to the
  18171. * "black list" (0..6, 14..25, 28..31).
  18172. * b) There is at least one printable character belonging to the
  18173. * "white list" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255).
  18174. * - BINARY otherwise.
  18175. * - The following partially-portable control characters form a
  18176. * "gray list" that is ignored in this detection algorithm:
  18177. * (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}).
  18178. * IN assertion: the fields Freq of dyn_ltree are set.
  18179. */
  18180. function detect_data_type(s) {
  18181. /* black_mask is the bit mask of black-listed bytes
  18182. * set bits 0..6, 14..25, and 28..31
  18183. * 0xf3ffc07f = binary 11110011111111111100000001111111
  18184. */
  18185. var black_mask = 0xf3ffc07f;
  18186. var n;
  18187. /* Check for non-textual ("black-listed") bytes. */
  18188. for (n = 0; n <= 31; n++, black_mask >>>= 1) {
  18189. if ((black_mask & 1) && (s.dyn_ltree[n*2]/*.Freq*/ !== 0)) {
  18190. return Z_BINARY;
  18191. }
  18192. }
  18193. /* Check for textual ("white-listed") bytes. */
  18194. if (s.dyn_ltree[9 * 2]/*.Freq*/ !== 0 || s.dyn_ltree[10 * 2]/*.Freq*/ !== 0 ||
  18195. s.dyn_ltree[13 * 2]/*.Freq*/ !== 0) {
  18196. return Z_TEXT;
  18197. }
  18198. for (n = 32; n < LITERALS; n++) {
  18199. if (s.dyn_ltree[n * 2]/*.Freq*/ !== 0) {
  18200. return Z_TEXT;
  18201. }
  18202. }
  18203. /* There are no "black-listed" or "white-listed" bytes:
  18204. * this stream either is empty or has tolerated ("gray-listed") bytes only.
  18205. */
  18206. return Z_BINARY;
  18207. }
  18208. var static_init_done = false;
  18209. /* ===========================================================================
  18210. * Initialize the tree data structures for a new zlib stream.
  18211. */
  18212. function _tr_init(s)
  18213. {
  18214. if (!static_init_done) {
  18215. tr_static_init();
  18216. static_init_done = true;
  18217. }
  18218. s.l_desc = new TreeDesc(s.dyn_ltree, static_l_desc);
  18219. s.d_desc = new TreeDesc(s.dyn_dtree, static_d_desc);
  18220. s.bl_desc = new TreeDesc(s.bl_tree, static_bl_desc);
  18221. s.bi_buf = 0;
  18222. s.bi_valid = 0;
  18223. /* Initialize the first block of the first file: */
  18224. init_block(s);
  18225. }
  18226. /* ===========================================================================
  18227. * Send a stored block
  18228. */
  18229. function _tr_stored_block(s, buf, stored_len, last)
  18230. //DeflateState *s;
  18231. //charf *buf; /* input block */
  18232. //ulg stored_len; /* length of input block */
  18233. //int last; /* one if this is the last block for a file */
  18234. {
  18235. send_bits(s, (STORED_BLOCK<<1)+(last ? 1 : 0), 3); /* send block type */
  18236. copy_block(s, buf, stored_len, true); /* with header */
  18237. }
  18238. /* ===========================================================================
  18239. * Send one empty static block to give enough lookahead for inflate.
  18240. * This takes 10 bits, of which 7 may remain in the bit buffer.
  18241. */
  18242. function _tr_align(s) {
  18243. send_bits(s, STATIC_TREES<<1, 3);
  18244. send_code(s, END_BLOCK, static_ltree);
  18245. bi_flush(s);
  18246. }
  18247. /* ===========================================================================
  18248. * Determine the best encoding for the current block: dynamic trees, static
  18249. * trees or store, and output the encoded block to the zip file.
  18250. */
  18251. function _tr_flush_block(s, buf, stored_len, last)
  18252. //DeflateState *s;
  18253. //charf *buf; /* input block, or NULL if too old */
  18254. //ulg stored_len; /* length of input block */
  18255. //int last; /* one if this is the last block for a file */
  18256. {
  18257. var opt_lenb, static_lenb; /* opt_len and static_len in bytes */
  18258. var max_blindex = 0; /* index of last bit length code of non zero freq */
  18259. /* Build the Huffman trees unless a stored block is forced */
  18260. if (s.level > 0) {
  18261. /* Check if the file is binary or text */
  18262. if (s.strm.data_type === Z_UNKNOWN) {
  18263. s.strm.data_type = detect_data_type(s);
  18264. }
  18265. /* Construct the literal and distance trees */
  18266. build_tree(s, s.l_desc);
  18267. // Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len,
  18268. // s->static_len));
  18269. build_tree(s, s.d_desc);
  18270. // Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len,
  18271. // s->static_len));
  18272. /* At this point, opt_len and static_len are the total bit lengths of
  18273. * the compressed block data, excluding the tree representations.
  18274. */
  18275. /* Build the bit length tree for the above two trees, and get the index
  18276. * in bl_order of the last bit length code to send.
  18277. */
  18278. max_blindex = build_bl_tree(s);
  18279. /* Determine the best encoding. Compute the block lengths in bytes. */
  18280. opt_lenb = (s.opt_len+3+7) >>> 3;
  18281. static_lenb = (s.static_len+3+7) >>> 3;
  18282. // Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ",
  18283. // opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,
  18284. // s->last_lit));
  18285. if (static_lenb <= opt_lenb) { opt_lenb = static_lenb; }
  18286. } else {
  18287. // Assert(buf != (char*)0, "lost buf");
  18288. opt_lenb = static_lenb = stored_len + 5; /* force a stored block */
  18289. }
  18290. if ((stored_len+4 <= opt_lenb) && (buf !== -1)) {
  18291. /* 4: two words for the lengths */
  18292. /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
  18293. * Otherwise we can't have processed more than WSIZE input bytes since
  18294. * the last block flush, because compression would have been
  18295. * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
  18296. * transform a block into a stored block.
  18297. */
  18298. _tr_stored_block(s, buf, stored_len, last);
  18299. } else if (s.strategy === Z_FIXED || static_lenb === opt_lenb) {
  18300. send_bits(s, (STATIC_TREES<<1) + (last ? 1 : 0), 3);
  18301. compress_block(s, static_ltree, static_dtree);
  18302. } else {
  18303. send_bits(s, (DYN_TREES<<1) + (last ? 1 : 0), 3);
  18304. send_all_trees(s, s.l_desc.max_code+1, s.d_desc.max_code+1, max_blindex+1);
  18305. compress_block(s, s.dyn_ltree, s.dyn_dtree);
  18306. }
  18307. // Assert (s->compressed_len == s->bits_sent, "bad compressed size");
  18308. /* The above check is made mod 2^32, for files larger than 512 MB
  18309. * and uLong implemented on 32 bits.
  18310. */
  18311. init_block(s);
  18312. if (last) {
  18313. bi_windup(s);
  18314. }
  18315. // Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3,
  18316. // s->compressed_len-7*last));
  18317. }
  18318. /* ===========================================================================
  18319. * Save the match info and tally the frequency counts. Return true if
  18320. * the current block must be flushed.
  18321. */
  18322. function _tr_tally(s, dist, lc)
  18323. // deflate_state *s;
  18324. // unsigned dist; /* distance of matched string */
  18325. // unsigned lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */
  18326. {
  18327. //var out_length, in_length, dcode;
  18328. s.pending_buf[s.d_buf + s.last_lit * 2] = (dist >>> 8) & 0xff;
  18329. s.pending_buf[s.d_buf + s.last_lit * 2 + 1] = dist & 0xff;
  18330. s.pending_buf[s.l_buf + s.last_lit] = lc & 0xff;
  18331. s.last_lit++;
  18332. if (dist === 0) {
  18333. /* lc is the unmatched char */
  18334. s.dyn_ltree[lc*2]/*.Freq*/++;
  18335. } else {
  18336. s.matches++;
  18337. /* Here, lc is the match length - MIN_MATCH */
  18338. dist--; /* dist = match distance - 1 */
  18339. //Assert((ush)dist < (ush)MAX_DIST(s) &&
  18340. // (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&
  18341. // (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match");
  18342. s.dyn_ltree[(_length_code[lc]+LITERALS+1) * 2]/*.Freq*/++;
  18343. s.dyn_dtree[d_code(dist) * 2]/*.Freq*/++;
  18344. }
  18345. // (!) This block is disabled in zlib defailts,
  18346. // don't enable it for binary compatibility
  18347. //#ifdef TRUNCATE_BLOCK
  18348. // /* Try to guess if it is profitable to stop the current block here */
  18349. // if ((s.last_lit & 0x1fff) === 0 && s.level > 2) {
  18350. // /* Compute an upper bound for the compressed length */
  18351. // out_length = s.last_lit*8;
  18352. // in_length = s.strstart - s.block_start;
  18353. //
  18354. // for (dcode = 0; dcode < D_CODES; dcode++) {
  18355. // out_length += s.dyn_dtree[dcode*2]/*.Freq*/ * (5 + extra_dbits[dcode]);
  18356. // }
  18357. // out_length >>>= 3;
  18358. // //Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ",
  18359. // // s->last_lit, in_length, out_length,
  18360. // // 100L - out_length*100L/in_length));
  18361. // if (s.matches < (s.last_lit>>1)/*int /2*/ && out_length < (in_length>>1)/*int /2*/) {
  18362. // return true;
  18363. // }
  18364. // }
  18365. //#endif
  18366. return (s.last_lit === s.lit_bufsize-1);
  18367. /* We avoid equality with lit_bufsize because of wraparound at 64K
  18368. * on 16 bit machines and because stored blocks are restricted to
  18369. * 64K-1 bytes.
  18370. */
  18371. }
  18372. exports._tr_init = _tr_init;
  18373. exports._tr_stored_block = _tr_stored_block;
  18374. exports._tr_flush_block = _tr_flush_block;
  18375. exports._tr_tally = _tr_tally;
  18376. exports._tr_align = _tr_align;
  18377. },{"../utils/common":51}],63:[function(require,module,exports){
  18378. 'use strict';
  18379. function ZStream() {
  18380. /* next input byte */
  18381. this.input = null; // JS specific, because we have no pointers
  18382. this.next_in = 0;
  18383. /* number of bytes available at input */
  18384. this.avail_in = 0;
  18385. /* total number of input bytes read so far */
  18386. this.total_in = 0;
  18387. /* next output byte should be put there */
  18388. this.output = null; // JS specific, because we have no pointers
  18389. this.next_out = 0;
  18390. /* remaining free space at output */
  18391. this.avail_out = 0;
  18392. /* total number of bytes output so far */
  18393. this.total_out = 0;
  18394. /* last error message, NULL if no error */
  18395. this.msg = ''/*Z_NULL*/;
  18396. /* not visible by applications */
  18397. this.state = null;
  18398. /* best guess about the data type: binary or text */
  18399. this.data_type = 2/*Z_UNKNOWN*/;
  18400. /* adler32 value of the uncompressed data */
  18401. this.adler = 0;
  18402. }
  18403. module.exports = ZStream;
  18404. },{}],64:[function(require,module,exports){
  18405. /* Copyright @ 2015 Atlassian Pty Ltd
  18406. *
  18407. * Licensed under the Apache License, Version 2.0 (the "License");
  18408. * you may not use this file except in compliance with the License.
  18409. * You may obtain a copy of the License at
  18410. *
  18411. * http://www.apache.org/licenses/LICENSE-2.0
  18412. *
  18413. * Unless required by applicable law or agreed to in writing, software
  18414. * distributed under the License is distributed on an "AS IS" BASIS,
  18415. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  18416. * See the License for the specific language governing permissions and
  18417. * limitations under the License.
  18418. */
  18419. module.exports = function arrayEquals(array) {
  18420. // if the other array is a falsy value, return
  18421. if (!array)
  18422. return false;
  18423. // compare lengths - can save a lot of time
  18424. if (this.length != array.length)
  18425. return false;
  18426. for (var i = 0, l = this.length; i < l; i++) {
  18427. // Check if we have nested arrays
  18428. if (this[i] instanceof Array && array[i] instanceof Array) {
  18429. // recurse into the nested arrays
  18430. if (!arrayEquals.apply(this[i], [array[i]]))
  18431. return false;
  18432. } else if (this[i] != array[i]) {
  18433. // Warning - two different object instances will never be equal:
  18434. // {x:20} != {x:20}
  18435. return false;
  18436. }
  18437. }
  18438. return true;
  18439. };
  18440. },{}],65:[function(require,module,exports){
  18441. /* Copyright @ 2015 Atlassian Pty Ltd
  18442. *
  18443. * Licensed under the Apache License, Version 2.0 (the "License");
  18444. * you may not use this file except in compliance with the License.
  18445. * You may obtain a copy of the License at
  18446. *
  18447. * http://www.apache.org/licenses/LICENSE-2.0
  18448. *
  18449. * Unless required by applicable law or agreed to in writing, software
  18450. * distributed under the License is distributed on an "AS IS" BASIS,
  18451. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  18452. * See the License for the specific language governing permissions and
  18453. * limitations under the License.
  18454. */
  18455. exports.Interop = require('./interop');
  18456. },{"./interop":66}],66:[function(require,module,exports){
  18457. /* Copyright @ 2015 Atlassian Pty Ltd
  18458. *
  18459. * Licensed under the Apache License, Version 2.0 (the "License");
  18460. * you may not use this file except in compliance with the License.
  18461. * You may obtain a copy of the License at
  18462. *
  18463. * http://www.apache.org/licenses/LICENSE-2.0
  18464. *
  18465. * Unless required by applicable law or agreed to in writing, software
  18466. * distributed under the License is distributed on an "AS IS" BASIS,
  18467. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  18468. * See the License for the specific language governing permissions and
  18469. * limitations under the License.
  18470. */
  18471. /* global RTCSessionDescription */
  18472. /* jshint -W097 */
  18473. "use strict";
  18474. var transform = require('./transform');
  18475. var arrayEquals = require('./array-equals');
  18476. function Interop() {
  18477. /**
  18478. * This map holds the most recent Unified Plan offer/answer SDP that was
  18479. * converted to Plan B, with the SDP type ('offer' or 'answer') as keys and
  18480. * the SDP string as values.
  18481. *
  18482. * @type {{}}
  18483. */
  18484. this.cache = {};
  18485. }
  18486. module.exports = Interop;
  18487. /**
  18488. * Returns the index of the first m-line with the given media type and with a
  18489. * direction which allows sending, in the last Unified Plan description with
  18490. * type "answer" converted to Plan B. Returns {null} if there is no saved
  18491. * answer, or if none of its m-lines with the given type allow sending.
  18492. * @param type the media type ("audio" or "video").
  18493. * @returns {*}
  18494. */
  18495. Interop.prototype.getFirstSendingIndexFromAnswer = function(type) {
  18496. if (!this.cache.answer) {
  18497. return null;
  18498. }
  18499. var session = transform.parse(this.cache.answer);
  18500. if (session && session.media && Array.isArray(session.media)){
  18501. for (var i = 0; i < session.media.length; i++) {
  18502. if (session.media[i].type == type &&
  18503. (!session.media[i].direction /* default to sendrecv */ ||
  18504. session.media[i].direction === 'sendrecv' ||
  18505. session.media[i].direction === 'sendonly')){
  18506. return i;
  18507. }
  18508. }
  18509. }
  18510. return null;
  18511. };
  18512. /**
  18513. * This method transforms a Unified Plan SDP to an equivalent Plan B SDP. A
  18514. * PeerConnection wrapper transforms the SDP to Plan B before passing it to the
  18515. * application.
  18516. *
  18517. * @param desc
  18518. * @returns {*}
  18519. */
  18520. Interop.prototype.toPlanB = function(desc) {
  18521. var self = this;
  18522. //#region Preliminary input validation.
  18523. if (typeof desc !== 'object' || desc === null ||
  18524. typeof desc.sdp !== 'string') {
  18525. console.warn('An empty description was passed as an argument.');
  18526. return desc;
  18527. }
  18528. // Objectify the SDP for easier manipulation.
  18529. var session = transform.parse(desc.sdp);
  18530. // If the SDP contains no media, there's nothing to transform.
  18531. if (typeof session.media === 'undefined' ||
  18532. !Array.isArray(session.media) || session.media.length === 0) {
  18533. console.warn('The description has no media.');
  18534. return desc;
  18535. }
  18536. // Try some heuristics to "make sure" this is a Unified Plan SDP. Plan B
  18537. // SDP has a video, an audio and a data "channel" at most.
  18538. if (session.media.length <= 3 && session.media.every(function(m) {
  18539. return ['video', 'audio', 'data'].indexOf(m.mid) !== -1;
  18540. })) {
  18541. console.warn('This description does not look like Unified Plan.');
  18542. return desc;
  18543. }
  18544. //#endregion
  18545. // HACK https://bugzilla.mozilla.org/show_bug.cgi?id=1113443
  18546. var sdp = desc.sdp;
  18547. var rewrite = false;
  18548. for (var i = 0; i < session.media.length; i++) {
  18549. var uLine = session.media[i];
  18550. uLine.rtp.forEach(function(rtp) {
  18551. if (rtp.codec === 'NULL')
  18552. {
  18553. rewrite = true;
  18554. var offer = transform.parse(self.cache['offer']);
  18555. rtp.codec = offer.media[i].rtp[0].codec;
  18556. }
  18557. });
  18558. };
  18559. if (rewrite) {
  18560. sdp = transform.write(session);
  18561. }
  18562. // Unified Plan SDP is our "precious". Cache it for later use in the Plan B
  18563. // -> Unified Plan transformation.
  18564. this.cache[desc.type] = sdp;
  18565. //#region Convert from Unified Plan to Plan B.
  18566. // We rebuild the session.media array.
  18567. var media = session.media;
  18568. session.media = [];
  18569. // Associative array that maps channel types to channel objects for fast
  18570. // access to channel objects by their type, e.g. type2bl['audio']->channel
  18571. // obj.
  18572. var type2bl = {};
  18573. // Used to build the group:BUNDLE value after the channels construction
  18574. // loop.
  18575. var types = [];
  18576. // Implode the Unified Plan m-lines/tracks into Plan B channels.
  18577. media.forEach(function(uLine) {
  18578. // rtcp-mux is required in the Plan B SDP.
  18579. if ((typeof uLine.rtcpMux !== 'string' ||
  18580. uLine.rtcpMux !== 'rtcp-mux') &&
  18581. uLine.direction !== 'inactive') {
  18582. throw new Error('Cannot convert to Plan B because m-lines ' +
  18583. 'without the rtcp-mux attribute were found.');
  18584. }
  18585. if (uLine.type === 'application') {
  18586. session.media.push(uLine);
  18587. types.push(uLine.mid);
  18588. return;
  18589. }
  18590. // If we don't have a channel for this uLine.type, then use this
  18591. // uLine as the channel basis.
  18592. if (typeof type2bl[uLine.type] === 'undefined') {
  18593. type2bl[uLine.type] = uLine;
  18594. }
  18595. // Add sources to the channel and handle a=msid.
  18596. if (typeof uLine.sources === 'object') {
  18597. Object.keys(uLine.sources).forEach(function(ssrc) {
  18598. if (typeof type2bl[uLine.type].sources !== 'object')
  18599. type2bl[uLine.type].sources = {};
  18600. // Assign the sources to the channel.
  18601. type2bl[uLine.type].sources[ssrc] =
  18602. uLine.sources[ssrc];
  18603. if (typeof uLine.msid !== 'undefined') {
  18604. // In Plan B the msid is an SSRC attribute. Also, we don't
  18605. // care about the obsolete label and mslabel attributes.
  18606. //
  18607. // Note that it is not guaranteed that the uLine will
  18608. // have an msid. recvonly channels in particular don't have
  18609. // one.
  18610. type2bl[uLine.type].sources[ssrc].msid =
  18611. uLine.msid;
  18612. }
  18613. // NOTE ssrcs in ssrc groups will share msids, as
  18614. // draft-uberti-rtcweb-plan-00 mandates.
  18615. });
  18616. }
  18617. // Add ssrc groups to the channel.
  18618. if (typeof uLine.ssrcGroups !== 'undefined' &&
  18619. Array.isArray(uLine.ssrcGroups)) {
  18620. // Create the ssrcGroups array, if it's not defined.
  18621. if (typeof type2bl[uLine.type].ssrcGroups === 'undefined' ||
  18622. !Array.isArray(type2bl[uLine.type].ssrcGroups)) {
  18623. type2bl[uLine.type].ssrcGroups = [];
  18624. }
  18625. type2bl[uLine.type].ssrcGroups =
  18626. type2bl[uLine.type].ssrcGroups.concat(
  18627. uLine.ssrcGroups);
  18628. }
  18629. if (type2bl[uLine.type] === uLine) {
  18630. // Copy ICE related stuff from the principal media line.
  18631. uLine.candidates = media[0].candidates;
  18632. uLine.iceUfrag = media[0].iceUfrag;
  18633. uLine.icePwd = media[0].icePwd;
  18634. uLine.fingerprint = media[0].fingerprint;
  18635. // Plan B mids are in ['audio', 'video', 'data']
  18636. uLine.mid = uLine.type;
  18637. // Plan B doesn't support/need the bundle-only attribute.
  18638. delete uLine.bundleOnly;
  18639. // In Plan B the msid is an SSRC attribute.
  18640. delete uLine.msid;
  18641. // Used to build the group:BUNDLE value after this loop.
  18642. types.push(uLine.type);
  18643. // Add the channel to the new media array.
  18644. session.media.push(uLine);
  18645. }
  18646. });
  18647. // We regenerate the BUNDLE group with the new mids.
  18648. session.groups.some(function(group) {
  18649. if (group.type === 'BUNDLE') {
  18650. group.mids = types.join(' ');
  18651. return true;
  18652. }
  18653. });
  18654. // msid semantic
  18655. session.msidSemantic = {
  18656. semantic: 'WMS',
  18657. token: '*'
  18658. };
  18659. var resStr = transform.write(session);
  18660. return new RTCSessionDescription({
  18661. type: desc.type,
  18662. sdp: resStr
  18663. });
  18664. //#endregion
  18665. };
  18666. /**
  18667. * This method transforms a Plan B SDP to an equivalent Unified Plan SDP. A
  18668. * PeerConnection wrapper transforms the SDP to Unified Plan before passing it
  18669. * to FF.
  18670. *
  18671. * @param desc
  18672. * @returns {*}
  18673. */
  18674. Interop.prototype.toUnifiedPlan = function(desc) {
  18675. var self = this;
  18676. //#region Preliminary input validation.
  18677. if (typeof desc !== 'object' || desc === null ||
  18678. typeof desc.sdp !== 'string') {
  18679. console.warn('An empty description was passed as an argument.');
  18680. return desc;
  18681. }
  18682. var session = transform.parse(desc.sdp);
  18683. // If the SDP contains no media, there's nothing to transform.
  18684. if (typeof session.media === 'undefined' ||
  18685. !Array.isArray(session.media) || session.media.length === 0) {
  18686. console.warn('The description has no media.');
  18687. return desc;
  18688. }
  18689. // Try some heuristics to "make sure" this is a Plan B SDP. Plan B SDP has
  18690. // a video, an audio and a data "channel" at most.
  18691. if (session.media.length > 3 || !session.media.every(function(m) {
  18692. return ['video', 'audio', 'data'].indexOf(m.mid) !== -1;
  18693. })) {
  18694. console.warn('This description does not look like Plan B.');
  18695. return desc;
  18696. }
  18697. // Make sure this Plan B SDP can be converted to a Unified Plan SDP.
  18698. var mids = [];
  18699. session.media.forEach(function(m) {
  18700. mids.push(m.mid);
  18701. });
  18702. var hasBundle = false;
  18703. if (typeof session.groups !== 'undefined' &&
  18704. Array.isArray(session.groups)) {
  18705. hasBundle = session.groups.every(function(g) {
  18706. return g.type !== 'BUNDLE' ||
  18707. arrayEquals.apply(g.mids.sort(), [mids.sort()]);
  18708. });
  18709. }
  18710. if (!hasBundle) {
  18711. throw new Error("Cannot convert to Unified Plan because m-lines that" +
  18712. " are not bundled were found.");
  18713. }
  18714. //#endregion
  18715. //#region Convert from Plan B to Unified Plan.
  18716. // Unfortunately, a Plan B offer/answer doesn't have enough information to
  18717. // rebuild an equivalent Unified Plan offer/answer.
  18718. //
  18719. // For example, if this is a local answer (in Unified Plan style) that we
  18720. // convert to Plan B prior to handing it over to the application (the
  18721. // PeerConnection wrapper called us, for instance, after a successful
  18722. // createAnswer), we want to remember the m-line at which we've seen the
  18723. // (local) SSRC. That's because when the application wants to do call the
  18724. // SLD method, forcing us to do the inverse transformation (from Plan B to
  18725. // Unified Plan), we need to know to which m-line to assign the (local)
  18726. // SSRC. We also need to know all the other m-lines that the original
  18727. // answer had and include them in the transformed answer as well.
  18728. //
  18729. // Another example is if this is a remote offer that we convert to Plan B
  18730. // prior to giving it to the application, we want to remember the mid at
  18731. // which we've seen the (remote) SSRC.
  18732. //
  18733. // In the iteration that follows, we use the cached Unified Plan (if it
  18734. // exists) to assign mids to ssrcs.
  18735. var cached;
  18736. if (typeof this.cache[desc.type] !== 'undefined') {
  18737. cached = transform.parse(this.cache[desc.type]);
  18738. }
  18739. var recvonlySsrcs = {
  18740. audio: {},
  18741. video: {}
  18742. };
  18743. // A helper map that sends mids to m-line objects. We use it later to
  18744. // rebuild the Unified Plan style session.media array.
  18745. var mid2ul = {};
  18746. session.media.forEach(function(bLine) {
  18747. if ((typeof bLine.rtcpMux !== 'string' ||
  18748. bLine.rtcpMux !== 'rtcp-mux') &&
  18749. bLine.direction !== 'inactive') {
  18750. throw new Error("Cannot convert to Unified Plan because m-lines " +
  18751. "without the rtcp-mux attribute were found.");
  18752. }
  18753. if (bLine.type === 'application') {
  18754. mid2ul[bLine.mid] = bLine;
  18755. return;
  18756. }
  18757. // With rtcp-mux and bundle all the channels should have the same ICE
  18758. // stuff.
  18759. var sources = bLine.sources;
  18760. var ssrcGroups = bLine.ssrcGroups;
  18761. var candidates = bLine.candidates;
  18762. var iceUfrag = bLine.iceUfrag;
  18763. var icePwd = bLine.icePwd;
  18764. var fingerprint = bLine.fingerprint;
  18765. var port = bLine.port;
  18766. // We'll use the "bLine" object as a prototype for each new "mLine"
  18767. // that we create, but first we need to clean it up a bit.
  18768. delete bLine.sources;
  18769. delete bLine.ssrcGroups;
  18770. delete bLine.candidates;
  18771. delete bLine.iceUfrag;
  18772. delete bLine.icePwd;
  18773. delete bLine.fingerprint;
  18774. delete bLine.port;
  18775. delete bLine.mid;
  18776. // inverted ssrc group map
  18777. var ssrc2group = {};
  18778. if (typeof ssrcGroups !== 'undefined' && Array.isArray(ssrcGroups)) {
  18779. ssrcGroups.forEach(function (ssrcGroup) {
  18780. // TODO(gp) find out how to receive simulcast with FF. For the
  18781. // time being, hide it.
  18782. if (ssrcGroup.semantics === 'SIM') {
  18783. return;
  18784. }
  18785. // XXX This might brake if an SSRC is in more than one group
  18786. // for some reason.
  18787. if (typeof ssrcGroup.ssrcs !== 'undefined' &&
  18788. Array.isArray(ssrcGroup.ssrcs)) {
  18789. ssrcGroup.ssrcs.forEach(function (ssrc) {
  18790. if (typeof ssrc2group[ssrc] === 'undefined') {
  18791. ssrc2group[ssrc] = [];
  18792. }
  18793. ssrc2group[ssrc].push(ssrcGroup);
  18794. });
  18795. }
  18796. });
  18797. }
  18798. // ssrc to m-line index.
  18799. var ssrc2ml = {};
  18800. if (typeof sources === 'object') {
  18801. // Explode the Plan B channel sources with one m-line per source.
  18802. Object.keys(sources).forEach(function(ssrc) {
  18803. // The (unified) m-line for this SSRC. We either create it from
  18804. // scratch or, if it's a grouped SSRC, we re-use a related
  18805. // mline. In other words, if the source is grouped with another
  18806. // source, put the two together in the same m-line.
  18807. var uLine;
  18808. // We assume here that we are the answerer in the O/A, so any
  18809. // offers which we translate come from the remote side, while
  18810. // answers are local. So the check below is to make that we
  18811. // handle receive-only SSRCs in a special way only if they come
  18812. // from the remote side.
  18813. if (desc.type==='offer') {
  18814. // We want to detect SSRCs which are used by a remote peer
  18815. // in an m-line with direction=recvonly (i.e. they are
  18816. // being used for RTCP only).
  18817. // This information would have gotten lost if the remote
  18818. // peer used Unified Plan and their local description was
  18819. // translated to Plan B. So we use the lack of an MSID
  18820. // attribute to deduce a "receive only" SSRC.
  18821. if (!sources[ssrc].msid) {
  18822. recvonlySsrcs[bLine.type][ssrc] = sources[ssrc];
  18823. // Receive-only SSRCs must not create new m-lines. We
  18824. // will assign them to an existing m-line later.
  18825. return;
  18826. }
  18827. }
  18828. if (typeof ssrc2group[ssrc] !== 'undefined' &&
  18829. Array.isArray(ssrc2group[ssrc])) {
  18830. ssrc2group[ssrc].some(function (ssrcGroup) {
  18831. // ssrcGroup.ssrcs *is* an Array, no need to check
  18832. // again here.
  18833. return ssrcGroup.ssrcs.some(function (related) {
  18834. if (typeof ssrc2ml[related] === 'object') {
  18835. uLine = ssrc2ml[related];
  18836. return true;
  18837. }
  18838. });
  18839. });
  18840. }
  18841. if (typeof uLine === 'object') {
  18842. // the m-line already exists. Just add the source.
  18843. uLine.sources[ssrc] = sources[ssrc];
  18844. delete sources[ssrc].msid;
  18845. } else {
  18846. // Use the "bLine" as a prototype for the "uLine".
  18847. uLine = Object.create(bLine);
  18848. ssrc2ml[ssrc] = uLine;
  18849. if (typeof sources[ssrc].msid !== 'undefined') {
  18850. // Assign the msid of the source to the m-line. Note
  18851. // that it is not guaranteed that the source will have
  18852. // msid. In particular "recvonly" sources don't have an
  18853. // msid. Note that "recvonly" is a term only defined
  18854. // for m-lines.
  18855. uLine.msid = sources[ssrc].msid;
  18856. uLine.direction = 'sendrecv';
  18857. delete sources[ssrc].msid;
  18858. }
  18859. // We assign one SSRC per media line.
  18860. uLine.sources = {};
  18861. uLine.sources[ssrc] = sources[ssrc];
  18862. uLine.ssrcGroups = ssrc2group[ssrc];
  18863. // Use the cached Unified Plan SDP (if it exists) to assign
  18864. // SSRCs to mids.
  18865. if (typeof cached !== 'undefined' &&
  18866. typeof cached.media !== 'undefined' &&
  18867. Array.isArray(cached.media)) {
  18868. cached.media.forEach(function (m) {
  18869. if (typeof m.sources === 'object') {
  18870. Object.keys(m.sources).forEach(function (s) {
  18871. if (s === ssrc) {
  18872. uLine.mid = m.mid;
  18873. }
  18874. });
  18875. }
  18876. });
  18877. }
  18878. if (typeof uLine.mid === 'undefined') {
  18879. // If this is an SSRC that we see for the first time
  18880. // assign it a new mid. This is typically the case when
  18881. // this method is called to transform a remote
  18882. // description for the first time or when there is a
  18883. // new SSRC in the remote description because a new
  18884. // peer has joined the conference. Local SSRCs should
  18885. // have already been added to the map in the toPlanB
  18886. // method.
  18887. //
  18888. // Because FF generates answers in Unified Plan style,
  18889. // we MUST already have a cached answer with all the
  18890. // local SSRCs mapped to some m-line/mid.
  18891. if (desc.type === 'answer') {
  18892. throw new Error("An unmapped SSRC was found.");
  18893. }
  18894. uLine.mid = [bLine.type, '-', ssrc].join('');
  18895. }
  18896. // Include the candidates in the 1st media line.
  18897. uLine.candidates = candidates;
  18898. uLine.iceUfrag = iceUfrag;
  18899. uLine.icePwd = icePwd;
  18900. uLine.fingerprint = fingerprint;
  18901. uLine.port = port;
  18902. mid2ul[uLine.mid] = uLine;
  18903. }
  18904. });
  18905. }
  18906. });
  18907. // Rebuild the media array in the right order and add the missing mLines
  18908. // (missing from the Plan B SDP).
  18909. session.media = [];
  18910. mids = []; // reuse
  18911. if (desc.type === 'answer') {
  18912. // The media lines in the answer must match the media lines in the
  18913. // offer. The order is important too. Here we assume that Firefox is
  18914. // the answerer, so we merely have to use the reconstructed (unified)
  18915. // answer to update the cached (unified) answer accordingly.
  18916. //
  18917. // In the general case, one would have to use the cached (unified)
  18918. // offer to find the m-lines that are missing from the reconstructed
  18919. // answer, potentially grabbing them from the cached (unified) answer.
  18920. // One has to be careful with this approach because inactive m-lines do
  18921. // not always have an mid, making it tricky (impossible?) to find where
  18922. // exactly and which m-lines are missing from the reconstructed answer.
  18923. for (var i = 0; i < cached.media.length; i++) {
  18924. var uLine = cached.media[i];
  18925. if (typeof mid2ul[uLine.mid] === 'undefined') {
  18926. // The mid isn't in the reconstructed (unified) answer.
  18927. // This is either a (unified) m-line containing a remote
  18928. // track only, or a (unified) m-line containing a remote
  18929. // track and a local track that has been removed.
  18930. // In either case, it MUST exist in the cached
  18931. // (unified) answer.
  18932. //
  18933. // In case this is a removed local track, clean-up
  18934. // the (unified) m-line and make sure it's 'recvonly' or
  18935. // 'inactive'.
  18936. delete uLine.msid;
  18937. delete uLine.sources;
  18938. delete uLine.ssrcGroups;
  18939. if (!uLine.direction
  18940. || uLine.direction === 'sendrecv')
  18941. uLine.direction = 'recvonly';
  18942. else if (uLine.direction === 'sendonly')
  18943. uLine.direction = 'inactive';
  18944. } else {
  18945. // This is an (unified) m-line/channel that contains a local
  18946. // track (sendrecv or sendonly channel) or it's a unified
  18947. // recvonly m-line/channel. In either case, since we're
  18948. // going from PlanB -> Unified Plan this m-line MUST
  18949. // exist in the cached answer.
  18950. }
  18951. session.media.push(uLine);
  18952. if (typeof uLine.mid === 'string') {
  18953. // inactive lines don't/may not have an mid.
  18954. mids.push(uLine.mid);
  18955. }
  18956. }
  18957. } else {
  18958. // SDP offer/answer (and the JSEP spec) forbids removing an m-section
  18959. // under any circumstances. If we are no longer interested in sending a
  18960. // track, we just remove the msid and ssrc attributes and set it to
  18961. // either a=recvonly (as the reofferer, we must use recvonly if the
  18962. // other side was previously sending on the m-section, but we can also
  18963. // leave the possibility open if it wasn't previously in use), or
  18964. // a=inactive.
  18965. if (typeof cached !== 'undefined' &&
  18966. typeof cached.media !== 'undefined' &&
  18967. Array.isArray(cached.media)) {
  18968. cached.media.forEach(function(uLine) {
  18969. mids.push(uLine.mid);
  18970. if (typeof mid2ul[uLine.mid] !== 'undefined') {
  18971. session.media.push(mid2ul[uLine.mid]);
  18972. } else {
  18973. delete uLine.msid;
  18974. delete uLine.sources;
  18975. delete uLine.ssrcGroups;
  18976. if (!uLine.direction
  18977. || uLine.direction === 'sendrecv')
  18978. uLine.direction = 'recvonly';
  18979. if (!uLine.direction
  18980. || uLine.direction === 'sendonly')
  18981. uLine.direction = 'inactive';
  18982. session.media.push(uLine);
  18983. }
  18984. });
  18985. }
  18986. // Add all the remaining (new) m-lines of the transformed SDP.
  18987. Object.keys(mid2ul).forEach(function(mid) {
  18988. if (mids.indexOf(mid) === -1) {
  18989. mids.push(mid);
  18990. if (mid2ul[mid].direction === 'recvonly') {
  18991. // This is a remote recvonly channel. Add its SSRC to the
  18992. // appropriate sendrecv or sendonly channel.
  18993. // TODO(gp) what if we don't have sendrecv/sendonly
  18994. // channel?
  18995. session.media.some(function (uLine) {
  18996. if ((uLine.direction === 'sendrecv' ||
  18997. uLine.direction === 'sendonly') &&
  18998. uLine.type === mid2ul[mid].type) {
  18999. // mid2ul[mid] shouldn't have any ssrc-groups
  19000. Object.keys(mid2ul[mid].sources).forEach(
  19001. function (ssrc) {
  19002. uLine.sources[ssrc] =
  19003. mid2ul[mid].sources[ssrc];
  19004. });
  19005. return true;
  19006. }
  19007. });
  19008. } else {
  19009. session.media.push(mid2ul[mid]);
  19010. }
  19011. }
  19012. });
  19013. }
  19014. // After we have constructed the Plan Unified m-lines we can figure out
  19015. // where (in which m-line) to place the 'recvonly SSRCs'.
  19016. // Note: we assume here that we are the answerer in the O/A, so any offers
  19017. // which we translate come from the remote side, while answers are local
  19018. // (and so our last local description is cached as an 'answer').
  19019. ["audio", "video"].forEach(function (type) {
  19020. if (!session || !session.media || !Array.isArray(session.media))
  19021. return;
  19022. var idx = null;
  19023. if (Object.keys(recvonlySsrcs[type]).length > 0) {
  19024. idx = self.getFirstSendingIndexFromAnswer(type);
  19025. if (idx === null){
  19026. // If this is the first offer we receive, we don't have a
  19027. // cached answer. Assume that we will be sending media using
  19028. // the first m-line for each media type.
  19029. for (var i = 0; i < session.media.length; i++) {
  19030. if (session.media[i].type === type) {
  19031. idx = i;
  19032. break;
  19033. }
  19034. }
  19035. }
  19036. }
  19037. if (idx && session.media.length > idx) {
  19038. var mLine = session.media[idx];
  19039. Object.keys(recvonlySsrcs[type]).forEach(function(ssrc) {
  19040. if (mLine.sources && mLine.sources[ssrc]) {
  19041. console.warn("Replacing an existing SSRC.");
  19042. }
  19043. if (!mLine.sources) {
  19044. mLine.sources = {};
  19045. }
  19046. mLine.sources[ssrc] = recvonlySsrcs[type][ssrc];
  19047. });
  19048. }
  19049. });
  19050. // We regenerate the BUNDLE group (since we regenerated the mids)
  19051. session.groups.some(function(group) {
  19052. if (group.type === 'BUNDLE') {
  19053. group.mids = mids.join(' ');
  19054. return true;
  19055. }
  19056. });
  19057. // msid semantic
  19058. session.msidSemantic = {
  19059. semantic: 'WMS',
  19060. token: '*'
  19061. };
  19062. var resStr = transform.write(session);
  19063. // Cache the transformed SDP (Unified Plan) for later re-use in this
  19064. // function.
  19065. this.cache[desc.type] = resStr;
  19066. return new RTCSessionDescription({
  19067. type: desc.type,
  19068. sdp: resStr
  19069. });
  19070. //#endregion
  19071. };
  19072. },{"./array-equals":64,"./transform":67}],67:[function(require,module,exports){
  19073. /* Copyright @ 2015 Atlassian Pty Ltd
  19074. *
  19075. * Licensed under the Apache License, Version 2.0 (the "License");
  19076. * you may not use this file except in compliance with the License.
  19077. * You may obtain a copy of the License at
  19078. *
  19079. * http://www.apache.org/licenses/LICENSE-2.0
  19080. *
  19081. * Unless required by applicable law or agreed to in writing, software
  19082. * distributed under the License is distributed on an "AS IS" BASIS,
  19083. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  19084. * See the License for the specific language governing permissions and
  19085. * limitations under the License.
  19086. */
  19087. var transform = require('sdp-transform');
  19088. exports.write = function(session, opts) {
  19089. if (typeof session !== 'undefined' &&
  19090. typeof session.media !== 'undefined' &&
  19091. Array.isArray(session.media)) {
  19092. session.media.forEach(function (mLine) {
  19093. // expand sources to ssrcs
  19094. if (typeof mLine.sources !== 'undefined' &&
  19095. Object.keys(mLine.sources).length !== 0) {
  19096. mLine.ssrcs = [];
  19097. Object.keys(mLine.sources).forEach(function (ssrc) {
  19098. var source = mLine.sources[ssrc];
  19099. Object.keys(source).forEach(function (attribute) {
  19100. mLine.ssrcs.push({
  19101. id: ssrc,
  19102. attribute: attribute,
  19103. value: source[attribute]
  19104. });
  19105. });
  19106. });
  19107. delete mLine.sources;
  19108. }
  19109. // join ssrcs in ssrc groups
  19110. if (typeof mLine.ssrcGroups !== 'undefined' &&
  19111. Array.isArray(mLine.ssrcGroups)) {
  19112. mLine.ssrcGroups.forEach(function (ssrcGroup) {
  19113. if (typeof ssrcGroup.ssrcs !== 'undefined' &&
  19114. Array.isArray(ssrcGroup.ssrcs)) {
  19115. ssrcGroup.ssrcs = ssrcGroup.ssrcs.join(' ');
  19116. }
  19117. });
  19118. }
  19119. });
  19120. }
  19121. // join group mids
  19122. if (typeof session !== 'undefined' &&
  19123. typeof session.groups !== 'undefined' && Array.isArray(session.groups)) {
  19124. session.groups.forEach(function (g) {
  19125. if (typeof g.mids !== 'undefined' && Array.isArray(g.mids)) {
  19126. g.mids = g.mids.join(' ');
  19127. }
  19128. });
  19129. }
  19130. return transform.write(session, opts);
  19131. };
  19132. exports.parse = function(sdp) {
  19133. var session = transform.parse(sdp);
  19134. if (typeof session !== 'undefined' && typeof session.media !== 'undefined' &&
  19135. Array.isArray(session.media)) {
  19136. session.media.forEach(function (mLine) {
  19137. // group sources attributes by ssrc
  19138. if (typeof mLine.ssrcs !== 'undefined' && Array.isArray(mLine.ssrcs)) {
  19139. mLine.sources = {};
  19140. mLine.ssrcs.forEach(function (ssrc) {
  19141. if (!mLine.sources[ssrc.id])
  19142. mLine.sources[ssrc.id] = {};
  19143. mLine.sources[ssrc.id][ssrc.attribute] = ssrc.value;
  19144. });
  19145. delete mLine.ssrcs;
  19146. }
  19147. // split ssrcs in ssrc groups
  19148. if (typeof mLine.ssrcGroups !== 'undefined' &&
  19149. Array.isArray(mLine.ssrcGroups)) {
  19150. mLine.ssrcGroups.forEach(function (ssrcGroup) {
  19151. if (typeof ssrcGroup.ssrcs === 'string') {
  19152. ssrcGroup.ssrcs = ssrcGroup.ssrcs.split(' ');
  19153. }
  19154. });
  19155. }
  19156. });
  19157. }
  19158. // split group mids
  19159. if (typeof session !== 'undefined' &&
  19160. typeof session.groups !== 'undefined' && Array.isArray(session.groups)) {
  19161. session.groups.forEach(function (g) {
  19162. if (typeof g.mids === 'string') {
  19163. g.mids = g.mids.split(' ');
  19164. }
  19165. });
  19166. }
  19167. return session;
  19168. };
  19169. },{"sdp-transform":75}],68:[function(require,module,exports){
  19170. /* Copyright @ 2015 Atlassian Pty Ltd
  19171. *
  19172. * Licensed under the Apache License, Version 2.0 (the "License");
  19173. * you may not use this file except in compliance with the License.
  19174. * You may obtain a copy of the License at
  19175. *
  19176. * http://www.apache.org/licenses/LICENSE-2.0
  19177. *
  19178. * Unless required by applicable law or agreed to in writing, software
  19179. * distributed under the License is distributed on an "AS IS" BASIS,
  19180. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  19181. * See the License for the specific language governing permissions and
  19182. * limitations under the License.
  19183. */
  19184. var transform = require('sdp-transform');
  19185. var transformUtils = require('./transform-utils');
  19186. var parseSsrcs = transformUtils.parseSsrcs;
  19187. var writeSsrcs = transformUtils.writeSsrcs;
  19188. //region Constants
  19189. var DEFAULT_NUM_OF_LAYERS = 3;
  19190. //endregion
  19191. //region Ctor
  19192. function Simulcast(options) {
  19193. this.options = options ? options : {};
  19194. if (!this.options.numOfLayers) {
  19195. this.options.numOfLayers = DEFAULT_NUM_OF_LAYERS;
  19196. }
  19197. this.layers = [];
  19198. }
  19199. //endregion
  19200. //region Stateless private utility functions
  19201. /**
  19202. * Returns a random integer between min (included) and max (excluded)
  19203. * Using Math.round() gives a non-uniform distribution!
  19204. * @returns {number}
  19205. */
  19206. function generateSSRC() {
  19207. var min = 0, max = 0xffffffff;
  19208. return Math.floor(Math.random() * (max - min)) + min;
  19209. };
  19210. function processVideo(session, action) {
  19211. if (session == null || !Array.isArray(session.media)) {
  19212. return;
  19213. }
  19214. session.media.forEach(function (mLine) {
  19215. if (mLine.type === 'video') {
  19216. action(mLine);
  19217. }
  19218. });
  19219. }
  19220. function validateDescription(desc)
  19221. {
  19222. return desc && desc != null
  19223. && desc.type && desc.type != ''
  19224. && desc.sdp && desc.sdp != '';
  19225. }
  19226. function explodeRemoteSimulcast(mLine) {
  19227. if (!mLine || !Array.isArray(mLine.ssrcGroups)) {
  19228. return;
  19229. }
  19230. var sources = parseSsrcs(mLine);
  19231. var order = [];
  19232. // Find the SIM group and explode its sources.
  19233. var j = mLine.ssrcGroups.length;
  19234. while (j--) {
  19235. if (mLine.ssrcGroups[j].semantics !== 'SIM') {
  19236. continue;
  19237. }
  19238. var simulcastSsrcs = mLine.ssrcGroups[j].ssrcs.split(' ');
  19239. for (var i = 0; i < simulcastSsrcs.length; i++) {
  19240. var ssrc = simulcastSsrcs[i];
  19241. order.push(ssrc);
  19242. var parts = sources[ssrc].msid.split(' ');
  19243. sources[ssrc].msid = [parts[0], '/', i, ' ', parts[1], '/', i].join('');
  19244. sources[ssrc].cname = [sources[ssrc].cname, '/', i].join('');
  19245. // Remove all the groups that this SSRC participates in.
  19246. mLine.ssrcGroups.forEach(function (relatedGroup) {
  19247. if (relatedGroup.semantics === 'SIM') {
  19248. return;
  19249. }
  19250. var relatedSsrcs = relatedGroup.ssrcs.split(' ');
  19251. if (relatedSsrcs.indexOf(ssrc) === -1) {
  19252. return;
  19253. }
  19254. // Nuke all the related SSRCs.
  19255. relatedSsrcs.forEach(function (relatedSSRC) {
  19256. sources[relatedSSRC].msid = sources[ssrc].msid;
  19257. sources[relatedSSRC].cname = sources[ssrc].cname;
  19258. if (relatedSSRC !== ssrc) {
  19259. order.push(relatedSSRC);
  19260. }
  19261. });
  19262. // Schedule the related group for nuking.
  19263. })
  19264. }
  19265. mLine.ssrcs = writeSsrcs(sources, order);
  19266. mLine.ssrcGroups.splice(j, 1);
  19267. };
  19268. }
  19269. function implodeRemoteSimulcast(mLine) {
  19270. if (!mLine || !Array.isArray(mLine.ssrcGroups)) {
  19271. console.debug('Halt: There are no SSRC groups in the remote ' +
  19272. 'description.');
  19273. return;
  19274. }
  19275. var sources = parseSsrcs(mLine);
  19276. // Find the SIM group and nuke it.
  19277. mLine.ssrcGroups.forEach(function (simulcastGroup) {
  19278. if (simulcastGroup.semantics !== 'SIM') {
  19279. return;
  19280. }
  19281. console.debug("Imploding SIM group: " + simulcastGroup.ssrcs);
  19282. // Schedule the SIM group for nuking.
  19283. simulcastGroup.nuke = true;
  19284. var simulcastSsrcs = simulcastGroup.ssrcs.split(' ');
  19285. // Nuke all the higher layer SSRCs.
  19286. for (var i = 1; i < simulcastSsrcs.length; i++) {
  19287. var ssrc = simulcastSsrcs[i];
  19288. delete sources[ssrc];
  19289. // Remove all the groups that this SSRC participates in.
  19290. mLine.ssrcGroups.forEach(function (relatedGroup) {
  19291. if (relatedGroup.semantics === 'SIM') {
  19292. return;
  19293. }
  19294. var relatedSsrcs = relatedGroup.ssrcs.split(' ');
  19295. if (relatedSsrcs.indexOf(ssrc) === -1) {
  19296. return;
  19297. }
  19298. // Nuke all the related SSRCs.
  19299. relatedSsrcs.forEach(function (relatedSSRC) {
  19300. delete sources[relatedSSRC];
  19301. });
  19302. // Schedule the related group for nuking.
  19303. relatedGroup.nuke = true;
  19304. })
  19305. }
  19306. return;
  19307. });
  19308. mLine.ssrcs = writeSsrcs(sources);
  19309. // Nuke all the scheduled groups.
  19310. var i = mLine.ssrcGroups.length;
  19311. while (i--) {
  19312. if (mLine.ssrcGroups[i].nuke) {
  19313. mLine.ssrcGroups.splice(i, 1);
  19314. }
  19315. }
  19316. }
  19317. function removeGoogConference(mLine) {
  19318. if (!mLine || !Array.isArray(mLine.invalid)) {
  19319. return;
  19320. }
  19321. var i = mLine.invalid.length;
  19322. while (i--) {
  19323. if (mLine.invalid[i].value == 'x-google-flag:conference') {
  19324. mLine.invalid.splice(i, 1);
  19325. }
  19326. }
  19327. }
  19328. function assertGoogConference(mLine) {
  19329. if (!mLine) {
  19330. return;
  19331. }
  19332. if (!Array.isArray(mLine.invalid)) {
  19333. mLine.invalid = [];
  19334. }
  19335. if (!mLine.invalid.some(
  19336. function (i) { return i.value === 'x-google-flag:conference' })) {
  19337. mLine.invalid.push({'value': 'x-google-flag:conference'});
  19338. }
  19339. }
  19340. //endregion
  19341. //region "Private" functions
  19342. /**
  19343. *
  19344. * @param mLine
  19345. * @private
  19346. */
  19347. Simulcast.prototype._maybeInitializeLayers = function(mLine) {
  19348. if (!mLine || mLine.type !== 'video') {
  19349. return;
  19350. }
  19351. var sources = parseSsrcs(mLine);
  19352. if (Object.keys(sources).length === 0) {
  19353. // no sources, disable simulcast.
  19354. if (this.layers.length !== 0) {
  19355. this.layers = [];
  19356. }
  19357. return;
  19358. }
  19359. // find the base layer (we'll reuse its msid and cname).
  19360. var baseLayerSSRC = Object.keys(sources)[0];
  19361. var baseLayer = sources[baseLayerSSRC];
  19362. // todo(gp) handle screen sharing.
  19363. // check if base CNAME has changed and reinitialise layers.
  19364. if (this.layers.length > 0
  19365. && sources[baseLayerSSRC].cname !== this.layers[0].cname) {
  19366. this.layers = [];
  19367. }
  19368. // (re)initialise layers
  19369. if (this.layers.length < 1) {
  19370. // first push the base layer.
  19371. this.layers.push({
  19372. ssrc: baseLayerSSRC,
  19373. msid: baseLayer.msid,
  19374. cname: baseLayer.cname
  19375. });
  19376. var rtx = false; // RFC 4588
  19377. if (Array.isArray(mLine.rtp)) {
  19378. rtx = mLine.rtp.some(
  19379. function (rtpmap) { return rtpmap.codec === 'rtx'; });
  19380. }
  19381. if (rtx) {
  19382. this.layers[0].rtx = generateSSRC();
  19383. }
  19384. // now push additional layers.
  19385. for (var i = 1; i < Math.max(1, this.options.numOfLayers); i++) {
  19386. var layer = { ssrc: generateSSRC() };
  19387. if (rtx) {
  19388. layer.rtx = generateSSRC();
  19389. }
  19390. this.layers.push(layer);
  19391. }
  19392. }
  19393. };
  19394. /**
  19395. *
  19396. * @param mLine
  19397. * @private
  19398. */
  19399. Simulcast.prototype._restoreSimulcastView = function(mLine) {
  19400. if (mLine && mLine.type === 'video' && this.layers.length !== 0) {
  19401. var sources = {};
  19402. var msid = this.layers[0].msid;
  19403. var cname = this.layers[0].cname;
  19404. var simulcastSsrcs = [];
  19405. var ssrcGroups = [];
  19406. for (var i = 0; i < this.layers.length; i++) {
  19407. var layer = this.layers[i];
  19408. sources[layer.ssrc] = { msid: msid, cname: cname };
  19409. simulcastSsrcs.push(layer.ssrc);
  19410. if (layer.rtx) {
  19411. sources[layer.rtx] = {
  19412. msid: msid,
  19413. cname: cname
  19414. }
  19415. ssrcGroups.push({
  19416. semantics: 'FID',
  19417. ssrcs: [layer.ssrc, layer.rtx].join(' ')
  19418. });
  19419. }
  19420. }
  19421. ssrcGroups.push({
  19422. semantics: 'SIM',
  19423. ssrcs: simulcastSsrcs.join(' ')
  19424. });
  19425. mLine.ssrcGroups = ssrcGroups;
  19426. mLine.ssrcs = writeSsrcs(sources);
  19427. }
  19428. }
  19429. //endregion
  19430. //region "Public" functions
  19431. Simulcast.prototype.isSupported = function () {
  19432. return window.chrome;
  19433. // TODO this needs improvements. For example I doubt that Chrome in Android
  19434. // has simulcast support. Also, only recent versions of Chromium have native
  19435. // simulcast support.
  19436. }
  19437. /**
  19438. *
  19439. * @param desc
  19440. * @returns {RTCSessionDescription}
  19441. */
  19442. Simulcast.prototype.mungeRemoteDescription = function (desc) {
  19443. if (!validateDescription(desc)) {
  19444. return desc;
  19445. }
  19446. var session = transform.parse(desc.sdp);
  19447. var self = this;
  19448. processVideo(session, function (mLine) {
  19449. // Handle simulcast reception.
  19450. if (self.options.explodeRemoteSimulcast) {
  19451. explodeRemoteSimulcast(mLine);
  19452. } else {
  19453. implodeRemoteSimulcast(mLine);
  19454. }
  19455. // If native simulcast is enabled, we must append the x-goog-conference
  19456. // attribute to the SDP.
  19457. if (self.layers.length < 1) {
  19458. removeGoogConference(mLine);
  19459. } else {
  19460. assertGoogConference(mLine);
  19461. }
  19462. });
  19463. return new RTCSessionDescription({
  19464. type: desc.type,
  19465. sdp: transform.write(session)
  19466. });
  19467. };
  19468. /**
  19469. *
  19470. * @param desc
  19471. * @returns {RTCSessionDescription}
  19472. */
  19473. Simulcast.prototype.mungeLocalDescription = function (desc) {
  19474. if (!validateDescription(desc) || !this.isSupported()) {
  19475. return desc;
  19476. }
  19477. var session = transform.parse(desc.sdp);
  19478. var self = this;
  19479. processVideo(session, function (mLine) {
  19480. // Initialize native simulcast layers, if not already done.
  19481. self._maybeInitializeLayers(mLine);
  19482. // Update the SDP with the simulcast layers.
  19483. self._restoreSimulcastView(mLine);
  19484. });
  19485. return new RTCSessionDescription({
  19486. type: desc.type,
  19487. sdp: transform.write(session)
  19488. });
  19489. };
  19490. //endregion
  19491. module.exports = Simulcast;
  19492. },{"./transform-utils":69,"sdp-transform":71}],69:[function(require,module,exports){
  19493. /* Copyright @ 2015 Atlassian Pty Ltd
  19494. *
  19495. * Licensed under the Apache License, Version 2.0 (the "License");
  19496. * you may not use this file except in compliance with the License.
  19497. * You may obtain a copy of the License at
  19498. *
  19499. * http://www.apache.org/licenses/LICENSE-2.0
  19500. *
  19501. * Unless required by applicable law or agreed to in writing, software
  19502. * distributed under the License is distributed on an "AS IS" BASIS,
  19503. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  19504. * See the License for the specific language governing permissions and
  19505. * limitations under the License.
  19506. */
  19507. exports.writeSsrcs = function(sources, order) {
  19508. var ssrcs = [];
  19509. // expand sources to ssrcs
  19510. if (typeof sources !== 'undefined' &&
  19511. Object.keys(sources).length !== 0) {
  19512. if (Array.isArray(order)) {
  19513. for (var i = 0; i < order.length; i++) {
  19514. var ssrc = order[i];
  19515. var source = sources[ssrc];
  19516. Object.keys(source).forEach(function (attribute) {
  19517. ssrcs.push({
  19518. id: ssrc,
  19519. attribute: attribute,
  19520. value: source[attribute]
  19521. });
  19522. });
  19523. }
  19524. } else {
  19525. Object.keys(sources).forEach(function (ssrc) {
  19526. var source = sources[ssrc];
  19527. Object.keys(source).forEach(function (attribute) {
  19528. ssrcs.push({
  19529. id: ssrc,
  19530. attribute: attribute,
  19531. value: source[attribute]
  19532. });
  19533. });
  19534. });
  19535. }
  19536. }
  19537. return ssrcs;
  19538. };
  19539. exports.parseSsrcs = function (mLine) {
  19540. var sources = {};
  19541. // group sources attributes by ssrc.
  19542. if (typeof mLine.ssrcs !== 'undefined' && Array.isArray(mLine.ssrcs)) {
  19543. mLine.ssrcs.forEach(function (ssrc) {
  19544. if (!sources[ssrc.id])
  19545. sources[ssrc.id] = {};
  19546. sources[ssrc.id][ssrc.attribute] = ssrc.value;
  19547. });
  19548. }
  19549. return sources;
  19550. };
  19551. },{}],70:[function(require,module,exports){
  19552. var grammar = module.exports = {
  19553. v: [{
  19554. name: 'version',
  19555. reg: /^(\d*)$/
  19556. }],
  19557. o: [{ //o=- 20518 0 IN IP4 203.0.113.1
  19558. // NB: sessionId will be a String in most cases because it is huge
  19559. name: 'origin',
  19560. reg: /^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/,
  19561. names: ['username', 'sessionId', 'sessionVersion', 'netType', 'ipVer', 'address'],
  19562. format: "%s %s %d %s IP%d %s"
  19563. }],
  19564. // default parsing of these only (though some of these feel outdated)
  19565. s: [{ name: 'name' }],
  19566. i: [{ name: 'description' }],
  19567. u: [{ name: 'uri' }],
  19568. e: [{ name: 'email' }],
  19569. p: [{ name: 'phone' }],
  19570. z: [{ name: 'timezones' }], // TODO: this one can actually be parsed properly..
  19571. r: [{ name: 'repeats' }], // TODO: this one can also be parsed properly
  19572. //k: [{}], // outdated thing ignored
  19573. t: [{ //t=0 0
  19574. name: 'timing',
  19575. reg: /^(\d*) (\d*)/,
  19576. names: ['start', 'stop'],
  19577. format: "%d %d"
  19578. }],
  19579. c: [{ //c=IN IP4 10.47.197.26
  19580. name: 'connection',
  19581. reg: /^IN IP(\d) (\S*)/,
  19582. names: ['version', 'ip'],
  19583. format: "IN IP%d %s"
  19584. }],
  19585. b: [{ //b=AS:4000
  19586. push: 'bandwidth',
  19587. reg: /^(TIAS|AS|CT|RR|RS):(\d*)/,
  19588. names: ['type', 'limit'],
  19589. format: "%s:%s"
  19590. }],
  19591. m: [{ //m=video 51744 RTP/AVP 126 97 98 34 31
  19592. // NB: special - pushes to session
  19593. // TODO: rtp/fmtp should be filtered by the payloads found here?
  19594. reg: /^(\w*) (\d*) ([\w\/]*)(?: (.*))?/,
  19595. names: ['type', 'port', 'protocol', 'payloads'],
  19596. format: "%s %d %s %s"
  19597. }],
  19598. a: [
  19599. { //a=rtpmap:110 opus/48000/2
  19600. push: 'rtp',
  19601. reg: /^rtpmap:(\d*) ([\w\-]*)\/(\d*)(?:\s*\/(\S*))?/,
  19602. names: ['payload', 'codec', 'rate', 'encoding'],
  19603. format: function (o) {
  19604. return (o.encoding) ?
  19605. "rtpmap:%d %s/%s/%s":
  19606. "rtpmap:%d %s/%s";
  19607. }
  19608. },
  19609. { //a=fmtp:108 profile-level-id=24;object=23;bitrate=64000
  19610. push: 'fmtp',
  19611. reg: /^fmtp:(\d*) (\S*)/,
  19612. names: ['payload', 'config'],
  19613. format: "fmtp:%d %s"
  19614. },
  19615. { //a=control:streamid=0
  19616. name: 'control',
  19617. reg: /^control:(.*)/,
  19618. format: "control:%s"
  19619. },
  19620. { //a=rtcp:65179 IN IP4 193.84.77.194
  19621. name: 'rtcp',
  19622. reg: /^rtcp:(\d*)(?: (\S*) IP(\d) (\S*))?/,
  19623. names: ['port', 'netType', 'ipVer', 'address'],
  19624. format: function (o) {
  19625. return (o.address != null) ?
  19626. "rtcp:%d %s IP%d %s":
  19627. "rtcp:%d";
  19628. }
  19629. },
  19630. { //a=rtcp-fb:98 trr-int 100
  19631. push: 'rtcpFbTrrInt',
  19632. reg: /^rtcp-fb:(\*|\d*) trr-int (\d*)/,
  19633. names: ['payload', 'value'],
  19634. format: "rtcp-fb:%d trr-int %d"
  19635. },
  19636. { //a=rtcp-fb:98 nack rpsi
  19637. push: 'rtcpFb',
  19638. reg: /^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,
  19639. names: ['payload', 'type', 'subtype'],
  19640. format: function (o) {
  19641. return (o.subtype != null) ?
  19642. "rtcp-fb:%s %s %s":
  19643. "rtcp-fb:%s %s";
  19644. }
  19645. },
  19646. { //a=extmap:2 urn:ietf:params:rtp-hdrext:toffset
  19647. //a=extmap:1/recvonly URI-gps-string
  19648. push: 'ext',
  19649. reg: /^extmap:([\w_\/]*) (\S*)(?: (\S*))?/,
  19650. names: ['value', 'uri', 'config'], // value may include "/direction" suffix
  19651. format: function (o) {
  19652. return (o.config != null) ?
  19653. "extmap:%s %s %s":
  19654. "extmap:%s %s";
  19655. }
  19656. },
  19657. {
  19658. //a=crypto:1 AES_CM_128_HMAC_SHA1_80 inline:PS1uQCVeeCFCanVmcjkpPywjNWhcYD0mXXtxaVBR|2^20|1:32
  19659. push: 'crypto',
  19660. reg: /^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,
  19661. names: ['id', 'suite', 'config', 'sessionConfig'],
  19662. format: function (o) {
  19663. return (o.sessionConfig != null) ?
  19664. "crypto:%d %s %s %s":
  19665. "crypto:%d %s %s";
  19666. }
  19667. },
  19668. { //a=setup:actpass
  19669. name: 'setup',
  19670. reg: /^setup:(\w*)/,
  19671. format: "setup:%s"
  19672. },
  19673. { //a=mid:1
  19674. name: 'mid',
  19675. reg: /^mid:([^\s]*)/,
  19676. format: "mid:%s"
  19677. },
  19678. { //a=msid:0c8b064d-d807-43b4-b434-f92a889d8587 98178685-d409-46e0-8e16-7ef0db0db64a
  19679. name: 'msid',
  19680. reg: /^msid:(.*)/,
  19681. format: "msid:%s"
  19682. },
  19683. { //a=ptime:20
  19684. name: 'ptime',
  19685. reg: /^ptime:(\d*)/,
  19686. format: "ptime:%d"
  19687. },
  19688. { //a=maxptime:60
  19689. name: 'maxptime',
  19690. reg: /^maxptime:(\d*)/,
  19691. format: "maxptime:%d"
  19692. },
  19693. { //a=sendrecv
  19694. name: 'direction',
  19695. reg: /^(sendrecv|recvonly|sendonly|inactive)/
  19696. },
  19697. { //a=ice-lite
  19698. name: 'icelite',
  19699. reg: /^(ice-lite)/
  19700. },
  19701. { //a=ice-ufrag:F7gI
  19702. name: 'iceUfrag',
  19703. reg: /^ice-ufrag:(\S*)/,
  19704. format: "ice-ufrag:%s"
  19705. },
  19706. { //a=ice-pwd:x9cml/YzichV2+XlhiMu8g
  19707. name: 'icePwd',
  19708. reg: /^ice-pwd:(\S*)/,
  19709. format: "ice-pwd:%s"
  19710. },
  19711. { //a=fingerprint:SHA-1 00:11:22:33:44:55:66:77:88:99:AA:BB:CC:DD:EE:FF:00:11:22:33
  19712. name: 'fingerprint',
  19713. reg: /^fingerprint:(\S*) (\S*)/,
  19714. names: ['type', 'hash'],
  19715. format: "fingerprint:%s %s"
  19716. },
  19717. {
  19718. //a=candidate:0 1 UDP 2113667327 203.0.113.1 54400 typ host
  19719. //a=candidate:1162875081 1 udp 2113937151 192.168.34.75 60017 typ host generation 0
  19720. //a=candidate:3289912957 2 udp 1845501695 193.84.77.194 60017 typ srflx raddr 192.168.34.75 rport 60017 generation 0
  19721. push:'candidates',
  19722. reg: /^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: generation (\d*))?/,
  19723. names: ['foundation', 'component', 'transport', 'priority', 'ip', 'port', 'type', 'raddr', 'rport', 'generation'],
  19724. format: function (o) {
  19725. var str = "candidate:%s %d %s %d %s %d typ %s";
  19726. // NB: candidate has two optional chunks, so %void middle one if it's missing
  19727. str += (o.raddr != null) ? " raddr %s rport %d" : "%v%v";
  19728. if (o.generation != null) {
  19729. str += " generation %d";
  19730. }
  19731. return str;
  19732. }
  19733. },
  19734. { //a=end-of-candidates (keep after the candidates line for readability)
  19735. name: 'endOfCandidates',
  19736. reg: /^(end-of-candidates)/
  19737. },
  19738. { //a=remote-candidates:1 203.0.113.1 54400 2 203.0.113.1 54401 ...
  19739. name: 'remoteCandidates',
  19740. reg: /^remote-candidates:(.*)/,
  19741. format: "remote-candidates:%s"
  19742. },
  19743. { //a=ice-options:google-ice
  19744. name: 'iceOptions',
  19745. reg: /^ice-options:(\S*)/,
  19746. format: "ice-options:%s"
  19747. },
  19748. { //a=ssrc:2566107569 cname:t9YU8M1UxTF8Y1A1
  19749. push: "ssrcs",
  19750. reg: /^ssrc:(\d*) ([\w_]*):(.*)/,
  19751. names: ['id', 'attribute', 'value'],
  19752. format: "ssrc:%d %s:%s"
  19753. },
  19754. { //a=ssrc-group:FEC 1 2
  19755. push: "ssrcGroups",
  19756. reg: /^ssrc-group:(\w*) (.*)/,
  19757. names: ['semantics', 'ssrcs'],
  19758. format: "ssrc-group:%s %s"
  19759. },
  19760. { //a=msid-semantic: WMS Jvlam5X3SX1OP6pn20zWogvaKJz5Hjf9OnlV
  19761. name: "msidSemantic",
  19762. reg: /^msid-semantic:\s?(\w*) (\S*)/,
  19763. names: ['semantic', 'token'],
  19764. format: "msid-semantic: %s %s" // space after ":" is not accidental
  19765. },
  19766. { //a=group:BUNDLE audio video
  19767. push: 'groups',
  19768. reg: /^group:(\w*) (.*)/,
  19769. names: ['type', 'mids'],
  19770. format: "group:%s %s"
  19771. },
  19772. { //a=rtcp-mux
  19773. name: 'rtcpMux',
  19774. reg: /^(rtcp-mux)/
  19775. },
  19776. { //a=rtcp-rsize
  19777. name: 'rtcpRsize',
  19778. reg: /^(rtcp-rsize)/
  19779. },
  19780. { // any a= that we don't understand is kepts verbatim on media.invalid
  19781. push: 'invalid',
  19782. names: ["value"]
  19783. }
  19784. ]
  19785. };
  19786. // set sensible defaults to avoid polluting the grammar with boring details
  19787. Object.keys(grammar).forEach(function (key) {
  19788. var objs = grammar[key];
  19789. objs.forEach(function (obj) {
  19790. if (!obj.reg) {
  19791. obj.reg = /(.*)/;
  19792. }
  19793. if (!obj.format) {
  19794. obj.format = "%s";
  19795. }
  19796. });
  19797. });
  19798. },{}],71:[function(require,module,exports){
  19799. var parser = require('./parser');
  19800. var writer = require('./writer');
  19801. exports.write = writer;
  19802. exports.parse = parser.parse;
  19803. exports.parseFmtpConfig = parser.parseFmtpConfig;
  19804. exports.parsePayloads = parser.parsePayloads;
  19805. exports.parseRemoteCandidates = parser.parseRemoteCandidates;
  19806. },{"./parser":72,"./writer":73}],72:[function(require,module,exports){
  19807. var toIntIfInt = function (v) {
  19808. return String(Number(v)) === v ? Number(v) : v;
  19809. };
  19810. var attachProperties = function (match, location, names, rawName) {
  19811. if (rawName && !names) {
  19812. location[rawName] = toIntIfInt(match[1]);
  19813. }
  19814. else {
  19815. for (var i = 0; i < names.length; i += 1) {
  19816. if (match[i+1] != null) {
  19817. location[names[i]] = toIntIfInt(match[i+1]);
  19818. }
  19819. }
  19820. }
  19821. };
  19822. var parseReg = function (obj, location, content) {
  19823. var needsBlank = obj.name && obj.names;
  19824. if (obj.push && !location[obj.push]) {
  19825. location[obj.push] = [];
  19826. }
  19827. else if (needsBlank && !location[obj.name]) {
  19828. location[obj.name] = {};
  19829. }
  19830. var keyLocation = obj.push ?
  19831. {} : // blank object that will be pushed
  19832. needsBlank ? location[obj.name] : location; // otherwise, named location or root
  19833. attachProperties(content.match(obj.reg), keyLocation, obj.names, obj.name);
  19834. if (obj.push) {
  19835. location[obj.push].push(keyLocation);
  19836. }
  19837. };
  19838. var grammar = require('./grammar');
  19839. var validLine = RegExp.prototype.test.bind(/^([a-z])=(.*)/);
  19840. exports.parse = function (sdp) {
  19841. var session = {}
  19842. , media = []
  19843. , location = session; // points at where properties go under (one of the above)
  19844. // parse lines we understand
  19845. sdp.split(/(\r\n|\r|\n)/).filter(validLine).forEach(function (l) {
  19846. var type = l[0];
  19847. var content = l.slice(2);
  19848. if (type === 'm') {
  19849. media.push({rtp: [], fmtp: []});
  19850. location = media[media.length-1]; // point at latest media line
  19851. }
  19852. for (var j = 0; j < (grammar[type] || []).length; j += 1) {
  19853. var obj = grammar[type][j];
  19854. if (obj.reg.test(content)) {
  19855. return parseReg(obj, location, content);
  19856. }
  19857. }
  19858. });
  19859. session.media = media; // link it up
  19860. return session;
  19861. };
  19862. var fmtpReducer = function (acc, expr) {
  19863. var s = expr.split('=');
  19864. if (s.length === 2) {
  19865. acc[s[0]] = toIntIfInt(s[1]);
  19866. }
  19867. return acc;
  19868. };
  19869. exports.parseFmtpConfig = function (str) {
  19870. return str.split(';').reduce(fmtpReducer, {});
  19871. };
  19872. exports.parsePayloads = function (str) {
  19873. return str.split(' ').map(Number);
  19874. };
  19875. exports.parseRemoteCandidates = function (str) {
  19876. var candidates = [];
  19877. var parts = str.split(' ').map(toIntIfInt);
  19878. for (var i = 0; i < parts.length; i += 3) {
  19879. candidates.push({
  19880. component: parts[i],
  19881. ip: parts[i + 1],
  19882. port: parts[i + 2]
  19883. });
  19884. }
  19885. return candidates;
  19886. };
  19887. },{"./grammar":70}],73:[function(require,module,exports){
  19888. var grammar = require('./grammar');
  19889. // customized util.format - discards excess arguments and can void middle ones
  19890. var formatRegExp = /%[sdv%]/g;
  19891. var format = function (formatStr) {
  19892. var i = 1;
  19893. var args = arguments;
  19894. var len = args.length;
  19895. return formatStr.replace(formatRegExp, function (x) {
  19896. if (i >= len) {
  19897. return x; // missing argument
  19898. }
  19899. var arg = args[i];
  19900. i += 1;
  19901. switch (x) {
  19902. case '%%':
  19903. return '%';
  19904. case '%s':
  19905. return String(arg);
  19906. case '%d':
  19907. return Number(arg);
  19908. case '%v':
  19909. return '';
  19910. }
  19911. });
  19912. // NB: we discard excess arguments - they are typically undefined from makeLine
  19913. };
  19914. var makeLine = function (type, obj, location) {
  19915. var str = obj.format instanceof Function ?
  19916. (obj.format(obj.push ? location : location[obj.name])) :
  19917. obj.format;
  19918. var args = [type + '=' + str];
  19919. if (obj.names) {
  19920. for (var i = 0; i < obj.names.length; i += 1) {
  19921. var n = obj.names[i];
  19922. if (obj.name) {
  19923. args.push(location[obj.name][n]);
  19924. }
  19925. else { // for mLine and push attributes
  19926. args.push(location[obj.names[i]]);
  19927. }
  19928. }
  19929. }
  19930. else {
  19931. args.push(location[obj.name]);
  19932. }
  19933. return format.apply(null, args);
  19934. };
  19935. // RFC specified order
  19936. // TODO: extend this with all the rest
  19937. var defaultOuterOrder = [
  19938. 'v', 'o', 's', 'i',
  19939. 'u', 'e', 'p', 'c',
  19940. 'b', 't', 'r', 'z', 'a'
  19941. ];
  19942. var defaultInnerOrder = ['i', 'c', 'b', 'a'];
  19943. module.exports = function (session, opts) {
  19944. opts = opts || {};
  19945. // ensure certain properties exist
  19946. if (session.version == null) {
  19947. session.version = 0; // "v=0" must be there (only defined version atm)
  19948. }
  19949. if (session.name == null) {
  19950. session.name = " "; // "s= " must be there if no meaningful name set
  19951. }
  19952. session.media.forEach(function (mLine) {
  19953. if (mLine.payloads == null) {
  19954. mLine.payloads = "";
  19955. }
  19956. });
  19957. var outerOrder = opts.outerOrder || defaultOuterOrder;
  19958. var innerOrder = opts.innerOrder || defaultInnerOrder;
  19959. var sdp = [];
  19960. // loop through outerOrder for matching properties on session
  19961. outerOrder.forEach(function (type) {
  19962. grammar[type].forEach(function (obj) {
  19963. if (obj.name in session && session[obj.name] != null) {
  19964. sdp.push(makeLine(type, obj, session));
  19965. }
  19966. else if (obj.push in session && session[obj.push] != null) {
  19967. session[obj.push].forEach(function (el) {
  19968. sdp.push(makeLine(type, obj, el));
  19969. });
  19970. }
  19971. });
  19972. });
  19973. // then for each media line, follow the innerOrder
  19974. session.media.forEach(function (mLine) {
  19975. sdp.push(makeLine('m', grammar.m[0], mLine));
  19976. innerOrder.forEach(function (type) {
  19977. grammar[type].forEach(function (obj) {
  19978. if (obj.name in mLine && mLine[obj.name] != null) {
  19979. sdp.push(makeLine(type, obj, mLine));
  19980. }
  19981. else if (obj.push in mLine && mLine[obj.push] != null) {
  19982. mLine[obj.push].forEach(function (el) {
  19983. sdp.push(makeLine(type, obj, el));
  19984. });
  19985. }
  19986. });
  19987. });
  19988. });
  19989. return sdp.join('\r\n') + '\r\n';
  19990. };
  19991. },{"./grammar":70}],74:[function(require,module,exports){
  19992. var grammar = module.exports = {
  19993. v: [{
  19994. name: 'version',
  19995. reg: /^(\d*)$/
  19996. }],
  19997. o: [{ //o=- 20518 0 IN IP4 203.0.113.1
  19998. // NB: sessionId will be a String in most cases because it is huge
  19999. name: 'origin',
  20000. reg: /^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/,
  20001. names: ['username', 'sessionId', 'sessionVersion', 'netType', 'ipVer', 'address'],
  20002. format: "%s %s %d %s IP%d %s"
  20003. }],
  20004. // default parsing of these only (though some of these feel outdated)
  20005. s: [{ name: 'name' }],
  20006. i: [{ name: 'description' }],
  20007. u: [{ name: 'uri' }],
  20008. e: [{ name: 'email' }],
  20009. p: [{ name: 'phone' }],
  20010. z: [{ name: 'timezones' }], // TODO: this one can actually be parsed properly..
  20011. r: [{ name: 'repeats' }], // TODO: this one can also be parsed properly
  20012. //k: [{}], // outdated thing ignored
  20013. t: [{ //t=0 0
  20014. name: 'timing',
  20015. reg: /^(\d*) (\d*)/,
  20016. names: ['start', 'stop'],
  20017. format: "%d %d"
  20018. }],
  20019. c: [{ //c=IN IP4 10.47.197.26
  20020. name: 'connection',
  20021. reg: /^IN IP(\d) (\S*)/,
  20022. names: ['version', 'ip'],
  20023. format: "IN IP%d %s"
  20024. }],
  20025. b: [{ //b=AS:4000
  20026. push: 'bandwidth',
  20027. reg: /^(TIAS|AS|CT|RR|RS):(\d*)/,
  20028. names: ['type', 'limit'],
  20029. format: "%s:%s"
  20030. }],
  20031. m: [{ //m=video 51744 RTP/AVP 126 97 98 34 31
  20032. // NB: special - pushes to session
  20033. // TODO: rtp/fmtp should be filtered by the payloads found here?
  20034. reg: /^(\w*) (\d*) ([\w\/]*)(?: (.*))?/,
  20035. names: ['type', 'port', 'protocol', 'payloads'],
  20036. format: "%s %d %s %s"
  20037. }],
  20038. a: [
  20039. { //a=rtpmap:110 opus/48000/2
  20040. push: 'rtp',
  20041. reg: /^rtpmap:(\d*) ([\w\-]*)\/(\d*)(?:\s*\/(\S*))?/,
  20042. names: ['payload', 'codec', 'rate', 'encoding'],
  20043. format: function (o) {
  20044. return (o.encoding) ?
  20045. "rtpmap:%d %s/%s/%s":
  20046. "rtpmap:%d %s/%s";
  20047. }
  20048. },
  20049. {
  20050. //a=fmtp:108 profile-level-id=24;object=23;bitrate=64000
  20051. //a=fmtp:111 minptime=10; useinbandfec=1
  20052. push: 'fmtp',
  20053. reg: /^fmtp:(\d*) ([\S| ]*)/,
  20054. names: ['payload', 'config'],
  20055. format: "fmtp:%d %s"
  20056. },
  20057. { //a=control:streamid=0
  20058. name: 'control',
  20059. reg: /^control:(.*)/,
  20060. format: "control:%s"
  20061. },
  20062. { //a=rtcp:65179 IN IP4 193.84.77.194
  20063. name: 'rtcp',
  20064. reg: /^rtcp:(\d*)(?: (\S*) IP(\d) (\S*))?/,
  20065. names: ['port', 'netType', 'ipVer', 'address'],
  20066. format: function (o) {
  20067. return (o.address != null) ?
  20068. "rtcp:%d %s IP%d %s":
  20069. "rtcp:%d";
  20070. }
  20071. },
  20072. { //a=rtcp-fb:98 trr-int 100
  20073. push: 'rtcpFbTrrInt',
  20074. reg: /^rtcp-fb:(\*|\d*) trr-int (\d*)/,
  20075. names: ['payload', 'value'],
  20076. format: "rtcp-fb:%d trr-int %d"
  20077. },
  20078. { //a=rtcp-fb:98 nack rpsi
  20079. push: 'rtcpFb',
  20080. reg: /^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,
  20081. names: ['payload', 'type', 'subtype'],
  20082. format: function (o) {
  20083. return (o.subtype != null) ?
  20084. "rtcp-fb:%s %s %s":
  20085. "rtcp-fb:%s %s";
  20086. }
  20087. },
  20088. { //a=extmap:2 urn:ietf:params:rtp-hdrext:toffset
  20089. //a=extmap:1/recvonly URI-gps-string
  20090. push: 'ext',
  20091. reg: /^extmap:([\w_\/]*) (\S*)(?: (\S*))?/,
  20092. names: ['value', 'uri', 'config'], // value may include "/direction" suffix
  20093. format: function (o) {
  20094. return (o.config != null) ?
  20095. "extmap:%s %s %s":
  20096. "extmap:%s %s";
  20097. }
  20098. },
  20099. {
  20100. //a=crypto:1 AES_CM_128_HMAC_SHA1_80 inline:PS1uQCVeeCFCanVmcjkpPywjNWhcYD0mXXtxaVBR|2^20|1:32
  20101. push: 'crypto',
  20102. reg: /^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,
  20103. names: ['id', 'suite', 'config', 'sessionConfig'],
  20104. format: function (o) {
  20105. return (o.sessionConfig != null) ?
  20106. "crypto:%d %s %s %s":
  20107. "crypto:%d %s %s";
  20108. }
  20109. },
  20110. { //a=setup:actpass
  20111. name: 'setup',
  20112. reg: /^setup:(\w*)/,
  20113. format: "setup:%s"
  20114. },
  20115. { //a=mid:1
  20116. name: 'mid',
  20117. reg: /^mid:([^\s]*)/,
  20118. format: "mid:%s"
  20119. },
  20120. { //a=msid:0c8b064d-d807-43b4-b434-f92a889d8587 98178685-d409-46e0-8e16-7ef0db0db64a
  20121. name: 'msid',
  20122. reg: /^msid:(.*)/,
  20123. format: "msid:%s"
  20124. },
  20125. { //a=ptime:20
  20126. name: 'ptime',
  20127. reg: /^ptime:(\d*)/,
  20128. format: "ptime:%d"
  20129. },
  20130. { //a=maxptime:60
  20131. name: 'maxptime',
  20132. reg: /^maxptime:(\d*)/,
  20133. format: "maxptime:%d"
  20134. },
  20135. { //a=sendrecv
  20136. name: 'direction',
  20137. reg: /^(sendrecv|recvonly|sendonly|inactive)/
  20138. },
  20139. { //a=ice-lite
  20140. name: 'icelite',
  20141. reg: /^(ice-lite)/
  20142. },
  20143. { //a=ice-ufrag:F7gI
  20144. name: 'iceUfrag',
  20145. reg: /^ice-ufrag:(\S*)/,
  20146. format: "ice-ufrag:%s"
  20147. },
  20148. { //a=ice-pwd:x9cml/YzichV2+XlhiMu8g
  20149. name: 'icePwd',
  20150. reg: /^ice-pwd:(\S*)/,
  20151. format: "ice-pwd:%s"
  20152. },
  20153. { //a=fingerprint:SHA-1 00:11:22:33:44:55:66:77:88:99:AA:BB:CC:DD:EE:FF:00:11:22:33
  20154. name: 'fingerprint',
  20155. reg: /^fingerprint:(\S*) (\S*)/,
  20156. names: ['type', 'hash'],
  20157. format: "fingerprint:%s %s"
  20158. },
  20159. {
  20160. //a=candidate:0 1 UDP 2113667327 203.0.113.1 54400 typ host
  20161. //a=candidate:1162875081 1 udp 2113937151 192.168.34.75 60017 typ host generation 0
  20162. //a=candidate:3289912957 2 udp 1845501695 193.84.77.194 60017 typ srflx raddr 192.168.34.75 rport 60017 generation 0
  20163. push:'candidates',
  20164. reg: /^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: generation (\d*))?/,
  20165. names: ['foundation', 'component', 'transport', 'priority', 'ip', 'port', 'type', 'raddr', 'rport', 'generation'],
  20166. format: function (o) {
  20167. var str = "candidate:%s %d %s %d %s %d typ %s";
  20168. // NB: candidate has two optional chunks, so %void middle one if it's missing
  20169. str += (o.raddr != null) ? " raddr %s rport %d" : "%v%v";
  20170. if (o.generation != null) {
  20171. str += " generation %d";
  20172. }
  20173. return str;
  20174. }
  20175. },
  20176. { //a=end-of-candidates (keep after the candidates line for readability)
  20177. name: 'endOfCandidates',
  20178. reg: /^(end-of-candidates)/
  20179. },
  20180. { //a=remote-candidates:1 203.0.113.1 54400 2 203.0.113.1 54401 ...
  20181. name: 'remoteCandidates',
  20182. reg: /^remote-candidates:(.*)/,
  20183. format: "remote-candidates:%s"
  20184. },
  20185. { //a=ice-options:google-ice
  20186. name: 'iceOptions',
  20187. reg: /^ice-options:(\S*)/,
  20188. format: "ice-options:%s"
  20189. },
  20190. { //a=ssrc:2566107569 cname:t9YU8M1UxTF8Y1A1
  20191. push: "ssrcs",
  20192. reg: /^ssrc:(\d*) ([\w_]*):(.*)/,
  20193. names: ['id', 'attribute', 'value'],
  20194. format: "ssrc:%d %s:%s"
  20195. },
  20196. { //a=ssrc-group:FEC 1 2
  20197. push: "ssrcGroups",
  20198. reg: /^ssrc-group:(\w*) (.*)/,
  20199. names: ['semantics', 'ssrcs'],
  20200. format: "ssrc-group:%s %s"
  20201. },
  20202. { //a=msid-semantic: WMS Jvlam5X3SX1OP6pn20zWogvaKJz5Hjf9OnlV
  20203. name: "msidSemantic",
  20204. reg: /^msid-semantic:\s?(\w*) (\S*)/,
  20205. names: ['semantic', 'token'],
  20206. format: "msid-semantic: %s %s" // space after ":" is not accidental
  20207. },
  20208. { //a=group:BUNDLE audio video
  20209. push: 'groups',
  20210. reg: /^group:(\w*) (.*)/,
  20211. names: ['type', 'mids'],
  20212. format: "group:%s %s"
  20213. },
  20214. { //a=rtcp-mux
  20215. name: 'rtcpMux',
  20216. reg: /^(rtcp-mux)/
  20217. },
  20218. { //a=rtcp-rsize
  20219. name: 'rtcpRsize',
  20220. reg: /^(rtcp-rsize)/
  20221. },
  20222. { // any a= that we don't understand is kepts verbatim on media.invalid
  20223. push: 'invalid',
  20224. names: ["value"]
  20225. }
  20226. ]
  20227. };
  20228. // set sensible defaults to avoid polluting the grammar with boring details
  20229. Object.keys(grammar).forEach(function (key) {
  20230. var objs = grammar[key];
  20231. objs.forEach(function (obj) {
  20232. if (!obj.reg) {
  20233. obj.reg = /(.*)/;
  20234. }
  20235. if (!obj.format) {
  20236. obj.format = "%s";
  20237. }
  20238. });
  20239. });
  20240. },{}],75:[function(require,module,exports){
  20241. arguments[4][71][0].apply(exports,arguments)
  20242. },{"./parser":76,"./writer":77,"dup":71}],76:[function(require,module,exports){
  20243. var toIntIfInt = function (v) {
  20244. return String(Number(v)) === v ? Number(v) : v;
  20245. };
  20246. var attachProperties = function (match, location, names, rawName) {
  20247. if (rawName && !names) {
  20248. location[rawName] = toIntIfInt(match[1]);
  20249. }
  20250. else {
  20251. for (var i = 0; i < names.length; i += 1) {
  20252. if (match[i+1] != null) {
  20253. location[names[i]] = toIntIfInt(match[i+1]);
  20254. }
  20255. }
  20256. }
  20257. };
  20258. var parseReg = function (obj, location, content) {
  20259. var needsBlank = obj.name && obj.names;
  20260. if (obj.push && !location[obj.push]) {
  20261. location[obj.push] = [];
  20262. }
  20263. else if (needsBlank && !location[obj.name]) {
  20264. location[obj.name] = {};
  20265. }
  20266. var keyLocation = obj.push ?
  20267. {} : // blank object that will be pushed
  20268. needsBlank ? location[obj.name] : location; // otherwise, named location or root
  20269. attachProperties(content.match(obj.reg), keyLocation, obj.names, obj.name);
  20270. if (obj.push) {
  20271. location[obj.push].push(keyLocation);
  20272. }
  20273. };
  20274. var grammar = require('./grammar');
  20275. var validLine = RegExp.prototype.test.bind(/^([a-z])=(.*)/);
  20276. exports.parse = function (sdp) {
  20277. var session = {}
  20278. , media = []
  20279. , location = session; // points at where properties go under (one of the above)
  20280. // parse lines we understand
  20281. sdp.split(/(\r\n|\r|\n)/).filter(validLine).forEach(function (l) {
  20282. var type = l[0];
  20283. var content = l.slice(2);
  20284. if (type === 'm') {
  20285. media.push({rtp: [], fmtp: []});
  20286. location = media[media.length-1]; // point at latest media line
  20287. }
  20288. for (var j = 0; j < (grammar[type] || []).length; j += 1) {
  20289. var obj = grammar[type][j];
  20290. if (obj.reg.test(content)) {
  20291. return parseReg(obj, location, content);
  20292. }
  20293. }
  20294. });
  20295. session.media = media; // link it up
  20296. return session;
  20297. };
  20298. var fmtpReducer = function (acc, expr) {
  20299. var s = expr.split('=');
  20300. if (s.length === 2) {
  20301. acc[s[0]] = toIntIfInt(s[1]);
  20302. }
  20303. return acc;
  20304. };
  20305. exports.parseFmtpConfig = function (str) {
  20306. return str.split(/\;\s?/).reduce(fmtpReducer, {});
  20307. };
  20308. exports.parsePayloads = function (str) {
  20309. return str.split(' ').map(Number);
  20310. };
  20311. exports.parseRemoteCandidates = function (str) {
  20312. var candidates = [];
  20313. var parts = str.split(' ').map(toIntIfInt);
  20314. for (var i = 0; i < parts.length; i += 3) {
  20315. candidates.push({
  20316. component: parts[i],
  20317. ip: parts[i + 1],
  20318. port: parts[i + 2]
  20319. });
  20320. }
  20321. return candidates;
  20322. };
  20323. },{"./grammar":74}],77:[function(require,module,exports){
  20324. arguments[4][73][0].apply(exports,arguments)
  20325. },{"./grammar":74,"dup":73}],78:[function(require,module,exports){
  20326. var MediaStreamType = {
  20327. VIDEO_TYPE: "Video",
  20328. AUDIO_TYPE: "Audio"
  20329. };
  20330. module.exports = MediaStreamType;
  20331. },{}],79:[function(require,module,exports){
  20332. var RTCEvents = {
  20333. RTC_READY: "rtc.ready",
  20334. DATA_CHANNEL_OPEN: "rtc.data_channel_open",
  20335. LASTN_CHANGED: "rtc.lastn_changed",
  20336. DOMINANTSPEAKER_CHANGED: "rtc.dominantspeaker_changed",
  20337. LASTN_ENDPOINT_CHANGED: "rtc.lastn_endpoint_changed",
  20338. AVAILABLE_DEVICES_CHANGED: "rtc.available_devices_changed"
  20339. };
  20340. module.exports = RTCEvents;
  20341. },{}],80:[function(require,module,exports){
  20342. var Resolutions = {
  20343. "1080": {
  20344. width: 1920,
  20345. height: 1080,
  20346. order: 7
  20347. },
  20348. "fullhd": {
  20349. width: 1920,
  20350. height: 1080,
  20351. order: 7
  20352. },
  20353. "720": {
  20354. width: 1280,
  20355. height: 720,
  20356. order: 6
  20357. },
  20358. "hd": {
  20359. width: 1280,
  20360. height: 720,
  20361. order: 6
  20362. },
  20363. "960": {
  20364. width: 960,
  20365. height: 720,
  20366. order: 5
  20367. },
  20368. "640": {
  20369. width: 640,
  20370. height: 480,
  20371. order: 4
  20372. },
  20373. "vga": {
  20374. width: 640,
  20375. height: 480,
  20376. order: 4
  20377. },
  20378. "360": {
  20379. width: 640,
  20380. height: 360,
  20381. order: 3
  20382. },
  20383. "320": {
  20384. width: 320,
  20385. height: 240,
  20386. order: 2
  20387. },
  20388. "180": {
  20389. width: 320,
  20390. height: 180,
  20391. order: 1
  20392. }
  20393. };
  20394. module.exports = Resolutions;
  20395. },{}],81:[function(require,module,exports){
  20396. var AuthenticationEvents = {
  20397. /**
  20398. * Event callback arguments:
  20399. * function(authenticationEnabled, userIdentity)
  20400. * authenticationEnabled - indicates whether authentication has been enabled
  20401. * in this session
  20402. * userIdentity - if user has been logged in then it contains user name. If
  20403. * contains 'null' or 'undefined' then user is not logged in.
  20404. */
  20405. IDENTITY_UPDATED: "authentication.identity_updated"
  20406. };
  20407. module.exports = AuthenticationEvents;
  20408. },{}],82:[function(require,module,exports){
  20409. var DesktopSharingEventTypes = {
  20410. INIT: "ds.init",
  20411. SWITCHING_DONE: "ds.switching_done",
  20412. NEW_STREAM_CREATED: "ds.new_stream_created",
  20413. /**
  20414. * An event which indicates that the jidesha extension for Firefox is
  20415. * needed to proceed with screen sharing, and that it is not installed.
  20416. */
  20417. FIREFOX_EXTENSION_NEEDED: "ds.firefox_extension_needed"
  20418. };
  20419. module.exports = DesktopSharingEventTypes;
  20420. },{}],83:[function(require,module,exports){
  20421. module.exports = {
  20422. /**
  20423. * An event carrying connection statistics.
  20424. */
  20425. CONNECTION_STATS: "statistics.connectionstats",
  20426. /**
  20427. * FIXME: needs documentation.
  20428. */
  20429. AUDIO_LEVEL: "statistics.audioLevel",
  20430. /**
  20431. * FIXME: needs documentation.
  20432. */
  20433. STOP: "statistics.stop"
  20434. };
  20435. },{}],84:[function(require,module,exports){
  20436. var Constants = {
  20437. LOCAL_JID: 'local'
  20438. };
  20439. module.exports = Constants;
  20440. },{}],85:[function(require,module,exports){
  20441. var XMPPEvents = {
  20442. // Designates an event indicating that the connection to the XMPP server
  20443. // failed.
  20444. CONNECTION_FAILED: "xmpp.connection.failed",
  20445. // Designates an event indicating that the media (ICE) connection was
  20446. // interrupted. This should go to the RTC module.
  20447. CONNECTION_INTERRUPTED: "xmpp.connection.interrupted",
  20448. // Designates an event indicating that the media (ICE) connection was
  20449. // restored. This should go to the RTC module.
  20450. CONNECTION_RESTORED: "xmpp.connection.restored",
  20451. // Designates an event indicating that an offer (e.g. Jingle
  20452. // session-initiate) was received.
  20453. CALL_INCOMING: "xmpp.callincoming.jingle",
  20454. // Designates an event indicating that we were kicked from the XMPP MUC.
  20455. KICKED: "xmpp.kicked",
  20456. // Designates an event indicating that the userID for a specific JID has
  20457. // changed.
  20458. // Note: currently this event fires every time we receive presence from
  20459. // someone (regardless of whether or not the "userID" changed).
  20460. USER_ID_CHANGED: "xmpp.user_id_changed",
  20461. // Designates an event indicating that we have joined the XMPP MUC.
  20462. MUC_JOINED: "xmpp.muc_joined",
  20463. // Designates an event indicating that a participant joined the XMPP MUC.
  20464. MUC_MEMBER_JOINED: "xmpp.muc_member_joined",
  20465. // Designates an event indicating that a participant left the XMPP MUC.
  20466. MUC_MEMBER_LEFT: "xmpp.muc_member_left",
  20467. // Designates an event indicating that the MUC role of a participant has
  20468. // changed.
  20469. MUC_ROLE_CHANGED: "xmpp.muc_role_changed",
  20470. // Designates an event indicating that the XMPP MUC was destroyed.
  20471. MUC_DESTROYED: "xmpp.muc_destroyed",
  20472. // Designates an event indicating that the display name of a participant
  20473. // has changed.
  20474. DISPLAY_NAME_CHANGED: "xmpp.display_name_changed",
  20475. // Designates an event indicating that we received statistics from a
  20476. // participant in the MUC.
  20477. REMOTE_STATS: "xmpp.remote_stats",
  20478. // Designates an event indicating that our role in the XMPP MUC has changed.
  20479. LOCAL_ROLE_CHANGED: "xmpp.localrole_changed",
  20480. // Designates an event indicating that the subject of the XMPP MUC has
  20481. // changed.
  20482. SUBJECT_CHANGED: "xmpp.subject_changed",
  20483. // Designates an event indicating that an XMPP message in the MUC was
  20484. // received.
  20485. MESSAGE_RECEIVED: "xmpp.message_received",
  20486. // Designates an event indicating that we sent an XMPP message to the MUC.
  20487. SENDING_CHAT_MESSAGE: "xmpp.sending_chat_message",
  20488. // Designates an event indicating that the video type (e.g. 'camera' or
  20489. // 'screen') for a participant has changed.
  20490. // Note: currently this event fires every time we receive presence from
  20491. // someone (regardless of whether or not the "video type" changed).
  20492. PARTICIPANT_VIDEO_TYPE_CHANGED: "xmpp.video_type",
  20493. // Designates an event indicating that a participant in the XMPP MUC has
  20494. // advertised that they have audio muted (or unmuted).
  20495. PARTICIPANT_AUDIO_MUTED: "xmpp.audio_muted",
  20496. // Designates an event indicating that a participant in the XMPP MUC has
  20497. // advertised that they have video muted (or unmuted).
  20498. PARTICIPANT_VIDEO_MUTED: "xmpp.video_muted",
  20499. // Designates an event indicating that the focus has asked us to mute our
  20500. // audio.
  20501. AUDIO_MUTED_BY_FOCUS: "xmpp.audio_muted_by_focus",
  20502. // Designates an event indicating that a moderator in the room changed the
  20503. // "start muted" settings for the conference.
  20504. START_MUTED_SETTING_CHANGED: "xmpp.start_muted_setting_changed",
  20505. // Designates an event indicating that we should join the conference with
  20506. // audio and/or video muted.
  20507. START_MUTED_FROM_FOCUS: "xmpp.start_muted_from_focus",
  20508. // Designates an event indicating that a remote participant's available
  20509. // devices (whether he supports a audio and/or video) changed.
  20510. // Note: currently this event fires every time we receive presence from
  20511. // someone (regardless of whether or not the devices changed).
  20512. DEVICE_AVAILABLE: "xmpp.device_available",
  20513. PEERCONNECTION_READY: "xmpp.peerconnection_ready",
  20514. CONFERENCE_SETUP_FAILED: "xmpp.conference_setup_failed",
  20515. PASSWORD_REQUIRED: "xmpp.password_required",
  20516. AUTHENTICATION_REQUIRED: "xmpp.authentication_required",
  20517. CHAT_ERROR_RECEIVED: "xmpp.chat_error_received",
  20518. ETHERPAD: "xmpp.etherpad",
  20519. BRIDGE_DOWN: "xmpp.bridge_down",
  20520. PRESENCE_STATUS: "xmpp.presence_status",
  20521. RESERVATION_ERROR: "xmpp.room_reservation_error",
  20522. DISPOSE_CONFERENCE: "xmpp.dispose_conference",
  20523. GRACEFUL_SHUTDOWN: "xmpp.graceful_shutdown",
  20524. // TODO: only used in a hack, should probably be removed.
  20525. SET_LOCAL_DESCRIPTION_ERROR: 'xmpp.set_local_description_error',
  20526. // TODO: only used in a hack, should probably be removed.
  20527. SET_REMOTE_DESCRIPTION_ERROR: 'xmpp.set_remote_description_error',
  20528. // TODO: only used in a hack, should probably be removed.
  20529. CREATE_ANSWER_ERROR: 'xmpp.create_answer_error',
  20530. JINGLE_FATAL_ERROR: 'xmpp.jingle_fatal_error',
  20531. PROMPT_FOR_LOGIN: 'xmpp.prompt_for_login',
  20532. FOCUS_DISCONNECTED: 'xmpp.focus_disconnected',
  20533. ROOM_JOIN_ERROR: 'xmpp.room_join_error',
  20534. ROOM_CONNECT_ERROR: 'xmpp.room_connect_error',
  20535. // xmpp is connected and obtained user media
  20536. READY_TO_JOIN: 'xmpp.ready_to_join',
  20537. FOCUS_LEFT: "xmpp.focus_left",
  20538. REMOTE_STREAM_RECEIVED: "xmpp.remote_stream_received"
  20539. };
  20540. module.exports = XMPPEvents;
  20541. },{}]},{},[7])(7)
  20542. });