您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

app.bundle.js 944KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862
  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.APP = 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. /* jshint -W117 */
  3. /* application specific logic */
  4. var APP =
  5. {
  6. init: function () {
  7. this.UI = require("./modules/UI/UI");
  8. this.API = require("./modules/API/API");
  9. this.connectionquality = require("./modules/connectionquality/connectionquality");
  10. this.statistics = require("./modules/statistics/statistics");
  11. this.RTC = require("./modules/RTC/RTC");
  12. this.simulcast = require("./modules/simulcast/simulcast");
  13. this.desktopsharing = require("./modules/desktopsharing/desktopsharing");
  14. this.xmpp = require("./modules/xmpp/xmpp");
  15. this.keyboardshortcut = require("./modules/keyboardshortcut/keyboardshortcut");
  16. this.translation = require("./modules/translation/translation");
  17. this.settings = require("./modules/settings/Settings");
  18. this.DTMF = require("./modules/DTMF/DTMF");
  19. this.members = require("./modules/members/MemberList");
  20. }
  21. };
  22. function init() {
  23. APP.RTC.start();
  24. APP.xmpp.start();
  25. APP.statistics.start();
  26. APP.connectionquality.init();
  27. // Set default desktop sharing method
  28. APP.desktopsharing.init();
  29. APP.keyboardshortcut.init();
  30. APP.members.start();
  31. }
  32. $(document).ready(function () {
  33. APP.init();
  34. APP.translation.init();
  35. if(APP.API.isEnabled())
  36. APP.API.init();
  37. APP.UI.start(init);
  38. });
  39. $(window).bind('beforeunload', function () {
  40. if(APP.API.isEnabled())
  41. APP.API.dispose();
  42. });
  43. module.exports = APP;
  44. },{"./modules/API/API":2,"./modules/DTMF/DTMF":3,"./modules/RTC/RTC":7,"./modules/UI/UI":9,"./modules/connectionquality/connectionquality":36,"./modules/desktopsharing/desktopsharing":37,"./modules/keyboardshortcut/keyboardshortcut":38,"./modules/members/MemberList":39,"./modules/settings/Settings":40,"./modules/simulcast/simulcast":45,"./modules/statistics/statistics":48,"./modules/translation/translation":49,"./modules/xmpp/xmpp":63}],2:[function(require,module,exports){
  45. /**
  46. * Implements API class that communicates with external api class
  47. * and provides interface to access Jitsi Meet features by external
  48. * applications that embed Jitsi Meet
  49. */
  50. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  51. /**
  52. * List of the available commands.
  53. * @type {{
  54. * displayName: inputDisplayNameHandler,
  55. * muteAudio: toggleAudio,
  56. * muteVideo: toggleVideo,
  57. * filmStrip: toggleFilmStrip
  58. * }}
  59. */
  60. var commands =
  61. {
  62. displayName: APP.UI.inputDisplayNameHandler,
  63. muteAudio: APP.UI.toggleAudio,
  64. muteVideo: APP.UI.toggleVideo,
  65. toggleFilmStrip: APP.UI.toggleFilmStrip,
  66. toggleChat: APP.UI.toggleChat,
  67. toggleContactList: APP.UI.toggleContactList
  68. };
  69. /**
  70. * Maps the supported events and their status
  71. * (true it the event is enabled and false if it is disabled)
  72. * @type {{
  73. * incomingMessage: boolean,
  74. * outgoingMessage: boolean,
  75. * displayNameChange: boolean,
  76. * participantJoined: boolean,
  77. * participantLeft: boolean
  78. * }}
  79. */
  80. var events =
  81. {
  82. incomingMessage: false,
  83. outgoingMessage:false,
  84. displayNameChange: false,
  85. participantJoined: false,
  86. participantLeft: false
  87. };
  88. var displayName = {};
  89. /**
  90. * Processes commands from external applicaiton.
  91. * @param message the object with the command
  92. */
  93. function processCommand(message)
  94. {
  95. if(message.action != "execute")
  96. {
  97. console.error("Unknown action of the message");
  98. return;
  99. }
  100. for(var key in message)
  101. {
  102. if(commands[key])
  103. commands[key].apply(null, message[key]);
  104. }
  105. }
  106. /**
  107. * Processes events objects from external applications
  108. * @param event the event
  109. */
  110. function processEvent(event) {
  111. if(!event.action)
  112. {
  113. console.error("Event with no action is received.");
  114. return;
  115. }
  116. var i = 0;
  117. switch(event.action)
  118. {
  119. case "add":
  120. for(; i < event.events.length; i++)
  121. {
  122. events[event.events[i]] = true;
  123. }
  124. break;
  125. case "remove":
  126. for(; i < event.events.length; i++)
  127. {
  128. events[event.events[i]] = false;
  129. }
  130. break;
  131. default:
  132. console.error("Unknown action for event.");
  133. }
  134. }
  135. /**
  136. * Sends message to the external application.
  137. * @param object
  138. */
  139. function sendMessage(object) {
  140. window.parent.postMessage(JSON.stringify(object), "*");
  141. }
  142. /**
  143. * Processes a message event from the external application
  144. * @param event the message event
  145. */
  146. function processMessage(event)
  147. {
  148. var message;
  149. try {
  150. message = JSON.parse(event.data);
  151. } catch (e) {}
  152. if(!message.type)
  153. return;
  154. switch (message.type)
  155. {
  156. case "command":
  157. processCommand(message);
  158. break;
  159. case "event":
  160. processEvent(message);
  161. break;
  162. default:
  163. console.error("Unknown type of the message");
  164. return;
  165. }
  166. }
  167. function setupListeners() {
  168. APP.xmpp.addListener(XMPPEvents.MUC_MEMBER_JOINED, function (from) {
  169. API.triggerEvent("participantJoined", {jid: from});
  170. });
  171. APP.xmpp.addListener(XMPPEvents.MESSAGE_RECEIVED, function (from, nick, txt, myjid) {
  172. if (from != myjid)
  173. API.triggerEvent("incomingMessage",
  174. {"from": from, "nick": nick, "message": txt});
  175. });
  176. APP.xmpp.addListener(XMPPEvents.MUC_MEMBER_LEFT, function (jid) {
  177. API.triggerEvent("participantLeft", {jid: jid});
  178. });
  179. APP.xmpp.addListener(XMPPEvents.DISPLAY_NAME_CHANGED, function (jid, newDisplayName) {
  180. name = displayName[jid];
  181. if(!name || name != newDisplayName) {
  182. API.triggerEvent("displayNameChange", {jid: jid, displayname: newDisplayName});
  183. displayName[jid] = newDisplayName;
  184. }
  185. });
  186. APP.xmpp.addListener(XMPPEvents.SENDING_CHAT_MESSAGE, function (body) {
  187. APP.API.triggerEvent("outgoingMessage", {"message": body});
  188. });
  189. }
  190. var API = {
  191. /**
  192. * Check whether the API should be enabled or not.
  193. * @returns {boolean}
  194. */
  195. isEnabled: function () {
  196. var hash = location.hash;
  197. if(hash && hash.indexOf("external") > -1 && window.postMessage)
  198. return true;
  199. return false;
  200. },
  201. /**
  202. * Initializes the APIConnector. Setups message event listeners that will
  203. * receive information from external applications that embed Jitsi Meet.
  204. * It also sends a message to the external application that APIConnector
  205. * is initialized.
  206. */
  207. init: function () {
  208. if (window.addEventListener)
  209. {
  210. window.addEventListener('message',
  211. processMessage, false);
  212. }
  213. else
  214. {
  215. window.attachEvent('onmessage', processMessage);
  216. }
  217. sendMessage({type: "system", loaded: true});
  218. setupListeners();
  219. },
  220. /**
  221. * Checks whether the event is enabled ot not.
  222. * @param name the name of the event.
  223. * @returns {*}
  224. */
  225. isEventEnabled: function (name) {
  226. return events[name];
  227. },
  228. /**
  229. * Sends event object to the external application that has been subscribed
  230. * for that event.
  231. * @param name the name event
  232. * @param object data associated with the event
  233. */
  234. triggerEvent: function (name, object) {
  235. if(this.isEnabled() && this.isEventEnabled(name))
  236. sendMessage({
  237. type: "event", action: "result", event: name, result: object});
  238. },
  239. /**
  240. * Removes the listeners.
  241. */
  242. dispose: function () {
  243. if(window.removeEventListener)
  244. {
  245. window.removeEventListener("message",
  246. processMessage, false);
  247. }
  248. else
  249. {
  250. window.detachEvent('onmessage', processMessage);
  251. }
  252. }
  253. };
  254. module.exports = API;
  255. },{"../../service/xmpp/XMPPEvents":101}],3:[function(require,module,exports){
  256. /* global APP */
  257. /**
  258. * A module for sending DTMF tones.
  259. */
  260. var DTMFSender;
  261. var initDtmfSender = function() {
  262. // TODO: This needs to reset this if the peerconnection changes
  263. // (e.g. the call is re-made)
  264. if (DTMFSender)
  265. return;
  266. var localAudio = APP.RTC.localAudio;
  267. if (localAudio && localAudio.getTracks().length > 0)
  268. {
  269. var peerconnection
  270. = APP.xmpp.getConnection().jingle.activecall.peerconnection;
  271. if (peerconnection) {
  272. DTMFSender =
  273. peerconnection.peerconnection
  274. .createDTMFSender(localAudio.getTracks()[0]);
  275. console.log("Initialized DTMFSender");
  276. }
  277. else {
  278. console.log("Failed to initialize DTMFSender: no PeerConnection.");
  279. }
  280. }
  281. else {
  282. console.log("Failed to initialize DTMFSender: no audio track.");
  283. }
  284. };
  285. var DTMF = {
  286. sendTones: function (tones, duration, pause) {
  287. if (!DTMFSender)
  288. initDtmfSender();
  289. if (DTMFSender){
  290. DTMFSender.insertDTMF(tones,
  291. (duration || 200),
  292. (pause || 200));
  293. }
  294. }
  295. };
  296. module.exports = DTMF;
  297. },{}],4:[function(require,module,exports){
  298. /* global Strophe, focusedVideoSrc*/
  299. // cache datachannels to avoid garbage collection
  300. // https://code.google.com/p/chromium/issues/detail?id=405545
  301. var RTCEvents = require("../../service/RTC/RTCEvents");
  302. var _dataChannels = [];
  303. var eventEmitter = null;
  304. var DataChannels =
  305. {
  306. /**
  307. * Callback triggered by PeerConnection when new data channel is opened
  308. * on the bridge.
  309. * @param event the event info object.
  310. */
  311. onDataChannel: function (event)
  312. {
  313. var dataChannel = event.channel;
  314. dataChannel.onopen = function () {
  315. console.info("Data channel opened by the Videobridge!", dataChannel);
  316. // Code sample for sending string and/or binary data
  317. // Sends String message to the bridge
  318. //dataChannel.send("Hello bridge!");
  319. // Sends 12 bytes binary message to the bridge
  320. //dataChannel.send(new ArrayBuffer(12));
  321. // when the data channel becomes available, tell the bridge about video
  322. // selections so that it can do adaptive simulcast,
  323. // we want the notification to trigger even if userJid is undefined,
  324. // or null.
  325. var userJid = APP.UI.getLargeVideoState().userResourceJid;
  326. // we want the notification to trigger even if userJid is undefined,
  327. // or null.
  328. onSelectedEndpointChanged(userJid);
  329. };
  330. dataChannel.onerror = function (error) {
  331. console.error("Data Channel Error:", error, dataChannel);
  332. };
  333. dataChannel.onmessage = function (event) {
  334. var data = event.data;
  335. // JSON
  336. var obj;
  337. try {
  338. obj = JSON.parse(data);
  339. }
  340. catch (e) {
  341. console.error(
  342. "Failed to parse data channel message as JSON: ",
  343. data,
  344. dataChannel);
  345. }
  346. if (('undefined' !== typeof(obj)) && (null !== obj)) {
  347. var colibriClass = obj.colibriClass;
  348. if ("DominantSpeakerEndpointChangeEvent" === colibriClass) {
  349. // Endpoint ID from the Videobridge.
  350. var dominantSpeakerEndpoint = obj.dominantSpeakerEndpoint;
  351. console.info(
  352. "Data channel new dominant speaker event: ",
  353. dominantSpeakerEndpoint);
  354. eventEmitter.emit(RTCEvents.DOMINANTSPEAKER_CHANGED, dominantSpeakerEndpoint);
  355. }
  356. else if ("InLastNChangeEvent" === colibriClass)
  357. {
  358. var oldValue = obj.oldValue;
  359. var newValue = obj.newValue;
  360. // Make sure that oldValue and newValue are of type boolean.
  361. var type;
  362. if ((type = typeof oldValue) !== 'boolean') {
  363. if (type === 'string') {
  364. oldValue = (oldValue == "true");
  365. } else {
  366. oldValue = new Boolean(oldValue).valueOf();
  367. }
  368. }
  369. if ((type = typeof newValue) !== 'boolean') {
  370. if (type === 'string') {
  371. newValue = (newValue == "true");
  372. } else {
  373. newValue = new Boolean(newValue).valueOf();
  374. }
  375. }
  376. eventEmitter.emit(RTCEvents.LASTN_CHANGED, oldValue, newValue);
  377. }
  378. else if ("LastNEndpointsChangeEvent" === colibriClass)
  379. {
  380. // The new/latest list of last-n endpoint IDs.
  381. var lastNEndpoints = obj.lastNEndpoints;
  382. // The list of endpoint IDs which are entering the list of
  383. // last-n at this time i.e. were not in the old list of last-n
  384. // endpoint IDs.
  385. var endpointsEnteringLastN = obj.endpointsEnteringLastN;
  386. var stream = obj.stream;
  387. console.log(
  388. "Data channel new last-n event: ",
  389. lastNEndpoints, endpointsEnteringLastN, obj);
  390. eventEmitter.emit(RTCEvents.LASTN_ENDPOINT_CHANGED,
  391. lastNEndpoints, endpointsEnteringLastN, obj);
  392. }
  393. else if ("SimulcastLayersChangedEvent" === colibriClass)
  394. {
  395. eventEmitter.emit(RTCEvents.SIMULCAST_LAYER_CHANGED,
  396. obj.endpointSimulcastLayers);
  397. }
  398. else if ("SimulcastLayersChangingEvent" === colibriClass)
  399. {
  400. eventEmitter.emit(RTCEvents.SIMULCAST_LAYER_CHANGING,
  401. obj.endpointSimulcastLayers);
  402. }
  403. else if ("StartSimulcastLayerEvent" === colibriClass)
  404. {
  405. eventEmitter.emit(RTCEvents.SIMULCAST_START, obj.simulcastLayer);
  406. }
  407. else if ("StopSimulcastLayerEvent" === colibriClass)
  408. {
  409. eventEmitter.emit(RTCEvents.SIMULCAST_STOP, obj.simulcastLayer);
  410. }
  411. else
  412. {
  413. console.debug("Data channel JSON-formatted message: ", obj);
  414. }
  415. }
  416. };
  417. dataChannel.onclose = function ()
  418. {
  419. console.info("The Data Channel closed", dataChannel);
  420. var idx = _dataChannels.indexOf(dataChannel);
  421. if (idx > -1)
  422. _dataChannels = _dataChannels.splice(idx, 1);
  423. };
  424. _dataChannels.push(dataChannel);
  425. },
  426. /**
  427. * Binds "ondatachannel" event listener to given PeerConnection instance.
  428. * @param peerConnection WebRTC peer connection instance.
  429. */
  430. init: function (peerConnection, emitter) {
  431. if(!config.openSctp)
  432. return;
  433. peerConnection.ondatachannel = this.onDataChannel;
  434. eventEmitter = emitter;
  435. // Sample code for opening new data channel from Jitsi Meet to the bridge.
  436. // Although it's not a requirement to open separate channels from both bridge
  437. // and peer as single channel can be used for sending and receiving data.
  438. // So either channel opened by the bridge or the one opened here is enough
  439. // for communication with the bridge.
  440. /*var dataChannelOptions =
  441. {
  442. reliable: true
  443. };
  444. var dataChannel
  445. = peerConnection.createDataChannel("myChannel", dataChannelOptions);
  446. // Can be used only when is in open state
  447. dataChannel.onopen = function ()
  448. {
  449. dataChannel.send("My channel !!!");
  450. };
  451. dataChannel.onmessage = function (event)
  452. {
  453. var msgData = event.data;
  454. console.info("Got My Data Channel Message:", msgData, dataChannel);
  455. };*/
  456. },
  457. handleSelectedEndpointEvent: onSelectedEndpointChanged,
  458. handlePinnedEndpointEvent: onPinnedEndpointChanged
  459. };
  460. function onSelectedEndpointChanged(userResource)
  461. {
  462. console.log('selected endpoint changed: ', userResource);
  463. if (_dataChannels && _dataChannels.length != 0)
  464. {
  465. _dataChannels.some(function (dataChannel) {
  466. if (dataChannel.readyState == 'open')
  467. {
  468. console.log('sending selected endpoint changed '
  469. + 'notification to the bridge: ', userResource);
  470. dataChannel.send(JSON.stringify({
  471. 'colibriClass': 'SelectedEndpointChangedEvent',
  472. 'selectedEndpoint':
  473. (!userResource || userResource === null)?
  474. null : userResource
  475. }));
  476. return true;
  477. }
  478. });
  479. }
  480. }
  481. function onPinnedEndpointChanged(userResource)
  482. {
  483. console.log('pinned endpoint changed: ', userResource);
  484. if (_dataChannels && _dataChannels.length != 0)
  485. {
  486. _dataChannels.some(function (dataChannel) {
  487. if (dataChannel.readyState == 'open')
  488. {
  489. dataChannel.send(JSON.stringify({
  490. 'colibriClass': 'PinnedEndpointChangedEvent',
  491. 'pinnedEndpoint':
  492. (!userResource || userResource == null)?
  493. null : userResource
  494. }));
  495. return true;
  496. }
  497. });
  498. }
  499. }
  500. module.exports = DataChannels;
  501. },{"../../service/RTC/RTCEvents":92}],5:[function(require,module,exports){
  502. var StreamEventTypes = require("../../service/RTC/StreamEventTypes.js");
  503. function LocalStream(stream, type, eventEmitter, videoType)
  504. {
  505. this.stream = stream;
  506. this.eventEmitter = eventEmitter;
  507. this.type = type;
  508. this.videoType = videoType;
  509. var self = this;
  510. if(type == "audio")
  511. {
  512. this.getTracks = function () {
  513. return self.stream.getAudioTracks();
  514. };
  515. }
  516. else
  517. {
  518. this.getTracks = function () {
  519. return self.stream.getVideoTracks();
  520. };
  521. }
  522. this.stream.onended = function()
  523. {
  524. self.streamEnded();
  525. };
  526. }
  527. LocalStream.prototype.streamEnded = function () {
  528. this.eventEmitter.emit(StreamEventTypes.EVENT_TYPE_LOCAL_ENDED, this);
  529. }
  530. LocalStream.prototype.getOriginalStream = function()
  531. {
  532. return this.stream;
  533. }
  534. LocalStream.prototype.isAudioStream = function () {
  535. return (this.stream.getAudioTracks() && this.stream.getAudioTracks().length > 0);
  536. };
  537. LocalStream.prototype.mute = function()
  538. {
  539. var ismuted = false;
  540. var tracks = this.getTracks();
  541. for (var idx = 0; idx < tracks.length; idx++) {
  542. ismuted = !tracks[idx].enabled;
  543. tracks[idx].enabled = ismuted;
  544. }
  545. return ismuted;
  546. };
  547. LocalStream.prototype.setMute = function(mute)
  548. {
  549. if(window.location.protocol != "https:" ||
  550. this.isAudioStream() || this.videoType === "screen")
  551. {
  552. var tracks = this.getTracks();
  553. for (var idx = 0; idx < tracks.length; idx++) {
  554. tracks[idx].enabled = mute;
  555. }
  556. }
  557. else
  558. {
  559. if(mute === false) {
  560. APP.xmpp.removeStream(this.stream);
  561. this.stream.stop();
  562. }
  563. else
  564. {
  565. APP.RTC.rtcUtils.obtainAudioAndVideoPermissions(["video"],
  566. function (stream) {
  567. APP.RTC.changeLocalVideo(stream, false, function () {});
  568. });
  569. }
  570. }
  571. };
  572. LocalStream.prototype.isMuted = function () {
  573. var tracks = [];
  574. if(this.type == "audio")
  575. {
  576. tracks = this.stream.getAudioTracks();
  577. }
  578. else
  579. {
  580. if(this.stream.ended)
  581. return true;
  582. tracks = this.stream.getVideoTracks();
  583. }
  584. for (var idx = 0; idx < tracks.length; idx++) {
  585. if(tracks[idx].enabled)
  586. return false;
  587. }
  588. return true;
  589. }
  590. LocalStream.prototype.getId = function () {
  591. return this.stream.getTracks()[0].id;
  592. }
  593. module.exports = LocalStream;
  594. },{"../../service/RTC/StreamEventTypes.js":94}],6:[function(require,module,exports){
  595. ////These lines should be uncommented when require works in app.js
  596. var MediaStreamType = require("../../service/RTC/MediaStreamTypes");
  597. var StreamEventType = require("../../service/RTC/StreamEventTypes");
  598. /**
  599. * Creates a MediaStream object for the given data, session id and ssrc.
  600. * It is a wrapper class for the MediaStream.
  601. *
  602. * @param data the data object from which we obtain the stream,
  603. * the peerjid, etc.
  604. * @param sid the session id
  605. * @param ssrc the ssrc corresponding to this MediaStream
  606. *
  607. * @constructor
  608. */
  609. function MediaStream(data, sid, ssrc, browser, eventEmitter) {
  610. // XXX(gp) to minimize headaches in the future, we should build our
  611. // abstractions around tracks and not streams. ORTC is track based API.
  612. // Mozilla expects m-lines to represent media tracks.
  613. //
  614. // Practically, what I'm saying is that we should have a MediaTrack class
  615. // and not a MediaStream class.
  616. //
  617. // Also, we should be able to associate multiple SSRCs with a MediaTrack as
  618. // a track might have an associated RTX and FEC sources.
  619. this.sid = sid;
  620. this.stream = data.stream;
  621. this.peerjid = data.peerjid;
  622. this.ssrc = ssrc;
  623. this.type = (this.stream.getVideoTracks().length > 0)?
  624. MediaStreamType.VIDEO_TYPE : MediaStreamType.AUDIO_TYPE;
  625. this.videoType = null;
  626. this.muted = false;
  627. this.eventEmitter = eventEmitter;
  628. }
  629. MediaStream.prototype.getOriginalStream = function()
  630. {
  631. return this.stream;
  632. };
  633. MediaStream.prototype.setMute = function (value)
  634. {
  635. this.stream.muted = value;
  636. this.muted = value;
  637. };
  638. MediaStream.prototype.setVideoType = function (value) {
  639. if(this.videoType === value)
  640. return;
  641. this.videoType = value;
  642. this.eventEmitter.emit(StreamEventType.EVENT_TYPE_REMOTE_CHANGED,
  643. this.peerjid);
  644. };
  645. module.exports = MediaStream;
  646. },{"../../service/RTC/MediaStreamTypes":90,"../../service/RTC/StreamEventTypes":94}],7:[function(require,module,exports){
  647. var EventEmitter = require("events");
  648. var RTCUtils = require("./RTCUtils.js");
  649. var LocalStream = require("./LocalStream.js");
  650. var DataChannels = require("./DataChannels");
  651. var MediaStream = require("./MediaStream.js");
  652. var DesktopSharingEventTypes
  653. = require("../../service/desktopsharing/DesktopSharingEventTypes");
  654. var MediaStreamType = require("../../service/RTC/MediaStreamTypes");
  655. var StreamEventTypes = require("../../service/RTC/StreamEventTypes.js");
  656. var RTCEvents = require("../../service/RTC/RTCEvents.js");
  657. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  658. var UIEvents = require("../../service/UI/UIEvents");
  659. var eventEmitter = new EventEmitter();
  660. var RTC = {
  661. rtcUtils: null,
  662. devices: {
  663. audio: false,
  664. video: false
  665. },
  666. localStreams: [],
  667. remoteStreams: {},
  668. localAudio: null,
  669. localVideo: null,
  670. addStreamListener: function (listener, eventType) {
  671. eventEmitter.on(eventType, listener);
  672. },
  673. addListener: function (type, listener) {
  674. eventEmitter.on(type, listener);
  675. },
  676. removeStreamListener: function (listener, eventType) {
  677. if(!(eventType instanceof StreamEventTypes))
  678. throw "Illegal argument";
  679. eventEmitter.removeListener(eventType, listener);
  680. },
  681. createLocalStream: function (stream, type, change, videoType) {
  682. var localStream = new LocalStream(stream, type, eventEmitter, videoType);
  683. //in firefox we have only one stream object
  684. if(this.localStreams.length == 0 ||
  685. this.localStreams[0].getOriginalStream() != stream)
  686. this.localStreams.push(localStream);
  687. if(type == "audio")
  688. {
  689. this.localAudio = localStream;
  690. }
  691. else
  692. {
  693. this.localVideo = localStream;
  694. }
  695. var eventType = StreamEventTypes.EVENT_TYPE_LOCAL_CREATED;
  696. if(change)
  697. eventType = StreamEventTypes.EVENT_TYPE_LOCAL_CHANGED;
  698. eventEmitter.emit(eventType, localStream);
  699. return localStream;
  700. },
  701. removeLocalStream: function (stream) {
  702. for(var i = 0; i < this.localStreams.length; i++)
  703. {
  704. if(this.localStreams[i].getOriginalStream() === stream) {
  705. delete this.localStreams[i];
  706. return;
  707. }
  708. }
  709. },
  710. createRemoteStream: function (data, sid, thessrc) {
  711. var remoteStream = new MediaStream(data, sid, thessrc,
  712. this.getBrowserType(), eventEmitter);
  713. var jid = data.peerjid || APP.xmpp.myJid();
  714. if(!this.remoteStreams[jid]) {
  715. this.remoteStreams[jid] = {};
  716. }
  717. this.remoteStreams[jid][remoteStream.type]= remoteStream;
  718. eventEmitter.emit(StreamEventTypes.EVENT_TYPE_REMOTE_CREATED, remoteStream);
  719. return remoteStream;
  720. },
  721. getBrowserType: function () {
  722. return this.rtcUtils.browser;
  723. },
  724. getPCConstraints: function () {
  725. return this.rtcUtils.pc_constraints;
  726. },
  727. getUserMediaWithConstraints:function(um, success_callback,
  728. failure_callback, resolution,
  729. bandwidth, fps, desktopStream)
  730. {
  731. return this.rtcUtils.getUserMediaWithConstraints(um, success_callback,
  732. failure_callback, resolution, bandwidth, fps, desktopStream);
  733. },
  734. attachMediaStream: function (element, stream) {
  735. this.rtcUtils.attachMediaStream(element, stream);
  736. },
  737. getStreamID: function (stream) {
  738. return this.rtcUtils.getStreamID(stream);
  739. },
  740. getVideoSrc: function (element) {
  741. return this.rtcUtils.getVideoSrc(element);
  742. },
  743. setVideoSrc: function (element, src) {
  744. this.rtcUtils.setVideoSrc(element, src);
  745. },
  746. dispose: function() {
  747. if (this.rtcUtils) {
  748. this.rtcUtils = null;
  749. }
  750. },
  751. stop: function () {
  752. this.dispose();
  753. },
  754. start: function () {
  755. var self = this;
  756. APP.desktopsharing.addListener(
  757. function (stream, isUsingScreenStream, callback) {
  758. self.changeLocalVideo(stream, isUsingScreenStream, callback);
  759. }, DesktopSharingEventTypes.NEW_STREAM_CREATED);
  760. APP.xmpp.addListener(XMPPEvents.STREAMS_CHANGED, function (jid, changedStreams) {
  761. for(var i = 0; i < changedStreams.length; i++) {
  762. var type = changedStreams[i].type;
  763. if (type != "audio") {
  764. var peerStreams = self.remoteStreams[jid];
  765. if(!peerStreams)
  766. continue;
  767. var videoStream = peerStreams[MediaStreamType.VIDEO_TYPE];
  768. if(!videoStream)
  769. continue;
  770. videoStream.setVideoType(changedStreams[i].type);
  771. }
  772. }
  773. });
  774. APP.xmpp.addListener(XMPPEvents.CALL_INCOMING, function(event) {
  775. DataChannels.init(event.peerconnection, eventEmitter);
  776. });
  777. APP.UI.addListener(UIEvents.SELECTED_ENDPOINT,
  778. DataChannels.handleSelectedEndpointEvent);
  779. APP.UI.addListener(UIEvents.PINNED_ENDPOINT,
  780. DataChannels.handlePinnedEndpointEvent);
  781. this.rtcUtils = new RTCUtils(this);
  782. this.rtcUtils.obtainAudioAndVideoPermissions();
  783. },
  784. muteRemoteVideoStream: function (jid, value) {
  785. var stream;
  786. if(this.remoteStreams[jid] &&
  787. this.remoteStreams[jid][MediaStreamType.VIDEO_TYPE])
  788. {
  789. stream = this.remoteStreams[jid][MediaStreamType.VIDEO_TYPE];
  790. }
  791. if(!stream)
  792. return true;
  793. if (value != stream.muted) {
  794. stream.setMute(value);
  795. return true;
  796. }
  797. return false;
  798. },
  799. switchVideoStreams: function (new_stream) {
  800. this.localVideo.stream = new_stream;
  801. this.localStreams = [];
  802. //in firefox we have only one stream object
  803. if (this.localAudio.getOriginalStream() != new_stream)
  804. this.localStreams.push(this.localAudio);
  805. this.localStreams.push(this.localVideo);
  806. },
  807. changeLocalVideo: function (stream, isUsingScreenStream, callback) {
  808. var oldStream = this.localVideo.getOriginalStream();
  809. var type = (isUsingScreenStream? "screen" : "video");
  810. var localCallback = callback;
  811. if(this.localVideo.isMuted() && this.localVideo.videoType !== type)
  812. {
  813. localCallback = function() {
  814. APP.xmpp.setVideoMute(false, APP.UI.setVideoMuteButtonsState);
  815. callback();
  816. };
  817. }
  818. var videoStream = this.rtcUtils.createVideoStream(stream);
  819. this.localVideo = this.createLocalStream(videoStream, "video", true, type);
  820. // Stop the stream to trigger onended event for old stream
  821. oldStream.stop();
  822. APP.xmpp.switchStreams(videoStream, oldStream,localCallback);
  823. },
  824. /**
  825. * Checks if video identified by given src is desktop stream.
  826. * @param videoSrc eg.
  827. * blob:https%3A//pawel.jitsi.net/9a46e0bd-131e-4d18-9c14-a9264e8db395
  828. * @returns {boolean}
  829. */
  830. isVideoSrcDesktop: function (jid) {
  831. if(!jid)
  832. return false;
  833. var isDesktop = false;
  834. var stream = null;
  835. if (APP.xmpp.myJid() === jid) {
  836. // local video
  837. stream = this.localVideo;
  838. } else {
  839. var peerStreams = this.remoteStreams[jid];
  840. if(!peerStreams)
  841. return false;
  842. stream = peerStreams[MediaStreamType.VIDEO_TYPE];
  843. }
  844. if(stream)
  845. isDesktop = (stream.videoType === "screen");
  846. return isDesktop;
  847. },
  848. setVideoMute: function(mute, callback, options) {
  849. if(!this.localVideo)
  850. return;
  851. if (mute == APP.RTC.localVideo.isMuted())
  852. {
  853. APP.xmpp.sendVideoInfoPresence(mute);
  854. if(callback)
  855. callback();
  856. }
  857. else
  858. {
  859. APP.RTC.localVideo.setMute(!mute);
  860. APP.xmpp.setVideoMute(
  861. mute,
  862. callback,
  863. options);
  864. }
  865. },
  866. setDeviceAvailability: function (devices) {
  867. if(!devices)
  868. return;
  869. if(devices.audio === true || devices.audio === false)
  870. this.devices.audio = devices.audio;
  871. if(devices.video === true || devices.video === false)
  872. this.devices.video = devices.video;
  873. eventEmitter.emit(RTCEvents.AVAILABLE_DEVICES_CHANGED, this.devices);
  874. }
  875. };
  876. module.exports = RTC;
  877. },{"../../service/RTC/MediaStreamTypes":90,"../../service/RTC/RTCEvents.js":92,"../../service/RTC/StreamEventTypes.js":94,"../../service/UI/UIEvents":95,"../../service/desktopsharing/DesktopSharingEventTypes":98,"../../service/xmpp/XMPPEvents":101,"./DataChannels":4,"./LocalStream.js":5,"./MediaStream.js":6,"./RTCUtils.js":8,"events":102}],8:[function(require,module,exports){
  878. var RTCBrowserType = require("../../service/RTC/RTCBrowserType.js");
  879. var Resolutions = require("../../service/RTC/Resolutions");
  880. var currentResolution = null;
  881. function getPreviousResolution(resolution) {
  882. if(!Resolutions[resolution])
  883. return null;
  884. var order = Resolutions[resolution].order;
  885. var res = null;
  886. var resName = null;
  887. for(var i in Resolutions)
  888. {
  889. var tmp = Resolutions[i];
  890. if(res == null || (res.order < tmp.order && tmp.order < order))
  891. {
  892. resName = i;
  893. res = tmp;
  894. }
  895. }
  896. return resName;
  897. }
  898. function setResolutionConstraints(constraints, resolution, isAndroid)
  899. {
  900. if (resolution && !constraints.video || isAndroid) {
  901. constraints.video = { mandatory: {}, optional: [] };// same behaviour as true
  902. }
  903. if(Resolutions[resolution])
  904. {
  905. constraints.video.mandatory.minWidth = Resolutions[resolution].width;
  906. constraints.video.mandatory.minHeight = Resolutions[resolution].height;
  907. }
  908. else
  909. {
  910. if (isAndroid) {
  911. constraints.video.mandatory.minWidth = 320;
  912. constraints.video.mandatory.minHeight = 240;
  913. constraints.video.mandatory.maxFrameRate = 15;
  914. }
  915. }
  916. if (constraints.video.mandatory.minWidth)
  917. constraints.video.mandatory.maxWidth = constraints.video.mandatory.minWidth;
  918. if (constraints.video.mandatory.minHeight)
  919. constraints.video.mandatory.maxHeight = constraints.video.mandatory.minHeight;
  920. }
  921. function getConstraints(um, resolution, bandwidth, fps, desktopStream, isAndroid)
  922. {
  923. var constraints = {audio: false, video: false};
  924. if (um.indexOf('video') >= 0) {
  925. constraints.video = { mandatory: {}, optional: [] };// same behaviour as true
  926. }
  927. if (um.indexOf('audio') >= 0) {
  928. constraints.audio = { mandatory: {}, optional: []};// same behaviour as true
  929. }
  930. if (um.indexOf('screen') >= 0) {
  931. constraints.video = {
  932. mandatory: {
  933. chromeMediaSource: "screen",
  934. googLeakyBucket: true,
  935. maxWidth: window.screen.width,
  936. maxHeight: window.screen.height,
  937. maxFrameRate: 3
  938. },
  939. optional: []
  940. };
  941. }
  942. if (um.indexOf('desktop') >= 0) {
  943. constraints.video = {
  944. mandatory: {
  945. chromeMediaSource: "desktop",
  946. chromeMediaSourceId: desktopStream,
  947. googLeakyBucket: true,
  948. maxWidth: window.screen.width,
  949. maxHeight: window.screen.height,
  950. maxFrameRate: 3
  951. },
  952. optional: []
  953. };
  954. }
  955. if (constraints.audio) {
  956. // if it is good enough for hangouts...
  957. constraints.audio.optional.push(
  958. {googEchoCancellation: true},
  959. {googAutoGainControl: true},
  960. {googNoiseSupression: true},
  961. {googHighpassFilter: true},
  962. {googNoisesuppression2: true},
  963. {googEchoCancellation2: true},
  964. {googAutoGainControl2: true}
  965. );
  966. }
  967. if (constraints.video) {
  968. constraints.video.optional.push(
  969. {googNoiseReduction: false} // chrome 37 workaround for issue 3807, reenable in M38
  970. );
  971. if (um.indexOf('video') >= 0) {
  972. constraints.video.optional.push(
  973. {googLeakyBucket: true}
  974. );
  975. }
  976. }
  977. if (um.indexOf('video') >= 0) {
  978. setResolutionConstraints(constraints, resolution, isAndroid);
  979. }
  980. if (bandwidth) { // doesn't work currently, see webrtc issue 1846
  981. if (!constraints.video) constraints.video = {mandatory: {}, optional: []};//same behaviour as true
  982. constraints.video.optional.push({bandwidth: bandwidth});
  983. }
  984. if (fps) { // for some cameras it might be necessary to request 30fps
  985. // so they choose 30fps mjpg over 10fps yuy2
  986. if (!constraints.video) constraints.video = {mandatory: {}, optional: []};// same behaviour as true;
  987. constraints.video.mandatory.minFrameRate = fps;
  988. }
  989. return constraints;
  990. }
  991. function RTCUtils(RTCService)
  992. {
  993. this.service = RTCService;
  994. if (navigator.mozGetUserMedia) {
  995. console.log('This appears to be Firefox');
  996. var version = parseInt(navigator.userAgent.match(/Firefox\/([0-9]+)\./)[1], 10);
  997. if (version >= 38
  998. && !config.enableSimulcast && config.useBundle && config.useRtcpMux) {
  999. this.peerconnection = mozRTCPeerConnection;
  1000. this.browser = RTCBrowserType.RTC_BROWSER_FIREFOX;
  1001. this.getUserMedia = navigator.mozGetUserMedia.bind(navigator);
  1002. this.pc_constraints = {};
  1003. this.attachMediaStream = function (element, stream) {
  1004. // srcObject is being standardized and FF will eventually
  1005. // support that unprefixed. FF also supports the
  1006. // "element.src = URL.createObjectURL(...)" combo, but that
  1007. // will be deprecated in favour of srcObject.
  1008. //
  1009. // https://groups.google.com/forum/#!topic/mozilla.dev.media/pKOiioXonJg
  1010. // https://github.com/webrtc/samples/issues/302
  1011. element[0].mozSrcObject = stream;
  1012. element[0].play();
  1013. };
  1014. this.getStreamID = function (stream) {
  1015. var tracks = stream.getVideoTracks();
  1016. if(!tracks || tracks.length == 0)
  1017. {
  1018. tracks = stream.getAudioTracks();
  1019. }
  1020. return tracks[0].id.replace(/[\{,\}]/g,"");
  1021. };
  1022. this.getVideoSrc = function (element) {
  1023. return element.mozSrcObject;
  1024. };
  1025. this.setVideoSrc = function (element, src) {
  1026. element.mozSrcObject = src;
  1027. };
  1028. RTCSessionDescription = mozRTCSessionDescription;
  1029. RTCIceCandidate = mozRTCIceCandidate;
  1030. } else {
  1031. window.location.href = 'unsupported_browser.html';
  1032. return;
  1033. }
  1034. } else if (navigator.webkitGetUserMedia) {
  1035. console.log('This appears to be Chrome');
  1036. this.peerconnection = webkitRTCPeerConnection;
  1037. this.browser = RTCBrowserType.RTC_BROWSER_CHROME;
  1038. this.getUserMedia = navigator.webkitGetUserMedia.bind(navigator);
  1039. this.attachMediaStream = function (element, stream) {
  1040. element.attr('src', webkitURL.createObjectURL(stream));
  1041. };
  1042. this.getStreamID = function (stream) {
  1043. // streams from FF endpoints have the characters '{' and '}'
  1044. // that make jQuery choke.
  1045. return stream.id.replace(/[\{,\}]/g,"");
  1046. };
  1047. this.getVideoSrc = function (element) {
  1048. return element.getAttribute("src");
  1049. };
  1050. this.setVideoSrc = function (element, src) {
  1051. element.setAttribute("src", src);
  1052. };
  1053. // DTLS should now be enabled by default but..
  1054. this.pc_constraints = {'optional': [{'DtlsSrtpKeyAgreement': 'true'}]};
  1055. if (navigator.userAgent.indexOf('Android') != -1) {
  1056. this.pc_constraints = {}; // disable DTLS on Android
  1057. }
  1058. if (!webkitMediaStream.prototype.getVideoTracks) {
  1059. webkitMediaStream.prototype.getVideoTracks = function () {
  1060. return this.videoTracks;
  1061. };
  1062. }
  1063. if (!webkitMediaStream.prototype.getAudioTracks) {
  1064. webkitMediaStream.prototype.getAudioTracks = function () {
  1065. return this.audioTracks;
  1066. };
  1067. }
  1068. }
  1069. else
  1070. {
  1071. try { console.log('Browser does not appear to be WebRTC-capable'); } catch (e) { }
  1072. window.location.href = 'unsupported_browser.html';
  1073. return;
  1074. }
  1075. }
  1076. RTCUtils.prototype.getUserMediaWithConstraints = function(
  1077. um, success_callback, failure_callback, resolution,bandwidth, fps,
  1078. desktopStream)
  1079. {
  1080. currentResolution = resolution;
  1081. // Check if we are running on Android device
  1082. var isAndroid = navigator.userAgent.indexOf('Android') != -1;
  1083. var constraints = getConstraints(
  1084. um, resolution, bandwidth, fps, desktopStream, isAndroid);
  1085. var isFF = navigator.userAgent.toLowerCase().indexOf('firefox') > -1;
  1086. var self = this;
  1087. try {
  1088. if (config.enableSimulcast
  1089. && constraints.video
  1090. && constraints.video.chromeMediaSource !== 'screen'
  1091. && constraints.video.chromeMediaSource !== 'desktop'
  1092. && !isAndroid
  1093. // We currently do not support FF, as it doesn't have multistream support.
  1094. && !isFF) {
  1095. APP.simulcast.getUserMedia(constraints, function (stream) {
  1096. console.log('onUserMediaSuccess');
  1097. self.setAvailableDevices(um, true);
  1098. success_callback(stream);
  1099. },
  1100. function (error) {
  1101. console.warn('Failed to get access to local media. Error ', error);
  1102. self.setAvailableDevices(um, false);
  1103. if (failure_callback) {
  1104. failure_callback(error);
  1105. }
  1106. });
  1107. } else {
  1108. this.getUserMedia(constraints,
  1109. function (stream) {
  1110. console.log('onUserMediaSuccess');
  1111. self.setAvailableDevices(um, true);
  1112. success_callback(stream);
  1113. },
  1114. function (error) {
  1115. self.setAvailableDevices(um, false);
  1116. console.warn('Failed to get access to local media. Error ',
  1117. error, constraints);
  1118. if (failure_callback) {
  1119. failure_callback(error);
  1120. }
  1121. });
  1122. }
  1123. } catch (e) {
  1124. console.error('GUM failed: ', e);
  1125. if(failure_callback) {
  1126. failure_callback(e);
  1127. }
  1128. }
  1129. };
  1130. RTCUtils.prototype.setAvailableDevices = function (um, available) {
  1131. var devices = {};
  1132. if(um.indexOf("video") != -1)
  1133. {
  1134. devices.video = available;
  1135. }
  1136. if(um.indexOf("audio") != -1)
  1137. {
  1138. devices.audio = available;
  1139. }
  1140. this.service.setDeviceAvailability(devices);
  1141. }
  1142. /**
  1143. * We ask for audio and video combined stream in order to get permissions and
  1144. * not to ask twice.
  1145. */
  1146. RTCUtils.prototype.obtainAudioAndVideoPermissions = function(devices, callback) {
  1147. var self = this;
  1148. // Get AV
  1149. if(!devices)
  1150. devices = ['audio', 'video'];
  1151. this.getUserMediaWithConstraints(
  1152. devices,
  1153. function (stream) {
  1154. if(callback)
  1155. callback(stream);
  1156. else
  1157. self.successCallback(stream);
  1158. },
  1159. function (error) {
  1160. self.errorCallback(error);
  1161. },
  1162. config.resolution || '360');
  1163. }
  1164. RTCUtils.prototype.successCallback = function (stream) {
  1165. if(stream)
  1166. console.log('got', stream, stream.getAudioTracks().length,
  1167. stream.getVideoTracks().length);
  1168. this.handleLocalStream(stream);
  1169. };
  1170. RTCUtils.prototype.errorCallback = function (error) {
  1171. var self = this;
  1172. console.error('failed to obtain audio/video stream - trying audio only', error);
  1173. var resolution = getPreviousResolution(currentResolution);
  1174. if(typeof error == "object" && error.constraintName && error.name
  1175. && (error.name == "ConstraintNotSatisfiedError" ||
  1176. error.name == "OverconstrainedError") &&
  1177. (error.constraintName == "minWidth" || error.constraintName == "maxWidth" ||
  1178. error.constraintName == "minHeight" || error.constraintName == "maxHeight")
  1179. && resolution != null)
  1180. {
  1181. self.getUserMediaWithConstraints(['audio', 'video'],
  1182. function (stream) {
  1183. return self.successCallback(stream);
  1184. }, function (error) {
  1185. return self.errorCallback(error);
  1186. }, resolution);
  1187. }
  1188. else
  1189. {
  1190. self.getUserMediaWithConstraints(
  1191. ['audio'],
  1192. function (stream) {
  1193. return self.successCallback(stream);
  1194. },
  1195. function (error) {
  1196. console.error('failed to obtain audio/video stream - stop',
  1197. error);
  1198. return self.successCallback(null);
  1199. }
  1200. );
  1201. }
  1202. }
  1203. RTCUtils.prototype.handleLocalStream = function(stream)
  1204. {
  1205. if(window.webkitMediaStream)
  1206. {
  1207. var audioStream = new webkitMediaStream();
  1208. var videoStream = new webkitMediaStream();
  1209. if(stream) {
  1210. var audioTracks = stream.getAudioTracks();
  1211. for (var i = 0; i < audioTracks.length; i++) {
  1212. audioStream.addTrack(audioTracks[i]);
  1213. }
  1214. var videoTracks = stream.getVideoTracks();
  1215. for (i = 0; i < videoTracks.length; i++) {
  1216. videoStream.addTrack(videoTracks[i]);
  1217. }
  1218. }
  1219. this.service.createLocalStream(audioStream, "audio");
  1220. this.service.createLocalStream(videoStream, "video");
  1221. }
  1222. else
  1223. {//firefox
  1224. this.service.createLocalStream(stream, "stream");
  1225. }
  1226. };
  1227. RTCUtils.prototype.createVideoStream = function(stream)
  1228. {
  1229. var videoStream = null;
  1230. if(window.webkitMediaStream)
  1231. {
  1232. videoStream = new webkitMediaStream();
  1233. if(stream)
  1234. {
  1235. var videoTracks = stream.getVideoTracks();
  1236. for (i = 0; i < videoTracks.length; i++) {
  1237. videoStream.addTrack(videoTracks[i]);
  1238. }
  1239. }
  1240. }
  1241. else
  1242. videoStream = stream;
  1243. return videoStream;
  1244. };
  1245. module.exports = RTCUtils;
  1246. },{"../../service/RTC/RTCBrowserType.js":91,"../../service/RTC/Resolutions":93}],9:[function(require,module,exports){
  1247. var UI = {};
  1248. var VideoLayout = require("./videolayout/VideoLayout.js");
  1249. var AudioLevels = require("./audio_levels/AudioLevels.js");
  1250. var Prezi = require("./prezi/Prezi.js");
  1251. var Etherpad = require("./etherpad/Etherpad.js");
  1252. var Chat = require("./side_pannels/chat/Chat.js");
  1253. var Toolbar = require("./toolbars/Toolbar");
  1254. var ToolbarToggler = require("./toolbars/ToolbarToggler");
  1255. var BottomToolbar = require("./toolbars/BottomToolbar");
  1256. var ContactList = require("./side_pannels/contactlist/ContactList");
  1257. var Avatar = require("./avatar/Avatar");
  1258. var EventEmitter = require("events");
  1259. var SettingsMenu = require("./side_pannels/settings/SettingsMenu");
  1260. var Settings = require("./../settings/Settings");
  1261. var PanelToggler = require("./side_pannels/SidePanelToggler");
  1262. var RoomNameGenerator = require("./welcome_page/RoomnameGenerator");
  1263. UI.messageHandler = require("./util/MessageHandler");
  1264. var messageHandler = UI.messageHandler;
  1265. var Authentication = require("./authentication/Authentication");
  1266. var UIUtil = require("./util/UIUtil");
  1267. var NicknameHandler = require("./util/NicknameHandler");
  1268. var CQEvents = require("../../service/connectionquality/CQEvents");
  1269. var DesktopSharingEventTypes
  1270. = require("../../service/desktopsharing/DesktopSharingEventTypes");
  1271. var RTCEvents = require("../../service/RTC/RTCEvents");
  1272. var StreamEventTypes = require("../../service/RTC/StreamEventTypes");
  1273. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  1274. var MemberEvents = require("../../service/members/Events");
  1275. var eventEmitter = new EventEmitter();
  1276. var roomName = null;
  1277. function setupPrezi()
  1278. {
  1279. $("#reloadPresentationLink").click(function()
  1280. {
  1281. Prezi.reloadPresentation();
  1282. });
  1283. }
  1284. function setupChat()
  1285. {
  1286. Chat.init();
  1287. $("#toggle_smileys").click(function() {
  1288. Chat.toggleSmileys();
  1289. });
  1290. }
  1291. function setupToolbars() {
  1292. Toolbar.init(UI);
  1293. Toolbar.setupButtonsFromConfig();
  1294. BottomToolbar.init();
  1295. }
  1296. function streamHandler(stream) {
  1297. switch (stream.type)
  1298. {
  1299. case "audio":
  1300. VideoLayout.changeLocalAudio(stream);
  1301. break;
  1302. case "video":
  1303. VideoLayout.changeLocalVideo(stream);
  1304. break;
  1305. case "stream":
  1306. VideoLayout.changeLocalStream(stream);
  1307. break;
  1308. }
  1309. }
  1310. function onDisposeConference(unload) {
  1311. Toolbar.showAuthenticateButton(false);
  1312. };
  1313. function onDisplayNameChanged(jid, displayName) {
  1314. ContactList.onDisplayNameChange(jid, displayName);
  1315. SettingsMenu.onDisplayNameChange(jid, displayName);
  1316. VideoLayout.onDisplayNameChanged(jid, displayName);
  1317. }
  1318. function registerListeners() {
  1319. APP.RTC.addStreamListener(streamHandler, StreamEventTypes.EVENT_TYPE_LOCAL_CREATED);
  1320. APP.RTC.addStreamListener(streamHandler, StreamEventTypes.EVENT_TYPE_LOCAL_CHANGED);
  1321. APP.RTC.addStreamListener(function (stream) {
  1322. VideoLayout.onRemoteStreamAdded(stream);
  1323. }, StreamEventTypes.EVENT_TYPE_REMOTE_CREATED);
  1324. APP.RTC.addStreamListener(function (jid) {
  1325. VideoLayout.onVideoTypeChanged(jid);
  1326. }, StreamEventTypes.EVENT_TYPE_REMOTE_CHANGED);
  1327. APP.RTC.addListener(RTCEvents.LASTN_CHANGED, onLastNChanged);
  1328. APP.RTC.addListener(RTCEvents.DOMINANTSPEAKER_CHANGED, function (resourceJid) {
  1329. VideoLayout.onDominantSpeakerChanged(resourceJid);
  1330. });
  1331. APP.RTC.addListener(RTCEvents.LASTN_ENDPOINT_CHANGED,
  1332. function (lastNEndpoints, endpointsEnteringLastN, stream) {
  1333. VideoLayout.onLastNEndpointsChanged(lastNEndpoints,
  1334. endpointsEnteringLastN, stream);
  1335. });
  1336. APP.RTC.addListener(RTCEvents.SIMULCAST_LAYER_CHANGED,
  1337. function (endpointSimulcastLayers) {
  1338. VideoLayout.onSimulcastLayersChanged(endpointSimulcastLayers);
  1339. });
  1340. APP.RTC.addListener(RTCEvents.SIMULCAST_LAYER_CHANGING,
  1341. function (endpointSimulcastLayers) {
  1342. VideoLayout.onSimulcastLayersChanging(endpointSimulcastLayers);
  1343. });
  1344. APP.RTC.addListener(RTCEvents.AVAILABLE_DEVICES_CHANGED,
  1345. function (devices) {
  1346. VideoLayout.setDeviceAvailabilityIcons(null, devices);
  1347. })
  1348. APP.statistics.addAudioLevelListener(function(jid, audioLevel)
  1349. {
  1350. var resourceJid;
  1351. if(jid === APP.statistics.LOCAL_JID)
  1352. {
  1353. resourceJid = AudioLevels.LOCAL_LEVEL;
  1354. if(APP.RTC.localAudio.isMuted())
  1355. {
  1356. audioLevel = 0;
  1357. }
  1358. }
  1359. else
  1360. {
  1361. resourceJid = Strophe.getResourceFromJid(jid);
  1362. }
  1363. AudioLevels.updateAudioLevel(resourceJid, audioLevel,
  1364. UI.getLargeVideoState().userResourceJid);
  1365. });
  1366. APP.desktopsharing.addListener(function () {
  1367. ToolbarToggler.showDesktopSharingButton();
  1368. }, DesktopSharingEventTypes.INIT);
  1369. APP.desktopsharing.addListener(
  1370. Toolbar.changeDesktopSharingButtonState,
  1371. DesktopSharingEventTypes.SWITCHING_DONE);
  1372. APP.connectionquality.addListener(CQEvents.LOCALSTATS_UPDATED,
  1373. VideoLayout.updateLocalConnectionStats);
  1374. APP.connectionquality.addListener(CQEvents.REMOTESTATS_UPDATED,
  1375. VideoLayout.updateConnectionStats);
  1376. APP.connectionquality.addListener(CQEvents.STOP,
  1377. VideoLayout.onStatsStop);
  1378. APP.xmpp.addListener(XMPPEvents.DISPOSE_CONFERENCE, onDisposeConference);
  1379. APP.xmpp.addListener(XMPPEvents.GRACEFUL_SHUTDOWN, function () {
  1380. messageHandler.openMessageDialog(
  1381. 'dialog.serviceUnavailable',
  1382. 'dialog.gracefulShutdown'
  1383. );
  1384. });
  1385. APP.xmpp.addListener(XMPPEvents.RESERVATION_ERROR, function (code, msg) {
  1386. var title = APP.translation.generateTranslatonHTML(
  1387. "dialog.reservationError");
  1388. var message = APP.translation.generateTranslatonHTML(
  1389. "dialog.reservationErrorMsg", {code: code, msg: msg});
  1390. messageHandler.openDialog(
  1391. title,
  1392. message,
  1393. true, {},
  1394. function (event, value, message, formVals)
  1395. {
  1396. return false;
  1397. }
  1398. );
  1399. });
  1400. APP.xmpp.addListener(XMPPEvents.KICKED, function () {
  1401. messageHandler.openMessageDialog("dialog.sessTerminated",
  1402. "dialog.kickMessage");
  1403. });
  1404. APP.xmpp.addListener(XMPPEvents.MUC_DESTROYED, function (reason) {
  1405. //FIXME: use Session Terminated from translation, but
  1406. // 'reason' text comes from XMPP packet and is not translated
  1407. var title = APP.translation.generateTranslatonHTML("dialog.sessTerminated");
  1408. messageHandler.openDialog(
  1409. title, reason, true, {},
  1410. function (event, value, message, formVals)
  1411. {
  1412. return false;
  1413. }
  1414. );
  1415. });
  1416. APP.xmpp.addListener(XMPPEvents.BRIDGE_DOWN, function () {
  1417. messageHandler.showError("dialog.error",
  1418. "dialog.bridgeUnavailable");
  1419. });
  1420. APP.xmpp.addListener(XMPPEvents.USER_ID_CHANGED, function (from, id) {
  1421. Avatar.setUserAvatar(from, id);
  1422. });
  1423. APP.xmpp.addListener(XMPPEvents.STREAMS_CHANGED, function (jid, changedStreams) {
  1424. for(stream in changedStreams)
  1425. {
  1426. // might need to update the direction if participant just went from sendrecv to recvonly
  1427. if (stream.type === 'video' || stream.type === 'screen') {
  1428. var el = $('#participant_' + Strophe.getResourceFromJid(jid) + '>video');
  1429. switch (stream.direction) {
  1430. case 'sendrecv':
  1431. el.show();
  1432. break;
  1433. case 'recvonly':
  1434. el.hide();
  1435. // FIXME: Check if we have to change large video
  1436. //VideoLayout.updateLargeVideo(el);
  1437. break;
  1438. }
  1439. }
  1440. }
  1441. });
  1442. APP.xmpp.addListener(XMPPEvents.DISPLAY_NAME_CHANGED, onDisplayNameChanged);
  1443. APP.xmpp.addListener(XMPPEvents.MUC_JOINED, onMucJoined);
  1444. APP.xmpp.addListener(XMPPEvents.LOCAL_ROLE_CHANGED, onLocalRoleChanged);
  1445. APP.xmpp.addListener(XMPPEvents.MUC_MEMBER_JOINED, onMucMemberJoined);
  1446. APP.xmpp.addListener(XMPPEvents.MUC_ROLE_CHANGED, onMucRoleChanged);
  1447. APP.xmpp.addListener(XMPPEvents.PRESENCE_STATUS, onMucPresenceStatus);
  1448. APP.xmpp.addListener(XMPPEvents.SUBJECT_CHANGED, chatSetSubject);
  1449. APP.xmpp.addListener(XMPPEvents.MESSAGE_RECEIVED, updateChatConversation);
  1450. APP.xmpp.addListener(XMPPEvents.MUC_MEMBER_LEFT, onMucMemberLeft);
  1451. APP.xmpp.addListener(XMPPEvents.PASSWORD_REQUIRED, onPasswordRequired);
  1452. APP.xmpp.addListener(XMPPEvents.CHAT_ERROR_RECEIVED, chatAddError);
  1453. APP.xmpp.addListener(XMPPEvents.ETHERPAD, initEtherpad);
  1454. APP.xmpp.addListener(XMPPEvents.AUTHENTICATION_REQUIRED,
  1455. onAuthenticationRequired);
  1456. APP.xmpp.addListener(XMPPEvents.DEVICE_AVAILABLE,
  1457. function (resource, devices) {
  1458. VideoLayout.setDeviceAvailabilityIcons(resource, devices);
  1459. });
  1460. APP.members.addListener(MemberEvents.DTMF_SUPPORT_CHANGED,
  1461. onDtmfSupportChanged);
  1462. }
  1463. /**
  1464. * Mutes/unmutes the local video.
  1465. *
  1466. * @param mute <tt>true</tt> to mute the local video; otherwise, <tt>false</tt>
  1467. * @param options an object which specifies optional arguments such as the
  1468. * <tt>boolean</tt> key <tt>byUser</tt> with default value <tt>true</tt> which
  1469. * specifies whether the method was initiated in response to a user command (in
  1470. * contrast to an automatic decision taken by the application logic)
  1471. */
  1472. function setVideoMute(mute, options) {
  1473. APP.RTC.setVideoMute(mute,
  1474. UI.setVideoMuteButtonsState,
  1475. options);
  1476. }
  1477. function bindEvents()
  1478. {
  1479. /**
  1480. * Resizes and repositions videos in full screen mode.
  1481. */
  1482. $(document).on('webkitfullscreenchange mozfullscreenchange fullscreenchange',
  1483. function () {
  1484. VideoLayout.resizeLargeVideoContainer();
  1485. VideoLayout.positionLarge();
  1486. }
  1487. );
  1488. $(window).resize(function () {
  1489. VideoLayout.resizeLargeVideoContainer();
  1490. VideoLayout.positionLarge();
  1491. });
  1492. }
  1493. UI.start = function (init) {
  1494. document.title = interfaceConfig.APP_NAME;
  1495. if(config.enableWelcomePage && window.location.pathname == "/" &&
  1496. (!window.localStorage.welcomePageDisabled || window.localStorage.welcomePageDisabled == "false"))
  1497. {
  1498. $("#videoconference_page").hide();
  1499. var setupWelcomePage = require("./welcome_page/WelcomePage");
  1500. setupWelcomePage();
  1501. return;
  1502. }
  1503. if (interfaceConfig.SHOW_JITSI_WATERMARK) {
  1504. var leftWatermarkDiv
  1505. = $("#largeVideoContainer div[class='watermark leftwatermark']");
  1506. leftWatermarkDiv.css({display: 'block'});
  1507. leftWatermarkDiv.parent().get(0).href
  1508. = interfaceConfig.JITSI_WATERMARK_LINK;
  1509. }
  1510. if (interfaceConfig.SHOW_BRAND_WATERMARK) {
  1511. var rightWatermarkDiv
  1512. = $("#largeVideoContainer div[class='watermark rightwatermark']");
  1513. rightWatermarkDiv.css({display: 'block'});
  1514. rightWatermarkDiv.parent().get(0).href
  1515. = interfaceConfig.BRAND_WATERMARK_LINK;
  1516. rightWatermarkDiv.get(0).style.backgroundImage
  1517. = "url(images/rightwatermark.png)";
  1518. }
  1519. if (interfaceConfig.SHOW_POWERED_BY) {
  1520. $("#largeVideoContainer>a[class='poweredby']").css({display: 'block'});
  1521. }
  1522. $("#welcome_page").hide();
  1523. VideoLayout.resizeLargeVideoContainer();
  1524. $("#videospace").mousemove(function () {
  1525. return ToolbarToggler.showToolbar();
  1526. });
  1527. // Set the defaults for prompt dialogs.
  1528. jQuery.prompt.setDefaults({persistent: false});
  1529. VideoLayout.init(eventEmitter);
  1530. AudioLevels.init();
  1531. NicknameHandler.init(eventEmitter);
  1532. registerListeners();
  1533. bindEvents();
  1534. setupPrezi();
  1535. setupToolbars();
  1536. setupChat();
  1537. document.title = interfaceConfig.APP_NAME;
  1538. $("#downloadlog").click(function (event) {
  1539. dump(event.target);
  1540. });
  1541. if(config.enableWelcomePage && window.location.pathname == "/" &&
  1542. (!window.localStorage.welcomePageDisabled || window.localStorage.welcomePageDisabled == "false"))
  1543. {
  1544. $("#videoconference_page").hide();
  1545. var setupWelcomePage = require("./welcome_page/WelcomePage");
  1546. setupWelcomePage();
  1547. return;
  1548. }
  1549. $("#welcome_page").hide();
  1550. // Display notice message at the top of the toolbar
  1551. if (config.noticeMessage) {
  1552. $('#noticeText').text(config.noticeMessage);
  1553. $('#notice').css({display: 'block'});
  1554. }
  1555. document.getElementById('largeVideo').volume = 0;
  1556. if (!$('#settings').is(':visible')) {
  1557. console.log('init');
  1558. init();
  1559. } else {
  1560. loginInfo.onsubmit = function (e) {
  1561. if (e.preventDefault) e.preventDefault();
  1562. $('#settings').hide();
  1563. init();
  1564. };
  1565. }
  1566. toastr.options = {
  1567. "closeButton": true,
  1568. "debug": false,
  1569. "positionClass": "notification-bottom-right",
  1570. "onclick": null,
  1571. "showDuration": "300",
  1572. "hideDuration": "1000",
  1573. "timeOut": "2000",
  1574. "extendedTimeOut": "1000",
  1575. "showEasing": "swing",
  1576. "hideEasing": "linear",
  1577. "showMethod": "fadeIn",
  1578. "hideMethod": "fadeOut",
  1579. "reposition": function() {
  1580. if(PanelToggler.isVisible()) {
  1581. $("#toast-container").addClass("notification-bottom-right-center");
  1582. } else {
  1583. $("#toast-container").removeClass("notification-bottom-right-center");
  1584. }
  1585. },
  1586. "newestOnTop": false
  1587. };
  1588. SettingsMenu.init();
  1589. };
  1590. function chatAddError(errorMessage, originalText)
  1591. {
  1592. return Chat.chatAddError(errorMessage, originalText);
  1593. };
  1594. function chatSetSubject(text)
  1595. {
  1596. return Chat.chatSetSubject(text);
  1597. };
  1598. function updateChatConversation(from, displayName, message) {
  1599. return Chat.updateChatConversation(from, displayName, message);
  1600. };
  1601. function onMucJoined(jid, info) {
  1602. Toolbar.updateRoomUrl(window.location.href);
  1603. var meHTML = APP.translation.generateTranslatonHTML("me");
  1604. $("#localNick").html(Strophe.getResourceFromJid(jid) + " (" + meHTML + ")");
  1605. var settings = Settings.getSettings();
  1606. // Add myself to the contact list.
  1607. ContactList.addContact(jid, settings.email || settings.uid);
  1608. // Once we've joined the muc show the toolbar
  1609. ToolbarToggler.showToolbar();
  1610. var displayName = !config.displayJids
  1611. ? info.displayName : Strophe.getResourceFromJid(jid);
  1612. if (displayName)
  1613. onDisplayNameChanged('localVideoContainer', displayName);
  1614. }
  1615. function initEtherpad(name) {
  1616. Etherpad.init(name);
  1617. };
  1618. function onMucMemberLeft(jid) {
  1619. console.log('left.muc', jid);
  1620. var displayName = $('#participant_' + Strophe.getResourceFromJid(jid) +
  1621. '>.displayname').html();
  1622. messageHandler.notify(displayName,'notify.somebody',
  1623. 'disconnected',
  1624. 'notify.disconnected');
  1625. // Need to call this with a slight delay, otherwise the element couldn't be
  1626. // found for some reason.
  1627. // XXX(gp) it works fine without the timeout for me (with Chrome 38).
  1628. window.setTimeout(function () {
  1629. var container = document.getElementById(
  1630. 'participant_' + Strophe.getResourceFromJid(jid));
  1631. if (container) {
  1632. ContactList.removeContact(jid);
  1633. VideoLayout.removeConnectionIndicator(jid);
  1634. // hide here, wait for video to close before removing
  1635. $(container).hide();
  1636. VideoLayout.resizeThumbnails();
  1637. }
  1638. }, 10);
  1639. VideoLayout.participantLeft(jid);
  1640. };
  1641. function onLocalRoleChanged(jid, info, pres, isModerator)
  1642. {
  1643. console.info("My role changed, new role: " + info.role);
  1644. onModeratorStatusChanged(isModerator);
  1645. VideoLayout.showModeratorIndicator();
  1646. if (isModerator) {
  1647. Authentication.closeAuthenticationWindow();
  1648. messageHandler.notify(null, "notify.me",
  1649. 'connected', "notify.moderator");
  1650. }
  1651. }
  1652. function onModeratorStatusChanged(isModerator) {
  1653. Toolbar.showSipCallButton(isModerator);
  1654. Toolbar.showRecordingButton(
  1655. isModerator); //&&
  1656. // FIXME:
  1657. // Recording visible if
  1658. // there are at least 2(+ 1 focus) participants
  1659. //Object.keys(connection.emuc.members).length >= 3);
  1660. if (isModerator && config.etherpad_base) {
  1661. Etherpad.init();
  1662. }
  1663. };
  1664. function onPasswordRequired(callback) {
  1665. // password is required
  1666. Toolbar.lockLockButton();
  1667. var message = '<h2 data-i18n="dialog.passwordRequired">';
  1668. message += APP.translation.translateString(
  1669. "dialog.passwordRequired");
  1670. message += '</h2>' +
  1671. '<input name="lockKey" type="text" data-i18n=' +
  1672. '"[placeholder]dialog.password" placeholder="' +
  1673. APP.translation.translateString("dialog.password") +
  1674. '" autofocus>';
  1675. messageHandler.openTwoButtonDialog(null, null, null, message,
  1676. true,
  1677. "dialog.Ok",
  1678. function (e, v, m, f) {},
  1679. null,
  1680. function (e, v, m, f) {
  1681. if (v) {
  1682. var lockKey = f.lockKey;
  1683. if (lockKey) {
  1684. Toolbar.setSharedKey(lockKey);
  1685. callback(lockKey);
  1686. }
  1687. }
  1688. },
  1689. ':input:first'
  1690. );
  1691. }
  1692. /**
  1693. * The dialpad button is shown iff there is at least one member that supports
  1694. * DTMF (e.g. jigasi).
  1695. */
  1696. function onDtmfSupportChanged(dtmfSupport) {
  1697. //TODO: enable when the UI is ready
  1698. //Toolbar.showDialPadButton(dtmfSupport);
  1699. }
  1700. function onMucMemberJoined(jid, id, displayName) {
  1701. messageHandler.notify(displayName,'notify.somebody',
  1702. 'connected',
  1703. 'notify.connected');
  1704. // Add Peer's container
  1705. VideoLayout.ensurePeerContainerExists(jid,id);
  1706. }
  1707. function onMucPresenceStatus( jid, info) {
  1708. VideoLayout.setPresenceStatus(
  1709. 'participant_' + Strophe.getResourceFromJid(jid), info.status);
  1710. }
  1711. function onMucRoleChanged(role, displayName) {
  1712. VideoLayout.showModeratorIndicator();
  1713. if (role === 'moderator') {
  1714. var messageKey, messageOptions = {};
  1715. if (!displayName) {
  1716. messageKey = "notify.grantedToUnknown";
  1717. }
  1718. else
  1719. {
  1720. messageKey = "notify.grantedTo";
  1721. messageOptions = {to: displayName};
  1722. }
  1723. messageHandler.notify(
  1724. displayName,'notify.somebody',
  1725. 'connected', messageKey,
  1726. messageOptions);
  1727. }
  1728. }
  1729. function onAuthenticationRequired(intervalCallback) {
  1730. Authentication.openAuthenticationDialog(
  1731. roomName, intervalCallback, function () {
  1732. Toolbar.authenticateClicked();
  1733. });
  1734. };
  1735. function onLastNChanged(oldValue, newValue) {
  1736. if (config.muteLocalVideoIfNotInLastN) {
  1737. setVideoMute(!newValue, { 'byUser': false });
  1738. }
  1739. }
  1740. UI.toggleSmileys = function () {
  1741. Chat.toggleSmileys();
  1742. };
  1743. UI.getSettings = function () {
  1744. return Settings.getSettings();
  1745. };
  1746. UI.toggleFilmStrip = function () {
  1747. return BottomToolbar.toggleFilmStrip();
  1748. };
  1749. UI.toggleChat = function () {
  1750. return BottomToolbar.toggleChat();
  1751. };
  1752. UI.toggleContactList = function () {
  1753. return BottomToolbar.toggleContactList();
  1754. };
  1755. UI.inputDisplayNameHandler = function (value) {
  1756. VideoLayout.inputDisplayNameHandler(value);
  1757. };
  1758. UI.getLargeVideoState = function()
  1759. {
  1760. return VideoLayout.getLargeVideoState();
  1761. };
  1762. UI.generateRoomName = function() {
  1763. if(roomName)
  1764. return roomName;
  1765. var roomnode = null;
  1766. var path = window.location.pathname;
  1767. // determinde the room node from the url
  1768. // TODO: just the roomnode or the whole bare jid?
  1769. if (config.getroomnode && typeof config.getroomnode === 'function') {
  1770. // custom function might be responsible for doing the pushstate
  1771. roomnode = config.getroomnode(path);
  1772. } else {
  1773. /* fall back to default strategy
  1774. * this is making assumptions about how the URL->room mapping happens.
  1775. * It currently assumes deployment at root, with a rewrite like the
  1776. * following one (for nginx):
  1777. location ~ ^/([a-zA-Z0-9]+)$ {
  1778. rewrite ^/(.*)$ / break;
  1779. }
  1780. */
  1781. if (path.length > 1) {
  1782. roomnode = path.substr(1).toLowerCase();
  1783. } else {
  1784. var word = RoomNameGenerator.generateRoomWithoutSeparator();
  1785. roomnode = word.toLowerCase();
  1786. window.history.pushState('VideoChat',
  1787. 'Room: ' + word, window.location.pathname + word);
  1788. }
  1789. }
  1790. roomName = roomnode + '@' + config.hosts.muc;
  1791. return roomName;
  1792. };
  1793. UI.connectionIndicatorShowMore = function(id)
  1794. {
  1795. return VideoLayout.connectionIndicators[id].showMore();
  1796. };
  1797. UI.showLoginPopup = function(callback)
  1798. {
  1799. console.log('password is required');
  1800. var message = '<h2 data-i18n="dialog.passwordRequired">';
  1801. message += APP.translation.translateString(
  1802. "dialog.passwordRequired");
  1803. message += '</h2>' +
  1804. '<input name="username" type="text" ' +
  1805. 'placeholder="user@domain.net" autofocus>' +
  1806. '<input name="password" ' +
  1807. 'type="password" data-i18n="[placeholder]dialog.userPassword"' +
  1808. ' placeholder="user password">';
  1809. UI.messageHandler.openTwoButtonDialog(null, null, null, message,
  1810. true,
  1811. "dialog.Ok",
  1812. function (e, v, m, f) {
  1813. if (v) {
  1814. if (f.username !== null && f.password != null) {
  1815. callback(f.username, f.password);
  1816. }
  1817. }
  1818. },
  1819. null, null, ':input:first'
  1820. );
  1821. }
  1822. UI.checkForNicknameAndJoin = function () {
  1823. Authentication.closeAuthenticationDialog();
  1824. Authentication.stopInterval();
  1825. var nick = null;
  1826. if (config.useNicks) {
  1827. nick = window.prompt('Your nickname (optional)');
  1828. }
  1829. APP.xmpp.joinRoom(roomName, config.useNicks, nick);
  1830. };
  1831. function dump(elem, filename) {
  1832. elem = elem.parentNode;
  1833. elem.download = filename || 'meetlog.json';
  1834. elem.href = 'data:application/json;charset=utf-8,\n';
  1835. var data = APP.xmpp.populateData();
  1836. var metadata = {};
  1837. metadata.time = new Date();
  1838. metadata.url = window.location.href;
  1839. metadata.ua = navigator.userAgent;
  1840. var log = APP.xmpp.getLogger();
  1841. if (log) {
  1842. metadata.xmpp = log;
  1843. }
  1844. data.metadata = metadata;
  1845. elem.href += encodeURIComponent(JSON.stringify(data, null, ' '));
  1846. return false;
  1847. }
  1848. UI.getRoomName = function () {
  1849. return roomName;
  1850. };
  1851. /**
  1852. * Mutes/unmutes the local video.
  1853. */
  1854. UI.toggleVideo = function () {
  1855. setVideoMute(!APP.RTC.localVideo.isMuted());
  1856. };
  1857. /**
  1858. * Mutes / unmutes audio for the local participant.
  1859. */
  1860. UI.toggleAudio = function() {
  1861. UI.setAudioMuted(!APP.RTC.localAudio.isMuted());
  1862. };
  1863. /**
  1864. * Sets muted audio state for the local participant.
  1865. */
  1866. UI.setAudioMuted = function (mute) {
  1867. if(!APP.xmpp.setAudioMute(mute, function () {
  1868. VideoLayout.showLocalAudioIndicator(mute);
  1869. UIUtil.buttonClick("#mute", "icon-microphone icon-mic-disabled");
  1870. }))
  1871. {
  1872. // We still click the button.
  1873. UIUtil.buttonClick("#mute", "icon-microphone icon-mic-disabled");
  1874. return;
  1875. }
  1876. }
  1877. UI.addListener = function (type, listener) {
  1878. eventEmitter.on(type, listener);
  1879. }
  1880. UI.clickOnVideo = function (videoNumber) {
  1881. var remoteVideos = $(".videocontainer:not(#mixedstream)");
  1882. if (remoteVideos.length > videoNumber) {
  1883. remoteVideos[videoNumber].click();
  1884. }
  1885. }
  1886. //Used by torture
  1887. UI.showToolbar = function () {
  1888. return ToolbarToggler.showToolbar();
  1889. }
  1890. //Used by torture
  1891. UI.dockToolbar = function (isDock) {
  1892. return ToolbarToggler.dockToolbar(isDock);
  1893. }
  1894. UI.setVideoMuteButtonsState = function (mute) {
  1895. var video = $('#video');
  1896. var communicativeClass = "icon-camera";
  1897. var muteClass = "icon-camera icon-camera-disabled";
  1898. if (mute) {
  1899. video.removeClass(communicativeClass);
  1900. video.addClass(muteClass);
  1901. } else {
  1902. video.removeClass(muteClass);
  1903. video.addClass(communicativeClass);
  1904. }
  1905. }
  1906. module.exports = UI;
  1907. },{"../../service/RTC/RTCEvents":92,"../../service/RTC/StreamEventTypes":94,"../../service/connectionquality/CQEvents":97,"../../service/desktopsharing/DesktopSharingEventTypes":98,"../../service/members/Events":99,"../../service/xmpp/XMPPEvents":101,"./../settings/Settings":40,"./audio_levels/AudioLevels.js":10,"./authentication/Authentication":12,"./avatar/Avatar":14,"./etherpad/Etherpad.js":15,"./prezi/Prezi.js":16,"./side_pannels/SidePanelToggler":18,"./side_pannels/chat/Chat.js":19,"./side_pannels/contactlist/ContactList":23,"./side_pannels/settings/SettingsMenu":24,"./toolbars/BottomToolbar":25,"./toolbars/Toolbar":26,"./toolbars/ToolbarToggler":27,"./util/MessageHandler":29,"./util/NicknameHandler":30,"./util/UIUtil":31,"./videolayout/VideoLayout.js":33,"./welcome_page/RoomnameGenerator":34,"./welcome_page/WelcomePage":35,"events":102}],10:[function(require,module,exports){
  1908. var CanvasUtil = require("./CanvasUtils");
  1909. var ASDrawContext = $('#activeSpeakerAudioLevel')[0].getContext('2d');
  1910. function initActiveSpeakerAudioLevels() {
  1911. var ASRadius = interfaceConfig.ACTIVE_SPEAKER_AVATAR_SIZE / 2;
  1912. var ASCenter = (interfaceConfig.ACTIVE_SPEAKER_AVATAR_SIZE + ASRadius) / 2;
  1913. // Draw a circle.
  1914. ASDrawContext.arc(ASCenter, ASCenter, ASRadius, 0, 2 * Math.PI);
  1915. // Add a shadow around the circle
  1916. ASDrawContext.shadowColor = interfaceConfig.SHADOW_COLOR;
  1917. ASDrawContext.shadowOffsetX = 0;
  1918. ASDrawContext.shadowOffsetY = 0;
  1919. }
  1920. /**
  1921. * The audio Levels plugin.
  1922. */
  1923. var AudioLevels = (function(my) {
  1924. var audioLevelCanvasCache = {};
  1925. my.LOCAL_LEVEL = 'local';
  1926. my.init = function () {
  1927. initActiveSpeakerAudioLevels();
  1928. }
  1929. /**
  1930. * Updates the audio level canvas for the given peerJid. If the canvas
  1931. * didn't exist we create it.
  1932. */
  1933. my.updateAudioLevelCanvas = function (peerJid, VideoLayout) {
  1934. var resourceJid = null;
  1935. var videoSpanId = null;
  1936. if (!peerJid)
  1937. videoSpanId = 'localVideoContainer';
  1938. else {
  1939. resourceJid = Strophe.getResourceFromJid(peerJid);
  1940. videoSpanId = 'participant_' + resourceJid;
  1941. }
  1942. var videoSpan = document.getElementById(videoSpanId);
  1943. if (!videoSpan) {
  1944. if (resourceJid)
  1945. console.error("No video element for jid", resourceJid);
  1946. else
  1947. console.error("No video element for local video.");
  1948. return;
  1949. }
  1950. var audioLevelCanvas = $('#' + videoSpanId + '>canvas');
  1951. var videoSpaceWidth = $('#remoteVideos').width();
  1952. var thumbnailSize = VideoLayout.calculateThumbnailSize(videoSpaceWidth);
  1953. var thumbnailWidth = thumbnailSize[0];
  1954. var thumbnailHeight = thumbnailSize[1];
  1955. if (!audioLevelCanvas || audioLevelCanvas.length === 0) {
  1956. audioLevelCanvas = document.createElement('canvas');
  1957. audioLevelCanvas.className = "audiolevel";
  1958. audioLevelCanvas.style.bottom = "-" + interfaceConfig.CANVAS_EXTRA/2 + "px";
  1959. audioLevelCanvas.style.left = "-" + interfaceConfig.CANVAS_EXTRA/2 + "px";
  1960. resizeAudioLevelCanvas( audioLevelCanvas,
  1961. thumbnailWidth,
  1962. thumbnailHeight);
  1963. videoSpan.appendChild(audioLevelCanvas);
  1964. } else {
  1965. audioLevelCanvas = audioLevelCanvas.get(0);
  1966. resizeAudioLevelCanvas( audioLevelCanvas,
  1967. thumbnailWidth,
  1968. thumbnailHeight);
  1969. }
  1970. };
  1971. /**
  1972. * Updates the audio level UI for the given resourceJid.
  1973. *
  1974. * @param resourceJid the resource jid indicating the video element for
  1975. * which we draw the audio level
  1976. * @param audioLevel the newAudio level to render
  1977. */
  1978. my.updateAudioLevel = function (resourceJid, audioLevel, largeVideoResourceJid) {
  1979. drawAudioLevelCanvas(resourceJid, audioLevel);
  1980. var videoSpanId = getVideoSpanId(resourceJid);
  1981. var audioLevelCanvas = $('#' + videoSpanId + '>canvas').get(0);
  1982. if (!audioLevelCanvas)
  1983. return;
  1984. var drawContext = audioLevelCanvas.getContext('2d');
  1985. var canvasCache = audioLevelCanvasCache[resourceJid];
  1986. drawContext.clearRect (0, 0,
  1987. audioLevelCanvas.width, audioLevelCanvas.height);
  1988. drawContext.drawImage(canvasCache, 0, 0);
  1989. if(resourceJid === AudioLevels.LOCAL_LEVEL) {
  1990. if(!APP.xmpp.myJid()) {
  1991. return;
  1992. }
  1993. resourceJid = APP.xmpp.myResource();
  1994. }
  1995. if(resourceJid === largeVideoResourceJid) {
  1996. window.requestAnimationFrame(function () {
  1997. AudioLevels.updateActiveSpeakerAudioLevel(audioLevel);
  1998. });
  1999. }
  2000. };
  2001. my.updateActiveSpeakerAudioLevel = function(audioLevel) {
  2002. if($("#activeSpeaker").css("visibility") == "hidden")
  2003. return;
  2004. ASDrawContext.clearRect(0, 0, 300, 300);
  2005. if(audioLevel == 0)
  2006. return;
  2007. ASDrawContext.shadowBlur = getShadowLevel(audioLevel);
  2008. // Fill the shape.
  2009. ASDrawContext.fill();
  2010. };
  2011. /**
  2012. * Resizes the given audio level canvas to match the given thumbnail size.
  2013. */
  2014. function resizeAudioLevelCanvas(audioLevelCanvas,
  2015. thumbnailWidth,
  2016. thumbnailHeight) {
  2017. audioLevelCanvas.width = thumbnailWidth + interfaceConfig.CANVAS_EXTRA;
  2018. audioLevelCanvas.height = thumbnailHeight + interfaceConfig.CANVAS_EXTRA;
  2019. }
  2020. /**
  2021. * Draws the audio level canvas into the cached canvas object.
  2022. *
  2023. * @param resourceJid the resource jid indicating the video element for
  2024. * which we draw the audio level
  2025. * @param audioLevel the newAudio level to render
  2026. */
  2027. function drawAudioLevelCanvas(resourceJid, audioLevel) {
  2028. if (!audioLevelCanvasCache[resourceJid]) {
  2029. var videoSpanId = getVideoSpanId(resourceJid);
  2030. var audioLevelCanvasOrig = $('#' + videoSpanId + '>canvas').get(0);
  2031. /*
  2032. * FIXME Testing has shown that audioLevelCanvasOrig may not exist.
  2033. * In such a case, the method CanvasUtil.cloneCanvas may throw an
  2034. * error. Since audio levels are frequently updated, the errors have
  2035. * been observed to pile into the console, strain the CPU.
  2036. */
  2037. if (audioLevelCanvasOrig)
  2038. {
  2039. audioLevelCanvasCache[resourceJid]
  2040. = CanvasUtil.cloneCanvas(audioLevelCanvasOrig);
  2041. }
  2042. }
  2043. var canvas = audioLevelCanvasCache[resourceJid];
  2044. if (!canvas)
  2045. return;
  2046. var drawContext = canvas.getContext('2d');
  2047. drawContext.clearRect(0, 0, canvas.width, canvas.height);
  2048. var shadowLevel = getShadowLevel(audioLevel);
  2049. if (shadowLevel > 0)
  2050. // drawContext, x, y, w, h, r, shadowColor, shadowLevel
  2051. CanvasUtil.drawRoundRectGlow( drawContext,
  2052. interfaceConfig.CANVAS_EXTRA/2, interfaceConfig.CANVAS_EXTRA/2,
  2053. canvas.width - interfaceConfig.CANVAS_EXTRA,
  2054. canvas.height - interfaceConfig.CANVAS_EXTRA,
  2055. interfaceConfig.CANVAS_RADIUS,
  2056. interfaceConfig.SHADOW_COLOR,
  2057. shadowLevel);
  2058. }
  2059. /**
  2060. * Returns the shadow/glow level for the given audio level.
  2061. *
  2062. * @param audioLevel the audio level from which we determine the shadow
  2063. * level
  2064. */
  2065. function getShadowLevel (audioLevel) {
  2066. var shadowLevel = 0;
  2067. if (audioLevel <= 0.3) {
  2068. shadowLevel = Math.round(interfaceConfig.CANVAS_EXTRA/2*(audioLevel/0.3));
  2069. }
  2070. else if (audioLevel <= 0.6) {
  2071. shadowLevel = Math.round(interfaceConfig.CANVAS_EXTRA/2*((audioLevel - 0.3) / 0.3));
  2072. }
  2073. else {
  2074. shadowLevel = Math.round(interfaceConfig.CANVAS_EXTRA/2*((audioLevel - 0.6) / 0.4));
  2075. }
  2076. return shadowLevel;
  2077. }
  2078. /**
  2079. * Returns the video span id corresponding to the given resourceJid or local
  2080. * user.
  2081. */
  2082. function getVideoSpanId(resourceJid) {
  2083. var videoSpanId = null;
  2084. if (resourceJid === AudioLevels.LOCAL_LEVEL
  2085. || (APP.xmpp.myResource() && resourceJid
  2086. === APP.xmpp.myResource()))
  2087. videoSpanId = 'localVideoContainer';
  2088. else
  2089. videoSpanId = 'participant_' + resourceJid;
  2090. return videoSpanId;
  2091. }
  2092. /**
  2093. * Indicates that the remote video has been resized.
  2094. */
  2095. $(document).bind('remotevideo.resized', function (event, width, height) {
  2096. var resized = false;
  2097. $('#remoteVideos>span>canvas').each(function() {
  2098. var canvas = $(this).get(0);
  2099. if (canvas.width !== width + interfaceConfig.CANVAS_EXTRA) {
  2100. canvas.width = width + interfaceConfig.CANVAS_EXTRA;
  2101. resized = true;
  2102. }
  2103. if (canvas.heigh !== height + interfaceConfig.CANVAS_EXTRA) {
  2104. canvas.height = height + interfaceConfig.CANVAS_EXTRA;
  2105. resized = true;
  2106. }
  2107. });
  2108. if (resized)
  2109. Object.keys(audioLevelCanvasCache).forEach(function (resourceJid) {
  2110. audioLevelCanvasCache[resourceJid].width
  2111. = width + interfaceConfig.CANVAS_EXTRA;
  2112. audioLevelCanvasCache[resourceJid].height
  2113. = height + interfaceConfig.CANVAS_EXTRA;
  2114. });
  2115. });
  2116. return my;
  2117. })(AudioLevels || {});
  2118. module.exports = AudioLevels;
  2119. },{"./CanvasUtils":11}],11:[function(require,module,exports){
  2120. /**
  2121. * Utility class for drawing canvas shapes.
  2122. */
  2123. var CanvasUtil = (function(my) {
  2124. /**
  2125. * Draws a round rectangle with a glow. The glowWidth indicates the depth
  2126. * of the glow.
  2127. *
  2128. * @param drawContext the context of the canvas to draw to
  2129. * @param x the x coordinate of the round rectangle
  2130. * @param y the y coordinate of the round rectangle
  2131. * @param w the width of the round rectangle
  2132. * @param h the height of the round rectangle
  2133. * @param glowColor the color of the glow
  2134. * @param glowWidth the width of the glow
  2135. */
  2136. my.drawRoundRectGlow
  2137. = function(drawContext, x, y, w, h, r, glowColor, glowWidth) {
  2138. // Save the previous state of the context.
  2139. drawContext.save();
  2140. if (w < 2 * r) r = w / 2;
  2141. if (h < 2 * r) r = h / 2;
  2142. // Draw a round rectangle.
  2143. drawContext.beginPath();
  2144. drawContext.moveTo(x+r, y);
  2145. drawContext.arcTo(x+w, y, x+w, y+h, r);
  2146. drawContext.arcTo(x+w, y+h, x, y+h, r);
  2147. drawContext.arcTo(x, y+h, x, y, r);
  2148. drawContext.arcTo(x, y, x+w, y, r);
  2149. drawContext.closePath();
  2150. // Add a shadow around the rectangle
  2151. drawContext.shadowColor = glowColor;
  2152. drawContext.shadowBlur = glowWidth;
  2153. drawContext.shadowOffsetX = 0;
  2154. drawContext.shadowOffsetY = 0;
  2155. // Fill the shape.
  2156. drawContext.fill();
  2157. drawContext.save();
  2158. drawContext.restore();
  2159. // 1) Uncomment this line to use Composite Operation, which is doing the
  2160. // same as the clip function below and is also antialiasing the round
  2161. // border, but is said to be less fast performance wise.
  2162. // drawContext.globalCompositeOperation='destination-out';
  2163. drawContext.beginPath();
  2164. drawContext.moveTo(x+r, y);
  2165. drawContext.arcTo(x+w, y, x+w, y+h, r);
  2166. drawContext.arcTo(x+w, y+h, x, y+h, r);
  2167. drawContext.arcTo(x, y+h, x, y, r);
  2168. drawContext.arcTo(x, y, x+w, y, r);
  2169. drawContext.closePath();
  2170. // 2) Uncomment this line to use Composite Operation, which is doing the
  2171. // same as the clip function below and is also antialiasing the round
  2172. // border, but is said to be less fast performance wise.
  2173. // drawContext.fill();
  2174. // Comment these two lines if choosing to do the same with composite
  2175. // operation above 1 and 2.
  2176. drawContext.clip();
  2177. drawContext.clearRect(0, 0, 277, 200);
  2178. // Restore the previous context state.
  2179. drawContext.restore();
  2180. };
  2181. /**
  2182. * Clones the given canvas.
  2183. *
  2184. * @return the new cloned canvas.
  2185. */
  2186. my.cloneCanvas = function (oldCanvas) {
  2187. /*
  2188. * FIXME Testing has shown that oldCanvas may not exist. In such a case,
  2189. * the method CanvasUtil.cloneCanvas may throw an error. Since audio
  2190. * levels are frequently updated, the errors have been observed to pile
  2191. * into the console, strain the CPU.
  2192. */
  2193. if (!oldCanvas)
  2194. return oldCanvas;
  2195. //create a new canvas
  2196. var newCanvas = document.createElement('canvas');
  2197. var context = newCanvas.getContext('2d');
  2198. //set dimensions
  2199. newCanvas.width = oldCanvas.width;
  2200. newCanvas.height = oldCanvas.height;
  2201. //apply the old canvas to the new one
  2202. context.drawImage(oldCanvas, 0, 0);
  2203. //return the new canvas
  2204. return newCanvas;
  2205. };
  2206. return my;
  2207. })(CanvasUtil || {});
  2208. module.exports = CanvasUtil;
  2209. },{}],12:[function(require,module,exports){
  2210. /* global $, APP*/
  2211. var LoginDialog = require('./LoginDialog');
  2212. var Moderator = require('../../xmpp/moderator');
  2213. /* Initial "authentication required" dialog */
  2214. var authDialog = null;
  2215. /* Loop retry ID that wits for other user to create the room */
  2216. var authRetryId = null;
  2217. var authenticationWindow = null;
  2218. var Authentication = {
  2219. openAuthenticationDialog: function (roomName, intervalCallback, callback) {
  2220. // This is the loop that will wait for the room to be created by
  2221. // someone else. 'auth_required.moderator' will bring us back here.
  2222. authRetryId = window.setTimeout(intervalCallback, 5000);
  2223. // Show prompt only if it's not open
  2224. if (authDialog !== null) {
  2225. return;
  2226. }
  2227. // extract room name from 'room@muc.server.net'
  2228. var room = roomName.substr(0, roomName.indexOf('@'));
  2229. var title
  2230. = APP.translation.generateTranslatonHTML("dialog.WaitingForHost");
  2231. var msg
  2232. = APP.translation.generateTranslatonHTML(
  2233. "dialog.WaitForHostMsg", {room: room});
  2234. var buttonTxt
  2235. = APP.translation.generateTranslatonHTML("dialog.IamHost");
  2236. var buttons = [];
  2237. buttons.push({title: buttonTxt, value: "authNow"});
  2238. authDialog = APP.UI.messageHandler.openDialog(
  2239. title,
  2240. msg,
  2241. true,
  2242. buttons,
  2243. function (onSubmitEvent, submitValue) {
  2244. // Do not close the dialog yet
  2245. onSubmitEvent.preventDefault();
  2246. // Open login popup
  2247. if (submitValue === 'authNow') {
  2248. callback();
  2249. }
  2250. }
  2251. );
  2252. },
  2253. closeAuthenticationWindow: function () {
  2254. if (authenticationWindow) {
  2255. authenticationWindow.close();
  2256. authenticationWindow = null;
  2257. }
  2258. },
  2259. xmppAuthenticate: function () {
  2260. var loginDialog = LoginDialog.show(
  2261. function (connection, state) {
  2262. if (!state) {
  2263. // User cancelled
  2264. loginDialog.close();
  2265. return;
  2266. } else if (state == APP.xmpp.Status.CONNECTED) {
  2267. loginDialog.close();
  2268. Authentication.stopInterval();
  2269. Authentication.closeAuthenticationDialog();
  2270. // Close the connection as anonymous one will be used
  2271. // to create the conference. Session-id will authorize
  2272. // the request.
  2273. connection.disconnect();
  2274. var roomName = APP.UI.generateRoomName();
  2275. Moderator.allocateConferenceFocus(roomName, function () {
  2276. // If it's not "on the fly" authentication now join
  2277. // the conference room
  2278. if (!APP.xmpp.getMUCJoined()) {
  2279. APP.UI.checkForNicknameAndJoin();
  2280. }
  2281. });
  2282. }
  2283. }, true);
  2284. },
  2285. focusAuthenticationWindow: function () {
  2286. // If auth window exists just bring it to the front
  2287. if (authenticationWindow) {
  2288. authenticationWindow.focus();
  2289. return;
  2290. }
  2291. },
  2292. closeAuthenticationDialog: function () {
  2293. // Close authentication dialog if opened
  2294. if (authDialog) {
  2295. authDialog.close();
  2296. authDialog = null;
  2297. }
  2298. },
  2299. createAuthenticationWindow: function (callback, url) {
  2300. authenticationWindow = APP.UI.messageHandler.openCenteredPopup(
  2301. url, 910, 660,
  2302. // On closed
  2303. function () {
  2304. // Close authentication dialog if opened
  2305. Authentication.closeAuthenticationDialog();
  2306. callback();
  2307. authenticationWindow = null;
  2308. });
  2309. return authenticationWindow;
  2310. },
  2311. stopInterval: function () {
  2312. // Clear retry interval, so that we don't call 'doJoinAfterFocus' twice
  2313. if (authRetryId) {
  2314. window.clearTimeout(authRetryId);
  2315. authRetryId = null;
  2316. }
  2317. }
  2318. };
  2319. module.exports = Authentication;
  2320. },{"../../xmpp/moderator":55,"./LoginDialog":13}],13:[function(require,module,exports){
  2321. /* global $, APP, config*/
  2322. var XMPP = require('../../xmpp/xmpp');
  2323. var Moderator = require('../../xmpp/moderator');
  2324. //FIXME: use LoginDialog to add retries to XMPP.connect method used when
  2325. // anonymous domain is not enabled
  2326. /**
  2327. * Creates new <tt>Dialog</tt> instance.
  2328. * @param callback <tt>function(Strophe.Connection, Strophe.Status)</tt> called
  2329. * when we either fail to connect or succeed(check Strophe.Status).
  2330. * @param obtainSession <tt>true</tt> if we want to send ConferenceIQ to Jicofo
  2331. * in order to create session-id after the connection is established.
  2332. * @constructor
  2333. */
  2334. function Dialog(callback, obtainSession) {
  2335. var self = this;
  2336. var stop = false;
  2337. var connection = APP.xmpp.createConnection();
  2338. var message = '<h2 data-i18n="dialog.passwordRequired">';
  2339. message += APP.translation.translateString("dialog.passwordRequired");
  2340. message += '</h2>' +
  2341. '<input name="username" type="text" ' +
  2342. 'placeholder="user@domain.net" autofocus>' +
  2343. '<input name="password" ' +
  2344. 'type="password" data-i18n="[placeholder]dialog.userPassword"' +
  2345. ' placeholder="user password">';
  2346. var okButton = APP.translation.generateTranslatonHTML("dialog.Ok");
  2347. var cancelButton = APP.translation.generateTranslatonHTML("dialog.Cancel");
  2348. var states = {
  2349. login: {
  2350. html: message,
  2351. buttons: [
  2352. { title: okButton, value: true},
  2353. { title: cancelButton, value: false}
  2354. ],
  2355. focus: ':input:first',
  2356. submit: function (e, v, m, f) {
  2357. e.preventDefault();
  2358. if (v) {
  2359. var jid = f.username;
  2360. var password = f.password;
  2361. if (jid && password) {
  2362. stop = false;
  2363. connection.reset();
  2364. connDialog.goToState('connecting');
  2365. connection.connect(jid, password, stateHandler);
  2366. }
  2367. } else {
  2368. // User cancelled
  2369. stop = true;
  2370. callback();
  2371. }
  2372. }
  2373. },
  2374. connecting: {
  2375. title: APP.translation.translateString('dialog.connecting'),
  2376. html: '<div id="connectionStatus"></div>',
  2377. buttons: [],
  2378. defaultButton: 0
  2379. },
  2380. finished: {
  2381. title: APP.translation.translateString('dialog.error'),
  2382. html: '<div id="errorMessage"></div>',
  2383. buttons: [
  2384. {
  2385. title: APP.translation.translateString('dialog.retry'),
  2386. value: 'retry'
  2387. },
  2388. {
  2389. title: APP.translation.translateString('dialog.Cancel'),
  2390. value: 'cancel'
  2391. },
  2392. ],
  2393. defaultButton: 0,
  2394. submit: function (e, v, m, f) {
  2395. e.preventDefault();
  2396. if (v === 'retry')
  2397. connDialog.goToState('login');
  2398. else
  2399. callback();
  2400. }
  2401. }
  2402. };
  2403. var connDialog
  2404. = APP.UI.messageHandler.openDialogWithStates(states,
  2405. { persistent: true, closeText: '' }, null);
  2406. var stateHandler = function (status, message) {
  2407. if (stop) {
  2408. return;
  2409. }
  2410. var translateKey = "connection." + XMPP.getStatusString(status);
  2411. var statusStr = APP.translation.translateString(translateKey);
  2412. // Display current state
  2413. var connectionStatus =
  2414. connDialog.getState('connecting').find('#connectionStatus');
  2415. connectionStatus.text(statusStr);
  2416. switch (status) {
  2417. case XMPP.Status.CONNECTED:
  2418. stop = true;
  2419. if (!obtainSession) {
  2420. callback(connection, status);
  2421. return;
  2422. }
  2423. // Obtaining session-id status
  2424. connectionStatus.text(
  2425. APP.translation.translateString(
  2426. 'connection.FETCH_SESSION_ID'));
  2427. // Authenticate with Jicofo and obtain session-id
  2428. var roomName = APP.UI.generateRoomName();
  2429. // Jicofo will return new session-id when connected
  2430. // from authenticated domain
  2431. connection.sendIQ(
  2432. Moderator.createConferenceIq(roomName),
  2433. function (result) {
  2434. connectionStatus.text(
  2435. APP.translation.translateString(
  2436. 'connection.GOT_SESSION_ID'));
  2437. stop = true;
  2438. // Parse session-id
  2439. Moderator.parseSessionId(result);
  2440. callback(connection, status);
  2441. },
  2442. function (error) {
  2443. console.error("Auth on the fly failed", error);
  2444. stop = true;
  2445. var errorMsg =
  2446. APP.translation.translateString(
  2447. 'connection.GET_SESSION_ID_ERROR') +
  2448. $(error).find('>error').attr('code');
  2449. self.displayError(errorMsg);
  2450. connection.disconnect();
  2451. });
  2452. break;
  2453. case XMPP.Status.AUTHFAIL:
  2454. case XMPP.Status.CONNFAIL:
  2455. case XMPP.Status.DISCONNECTED:
  2456. stop = true;
  2457. callback(connection, status);
  2458. var errorMessage = statusStr;
  2459. if (message)
  2460. {
  2461. errorMessage += ': ' + message;
  2462. }
  2463. self.displayError(errorMessage);
  2464. break;
  2465. default:
  2466. break;
  2467. }
  2468. };
  2469. /**
  2470. * Displays error message in 'finished' state which allows either to cancel
  2471. * or retry.
  2472. * @param message the final message to be displayed.
  2473. */
  2474. this.displayError = function (message) {
  2475. var finishedState = connDialog.getState('finished');
  2476. var errorMessageElem = finishedState.find('#errorMessage');
  2477. errorMessageElem.text(message);
  2478. connDialog.goToState('finished');
  2479. };
  2480. /**
  2481. * Closes LoginDialog.
  2482. */
  2483. this.close = function () {
  2484. stop = true;
  2485. connDialog.close();
  2486. };
  2487. }
  2488. var LoginDialog = {
  2489. /**
  2490. * Displays login prompt used to establish new XMPP connection. Given
  2491. * <tt>callback(Strophe.Connection, Strophe.Status)</tt> function will be
  2492. * called when we connect successfully(status === CONNECTED) or when we fail
  2493. * to do so. On connection failure program can call Dialog.close() method in
  2494. * order to cancel or do nothing to let the user retry.
  2495. * @param callback <tt>function(Strophe.Connection, Strophe.Status)</tt>
  2496. * called when we either fail to connect or succeed(check
  2497. * Strophe.Status).
  2498. * @param obtainSession <tt>true</tt> if we want to send ConferenceIQ to
  2499. * Jicofo in order to create session-id after the connection is
  2500. * established.
  2501. * @returns {Dialog}
  2502. */
  2503. show: function (callback, obtainSession) {
  2504. return new Dialog(callback, obtainSession);
  2505. }
  2506. };
  2507. module.exports = LoginDialog;
  2508. },{"../../xmpp/moderator":55,"../../xmpp/xmpp":63}],14:[function(require,module,exports){
  2509. var Settings = require("../../settings/Settings");
  2510. var MediaStreamType = require("../../../service/RTC/MediaStreamTypes");
  2511. var users = {};
  2512. var activeSpeakerJid;
  2513. function setVisibility(selector, show) {
  2514. if (selector && selector.length > 0) {
  2515. selector.css("visibility", show ? "visible" : "hidden");
  2516. }
  2517. }
  2518. function isUserMuted(jid) {
  2519. // XXX(gp) we may want to rename this method to something like
  2520. // isUserStreaming, for example.
  2521. if (jid && jid != APP.xmpp.myJid()) {
  2522. var resource = Strophe.getResourceFromJid(jid);
  2523. if (!require("../videolayout/VideoLayout").isInLastN(resource)) {
  2524. return true;
  2525. }
  2526. }
  2527. if (!APP.RTC.remoteStreams[jid] || !APP.RTC.remoteStreams[jid][MediaStreamType.VIDEO_TYPE]) {
  2528. return null;
  2529. }
  2530. return APP.RTC.remoteStreams[jid][MediaStreamType.VIDEO_TYPE].muted;
  2531. }
  2532. function getGravatarUrl(id, size) {
  2533. if(id === APP.xmpp.myJid() || !id) {
  2534. id = Settings.getSettings().uid;
  2535. }
  2536. return 'https://www.gravatar.com/avatar/' +
  2537. MD5.hexdigest(id.trim().toLowerCase()) +
  2538. "?d=wavatar&size=" + (size || "30");
  2539. }
  2540. var Avatar = {
  2541. /**
  2542. * Sets the user's avatar in the settings menu(if local user), contact list
  2543. * and thumbnail
  2544. * @param jid jid of the user
  2545. * @param id email or userID to be used as a hash
  2546. */
  2547. setUserAvatar: function (jid, id) {
  2548. if (id) {
  2549. if (users[jid] === id) {
  2550. return;
  2551. }
  2552. users[jid] = id;
  2553. }
  2554. var thumbUrl = getGravatarUrl(users[jid] || jid, 100);
  2555. var contactListUrl = getGravatarUrl(users[jid] || jid);
  2556. var resourceJid = Strophe.getResourceFromJid(jid);
  2557. var thumbnail = $('#participant_' + resourceJid);
  2558. var avatar = $('#avatar_' + resourceJid);
  2559. // set the avatar in the settings menu if it is local user and get the
  2560. // local video container
  2561. if (jid === APP.xmpp.myJid()) {
  2562. $('#avatar').get(0).src = thumbUrl;
  2563. thumbnail = $('#localVideoContainer');
  2564. }
  2565. // set the avatar in the contact list
  2566. var contact = $('#' + resourceJid + '>img');
  2567. if (contact && contact.length > 0) {
  2568. contact.get(0).src = contactListUrl;
  2569. }
  2570. // set the avatar in the thumbnail
  2571. if (avatar && avatar.length > 0) {
  2572. avatar[0].src = thumbUrl;
  2573. } else {
  2574. if (thumbnail && thumbnail.length > 0) {
  2575. avatar = document.createElement('img');
  2576. avatar.id = 'avatar_' + resourceJid;
  2577. avatar.className = 'userAvatar';
  2578. avatar.src = thumbUrl;
  2579. thumbnail.append(avatar);
  2580. }
  2581. }
  2582. //if the user is the current active speaker - update the active speaker
  2583. // avatar
  2584. if (jid === activeSpeakerJid) {
  2585. this.updateActiveSpeakerAvatarSrc(jid);
  2586. }
  2587. },
  2588. /**
  2589. * Hides or shows the user's avatar
  2590. * @param jid jid of the user
  2591. * @param show whether we should show the avatar or not
  2592. * video because there is no dominant speaker and no focused speaker
  2593. */
  2594. showUserAvatar: function (jid, show) {
  2595. if (users[jid]) {
  2596. var resourceJid = Strophe.getResourceFromJid(jid);
  2597. var video = $('#participant_' + resourceJid + '>video');
  2598. var avatar = $('#avatar_' + resourceJid);
  2599. if (jid === APP.xmpp.myJid()) {
  2600. video = $('#localVideoWrapper>video');
  2601. }
  2602. if (show === undefined || show === null) {
  2603. show = isUserMuted(jid);
  2604. }
  2605. //if the user is the currently focused, the dominant speaker or if
  2606. //there is no focused and no dominant speaker and the large video is
  2607. //currently shown
  2608. if (activeSpeakerJid === jid && require("../videolayout/VideoLayout").isLargeVideoOnTop()) {
  2609. setVisibility($("#largeVideo"), !show);
  2610. setVisibility($('#activeSpeaker'), show);
  2611. setVisibility(avatar, false);
  2612. setVisibility(video, false);
  2613. } else {
  2614. if (video && video.length > 0) {
  2615. setVisibility(video, !show);
  2616. setVisibility(avatar, show);
  2617. }
  2618. }
  2619. }
  2620. },
  2621. /**
  2622. * Updates the src of the active speaker avatar
  2623. * @param jid of the current active speaker
  2624. */
  2625. updateActiveSpeakerAvatarSrc: function (jid) {
  2626. if (!jid) {
  2627. jid = APP.xmpp.findJidFromResource(
  2628. require("../videolayout/VideoLayout").getLargeVideoState().userResourceJid);
  2629. }
  2630. var avatar = $("#activeSpeakerAvatar")[0];
  2631. var url = getGravatarUrl(users[jid],
  2632. interfaceConfig.ACTIVE_SPEAKER_AVATAR_SIZE);
  2633. if (jid === activeSpeakerJid && avatar.src === url) {
  2634. return;
  2635. }
  2636. activeSpeakerJid = jid;
  2637. var isMuted = isUserMuted(jid);
  2638. if (jid && isMuted !== null) {
  2639. avatar.src = url;
  2640. setVisibility($("#largeVideo"), !isMuted);
  2641. Avatar.showUserAvatar(jid, isMuted);
  2642. }
  2643. }
  2644. };
  2645. module.exports = Avatar;
  2646. },{"../../../service/RTC/MediaStreamTypes":90,"../../settings/Settings":40,"../videolayout/VideoLayout":33}],15:[function(require,module,exports){
  2647. /* global $, config,
  2648. setLargeVideoVisible, Util */
  2649. var VideoLayout = require("../videolayout/VideoLayout");
  2650. var Prezi = require("../prezi/Prezi");
  2651. var UIUtil = require("../util/UIUtil");
  2652. var etherpadName = null;
  2653. var etherpadIFrame = null;
  2654. var domain = null;
  2655. var options = "?showControls=true&showChat=false&showLineNumbers=true&useMonospaceFont=false";
  2656. /**
  2657. * Resizes the etherpad.
  2658. */
  2659. function resize() {
  2660. if ($('#etherpad>iframe').length) {
  2661. var remoteVideos = $('#remoteVideos');
  2662. var availableHeight
  2663. = window.innerHeight - remoteVideos.outerHeight();
  2664. var availableWidth = UIUtil.getAvailableVideoWidth();
  2665. $('#etherpad>iframe').width(availableWidth);
  2666. $('#etherpad>iframe').height(availableHeight);
  2667. }
  2668. }
  2669. /**
  2670. * Shares the Etherpad name with other participants.
  2671. */
  2672. function shareEtherpad() {
  2673. APP.xmpp.addToPresence("etherpad", etherpadName);
  2674. }
  2675. /**
  2676. * Creates the Etherpad button and adds it to the toolbar.
  2677. */
  2678. function enableEtherpadButton() {
  2679. if (!$('#etherpadButton').is(":visible"))
  2680. $('#etherpadButton').css({display: 'inline-block'});
  2681. }
  2682. /**
  2683. * Creates the IFrame for the etherpad.
  2684. */
  2685. function createIFrame() {
  2686. etherpadIFrame = document.createElement('iframe');
  2687. etherpadIFrame.src = domain + etherpadName + options;
  2688. etherpadIFrame.frameBorder = 0;
  2689. etherpadIFrame.scrolling = "no";
  2690. etherpadIFrame.width = $('#largeVideoContainer').width() || 640;
  2691. etherpadIFrame.height = $('#largeVideoContainer').height() || 480;
  2692. etherpadIFrame.setAttribute('style', 'visibility: hidden;');
  2693. document.getElementById('etherpad').appendChild(etherpadIFrame);
  2694. etherpadIFrame.onload = function() {
  2695. document.domain = document.domain;
  2696. bubbleIframeMouseMove(etherpadIFrame);
  2697. setTimeout(function() {
  2698. // the iframes inside of the etherpad are
  2699. // not yet loaded when the etherpad iframe is loaded
  2700. var outer = etherpadIFrame.
  2701. contentDocument.getElementsByName("ace_outer")[0];
  2702. bubbleIframeMouseMove(outer);
  2703. var inner = outer.
  2704. contentDocument.getElementsByName("ace_inner")[0];
  2705. bubbleIframeMouseMove(inner);
  2706. }, 2000);
  2707. };
  2708. }
  2709. function bubbleIframeMouseMove(iframe){
  2710. var existingOnMouseMove = iframe.contentWindow.onmousemove;
  2711. iframe.contentWindow.onmousemove = function(e){
  2712. if(existingOnMouseMove) existingOnMouseMove(e);
  2713. var evt = document.createEvent("MouseEvents");
  2714. var boundingClientRect = iframe.getBoundingClientRect();
  2715. evt.initMouseEvent(
  2716. "mousemove",
  2717. true, // bubbles
  2718. false, // not cancelable
  2719. window,
  2720. e.detail,
  2721. e.screenX,
  2722. e.screenY,
  2723. e.clientX + boundingClientRect.left,
  2724. e.clientY + boundingClientRect.top,
  2725. e.ctrlKey,
  2726. e.altKey,
  2727. e.shiftKey,
  2728. e.metaKey,
  2729. e.button,
  2730. null // no related element
  2731. );
  2732. iframe.dispatchEvent(evt);
  2733. };
  2734. }
  2735. /**
  2736. * On video selected event.
  2737. */
  2738. $(document).bind('video.selected', function (event, isPresentation) {
  2739. if (config.etherpad_base && etherpadIFrame && etherpadIFrame.style.visibility !== 'hidden')
  2740. Etherpad.toggleEtherpad(isPresentation);
  2741. });
  2742. var Etherpad = {
  2743. /**
  2744. * Initializes the etherpad.
  2745. */
  2746. init: function (name) {
  2747. if (config.etherpad_base && !etherpadName) {
  2748. domain = config.etherpad_base;
  2749. if (!name) {
  2750. // In case we're the focus we generate the name.
  2751. etherpadName = Math.random().toString(36).substring(7) +
  2752. '_' + (new Date().getTime()).toString();
  2753. shareEtherpad();
  2754. }
  2755. else
  2756. etherpadName = name;
  2757. enableEtherpadButton();
  2758. /**
  2759. * Resizes the etherpad, when the window is resized.
  2760. */
  2761. $(window).resize(function () {
  2762. resize();
  2763. });
  2764. }
  2765. },
  2766. /**
  2767. * Opens/hides the Etherpad.
  2768. */
  2769. toggleEtherpad: function (isPresentation) {
  2770. if (!etherpadIFrame)
  2771. createIFrame();
  2772. var largeVideo = null;
  2773. if (Prezi.isPresentationVisible())
  2774. largeVideo = $('#presentation>iframe');
  2775. else
  2776. largeVideo = $('#largeVideo');
  2777. if ($('#etherpad>iframe').css('visibility') === 'hidden') {
  2778. $('#activeSpeaker').css('visibility', 'hidden');
  2779. largeVideo.fadeOut(300, function () {
  2780. if (Prezi.isPresentationVisible()) {
  2781. largeVideo.css({opacity: '0'});
  2782. } else {
  2783. VideoLayout.setLargeVideoVisible(false);
  2784. }
  2785. });
  2786. $('#etherpad>iframe').fadeIn(300, function () {
  2787. document.body.style.background = '#eeeeee';
  2788. $('#etherpad>iframe').css({visibility: 'visible'});
  2789. $('#etherpad').css({zIndex: 2});
  2790. });
  2791. }
  2792. else if ($('#etherpad>iframe')) {
  2793. $('#etherpad>iframe').fadeOut(300, function () {
  2794. $('#etherpad>iframe').css({visibility: 'hidden'});
  2795. $('#etherpad').css({zIndex: 0});
  2796. document.body.style.background = 'black';
  2797. });
  2798. if (!isPresentation) {
  2799. $('#largeVideo').fadeIn(300, function () {
  2800. VideoLayout.setLargeVideoVisible(true);
  2801. });
  2802. }
  2803. }
  2804. resize();
  2805. },
  2806. isVisible: function() {
  2807. var etherpadIframe = $('#etherpad>iframe');
  2808. return etherpadIframe && etherpadIframe.is(':visible');
  2809. }
  2810. };
  2811. module.exports = Etherpad;
  2812. },{"../prezi/Prezi":16,"../util/UIUtil":31,"../videolayout/VideoLayout":33}],16:[function(require,module,exports){
  2813. var ToolbarToggler = require("../toolbars/ToolbarToggler");
  2814. var UIUtil = require("../util/UIUtil");
  2815. var VideoLayout = require("../videolayout/VideoLayout");
  2816. var messageHandler = require("../util/MessageHandler");
  2817. var PreziPlayer = require("./PreziPlayer");
  2818. var preziPlayer = null;
  2819. var Prezi = {
  2820. /**
  2821. * Reloads the current presentation.
  2822. */
  2823. reloadPresentation: function() {
  2824. var iframe = document.getElementById(preziPlayer.options.preziId);
  2825. iframe.src = iframe.src;
  2826. },
  2827. /**
  2828. * Returns <tt>true</tt> if the presentation is visible, <tt>false</tt> -
  2829. * otherwise.
  2830. */
  2831. isPresentationVisible: function () {
  2832. return ($('#presentation>iframe') != null
  2833. && $('#presentation>iframe').css('opacity') == 1);
  2834. },
  2835. /**
  2836. * Opens the Prezi dialog, from which the user could choose a presentation
  2837. * to load.
  2838. */
  2839. openPreziDialog: function() {
  2840. var myprezi = APP.xmpp.getPrezi();
  2841. if (myprezi) {
  2842. messageHandler.openTwoButtonDialog("dialog.removePreziTitle",
  2843. null,
  2844. "dialog.removePreziMsg",
  2845. null,
  2846. false,
  2847. "dialog.Remove",
  2848. function(e,v,m,f) {
  2849. if(v) {
  2850. APP.xmpp.removePreziFromPresence();
  2851. }
  2852. }
  2853. );
  2854. }
  2855. else if (preziPlayer != null) {
  2856. messageHandler.openTwoButtonDialog("dialog.sharePreziTitle",
  2857. null, "dialog.sharePreziMsg",
  2858. null,
  2859. false,
  2860. "dialog.Ok",
  2861. function(e,v,m,f) {
  2862. $.prompt.close();
  2863. }
  2864. );
  2865. }
  2866. else {
  2867. var html = APP.translation.generateTranslatonHTML(
  2868. "dialog.sharePreziTitle");
  2869. var cancelButton = APP.translation.generateTranslatonHTML(
  2870. "dialog.Cancel");
  2871. var shareButton = APP.translation.generateTranslatonHTML(
  2872. "dialog.Share");
  2873. var backButton = APP.translation.generateTranslatonHTML(
  2874. "dialog.Back");
  2875. var buttons = [];
  2876. var buttons1 = [];
  2877. // Cancel button to both states
  2878. buttons.push({title: cancelButton, value: false});
  2879. buttons1.push({title: cancelButton, value: false});
  2880. // Share button
  2881. buttons.push({title: shareButton, value: true});
  2882. // Back button
  2883. buttons1.push({title: backButton, value: true});
  2884. var linkError = APP.translation.generateTranslatonHTML(
  2885. "dialog.preziLinkError");
  2886. var defaultUrl = APP.translation.translateString("defaultPreziLink",
  2887. {url: "http://prezi.com/wz7vhjycl7e6/my-prezi"});
  2888. var openPreziState = {
  2889. state0: {
  2890. html: '<h2>' + html + '</h2>' +
  2891. '<input name="preziUrl" type="text" ' +
  2892. 'data-i18n="[placeholder]defaultPreziLink" data-i18n-options=\'' +
  2893. JSON.stringify({"url": "http://prezi.com/wz7vhjycl7e6/my-prezi"}) +
  2894. '\' placeholder="' + defaultUrl + '" autofocus>',
  2895. persistent: false,
  2896. buttons: buttons,
  2897. focus: ':input:first',
  2898. defaultButton: 0,
  2899. submit: function (e, v, m, f) {
  2900. e.preventDefault();
  2901. if(v)
  2902. {
  2903. var preziUrl = f.preziUrl;
  2904. if (preziUrl)
  2905. {
  2906. var urlValue
  2907. = encodeURI(UIUtil.escapeHtml(preziUrl));
  2908. if (urlValue.indexOf('http://prezi.com/') != 0
  2909. && urlValue.indexOf('https://prezi.com/') != 0)
  2910. {
  2911. $.prompt.goToState('state1');
  2912. return false;
  2913. }
  2914. else {
  2915. var presIdTmp = urlValue.substring(
  2916. urlValue.indexOf("prezi.com/") + 10);
  2917. if (!isAlphanumeric(presIdTmp)
  2918. || presIdTmp.indexOf('/') < 2) {
  2919. $.prompt.goToState('state1');
  2920. return false;
  2921. }
  2922. else {
  2923. APP.xmpp.addToPresence("prezi", urlValue);
  2924. $.prompt.close();
  2925. }
  2926. }
  2927. }
  2928. }
  2929. else
  2930. $.prompt.close();
  2931. }
  2932. },
  2933. state1: {
  2934. html: '<h2>' + html + '</h2>' +
  2935. linkError,
  2936. persistent: false,
  2937. buttons: buttons1,
  2938. focus: ':input:first',
  2939. defaultButton: 1,
  2940. submit: function (e, v, m, f) {
  2941. e.preventDefault();
  2942. if (v === 0)
  2943. $.prompt.close();
  2944. else
  2945. $.prompt.goToState('state0');
  2946. }
  2947. }
  2948. };
  2949. messageHandler.openDialogWithStates(openPreziState);
  2950. }
  2951. }
  2952. };
  2953. /**
  2954. * A new presentation has been added.
  2955. *
  2956. * @param event the event indicating the add of a presentation
  2957. * @param jid the jid from which the presentation was added
  2958. * @param presUrl url of the presentation
  2959. * @param currentSlide the current slide to which we should move
  2960. */
  2961. function presentationAdded(event, jid, presUrl, currentSlide) {
  2962. console.log("presentation added", presUrl);
  2963. var presId = getPresentationId(presUrl);
  2964. var elementId = 'participant_'
  2965. + Strophe.getResourceFromJid(jid)
  2966. + '_' + presId;
  2967. // We explicitly don't specify the peer jid here, because we don't want
  2968. // this video to be dealt with as a peer related one (for example we
  2969. // don't want to show a mute/kick menu for this one, etc.).
  2970. VideoLayout.addRemoteVideoContainer(null, elementId);
  2971. VideoLayout.resizeThumbnails();
  2972. var controlsEnabled = false;
  2973. if (jid === APP.xmpp.myJid())
  2974. controlsEnabled = true;
  2975. setPresentationVisible(true);
  2976. $('#largeVideoContainer').hover(
  2977. function (event) {
  2978. if (Prezi.isPresentationVisible()) {
  2979. var reloadButtonRight = window.innerWidth
  2980. - $('#presentation>iframe').offset().left
  2981. - $('#presentation>iframe').width();
  2982. $('#reloadPresentation').css({ right: reloadButtonRight,
  2983. display:'inline-block'});
  2984. }
  2985. },
  2986. function (event) {
  2987. if (!Prezi.isPresentationVisible())
  2988. $('#reloadPresentation').css({display:'none'});
  2989. else {
  2990. var e = event.toElement || event.relatedTarget;
  2991. if (e && e.id != 'reloadPresentation' && e.id != 'header')
  2992. $('#reloadPresentation').css({display:'none'});
  2993. }
  2994. });
  2995. preziPlayer = new PreziPlayer(
  2996. 'presentation',
  2997. {preziId: presId,
  2998. width: getPresentationWidth(),
  2999. height: getPresentationHeihgt(),
  3000. controls: controlsEnabled,
  3001. debug: true
  3002. });
  3003. $('#presentation>iframe').attr('id', preziPlayer.options.preziId);
  3004. preziPlayer.on(PreziPlayer.EVENT_STATUS, function(event) {
  3005. console.log("prezi status", event.value);
  3006. if (event.value == PreziPlayer.STATUS_CONTENT_READY) {
  3007. if (jid != APP.xmpp.myJid())
  3008. preziPlayer.flyToStep(currentSlide);
  3009. }
  3010. });
  3011. preziPlayer.on(PreziPlayer.EVENT_CURRENT_STEP, function(event) {
  3012. console.log("event value", event.value);
  3013. APP.xmpp.addToPresence("preziSlide", event.value);
  3014. });
  3015. $("#" + elementId).css( 'background-image',
  3016. 'url(../images/avatarprezi.png)');
  3017. $("#" + elementId).click(
  3018. function () {
  3019. setPresentationVisible(true);
  3020. }
  3021. );
  3022. };
  3023. /**
  3024. * A presentation has been removed.
  3025. *
  3026. * @param event the event indicating the remove of a presentation
  3027. * @param jid the jid for which the presentation was removed
  3028. * @param the url of the presentation
  3029. */
  3030. function presentationRemoved(event, jid, presUrl) {
  3031. console.log('presentation removed', presUrl);
  3032. var presId = getPresentationId(presUrl);
  3033. setPresentationVisible(false);
  3034. $('#participant_'
  3035. + Strophe.getResourceFromJid(jid)
  3036. + '_' + presId).remove();
  3037. $('#presentation>iframe').remove();
  3038. if (preziPlayer != null) {
  3039. preziPlayer.destroy();
  3040. preziPlayer = null;
  3041. }
  3042. };
  3043. /**
  3044. * Indicates if the given string is an alphanumeric string.
  3045. * Note that some special characters are also allowed (-, _ , /, &, ?, =, ;) for the
  3046. * purpose of checking URIs.
  3047. */
  3048. function isAlphanumeric(unsafeText) {
  3049. var regex = /^[a-z0-9-_\/&\?=;]+$/i;
  3050. return regex.test(unsafeText);
  3051. }
  3052. /**
  3053. * Returns the presentation id from the given url.
  3054. */
  3055. function getPresentationId (presUrl) {
  3056. var presIdTmp = presUrl.substring(presUrl.indexOf("prezi.com/") + 10);
  3057. return presIdTmp.substring(0, presIdTmp.indexOf('/'));
  3058. }
  3059. /**
  3060. * Returns the presentation width.
  3061. */
  3062. function getPresentationWidth() {
  3063. var availableWidth = UIUtil.getAvailableVideoWidth();
  3064. var availableHeight = getPresentationHeihgt();
  3065. var aspectRatio = 16.0 / 9.0;
  3066. if (availableHeight < availableWidth / aspectRatio) {
  3067. availableWidth = Math.floor(availableHeight * aspectRatio);
  3068. }
  3069. return availableWidth;
  3070. }
  3071. /**
  3072. * Returns the presentation height.
  3073. */
  3074. function getPresentationHeihgt() {
  3075. var remoteVideos = $('#remoteVideos');
  3076. return window.innerHeight - remoteVideos.outerHeight();
  3077. }
  3078. /**
  3079. * Resizes the presentation iframe.
  3080. */
  3081. function resize() {
  3082. if ($('#presentation>iframe')) {
  3083. $('#presentation>iframe').width(getPresentationWidth());
  3084. $('#presentation>iframe').height(getPresentationHeihgt());
  3085. }
  3086. }
  3087. /**
  3088. * Shows/hides a presentation.
  3089. */
  3090. function setPresentationVisible(visible) {
  3091. var prezi = $('#presentation>iframe');
  3092. if (visible) {
  3093. // Trigger the video.selected event to indicate a change in the
  3094. // large video.
  3095. $(document).trigger("video.selected", [true]);
  3096. $('#largeVideo').fadeOut(300);
  3097. prezi.fadeIn(300, function() {
  3098. prezi.css({opacity:'1'});
  3099. ToolbarToggler.dockToolbar(true);
  3100. VideoLayout.setLargeVideoVisible(false);
  3101. });
  3102. $('#activeSpeaker').css('visibility', 'hidden');
  3103. }
  3104. else {
  3105. if (prezi.css('opacity') == '1') {
  3106. prezi.fadeOut(300, function () {
  3107. prezi.css({opacity:'0'});
  3108. $('#reloadPresentation').css({display:'none'});
  3109. $('#largeVideo').fadeIn(300, function() {
  3110. VideoLayout.setLargeVideoVisible(true);
  3111. ToolbarToggler.dockToolbar(false);
  3112. });
  3113. });
  3114. }
  3115. }
  3116. }
  3117. /**
  3118. * Presentation has been removed.
  3119. */
  3120. $(document).bind('presentationremoved.muc', presentationRemoved);
  3121. /**
  3122. * Presentation has been added.
  3123. */
  3124. $(document).bind('presentationadded.muc', presentationAdded);
  3125. /*
  3126. * Indicates presentation slide change.
  3127. */
  3128. $(document).bind('gotoslide.muc', function (event, jid, presUrl, current) {
  3129. if (preziPlayer && preziPlayer.getCurrentStep() != current) {
  3130. preziPlayer.flyToStep(current);
  3131. var animationStepsArray = preziPlayer.getAnimationCountOnSteps();
  3132. for (var i = 0; i < parseInt(animationStepsArray[current]); i++) {
  3133. preziPlayer.flyToStep(current, i);
  3134. }
  3135. }
  3136. });
  3137. /**
  3138. * On video selected event.
  3139. */
  3140. $(document).bind('video.selected', function (event, isPresentation) {
  3141. if (!isPresentation && $('#presentation>iframe')) {
  3142. setPresentationVisible(false);
  3143. }
  3144. });
  3145. $(window).resize(function () {
  3146. resize();
  3147. });
  3148. module.exports = Prezi;
  3149. },{"../toolbars/ToolbarToggler":27,"../util/MessageHandler":29,"../util/UIUtil":31,"../videolayout/VideoLayout":33,"./PreziPlayer":17}],17:[function(require,module,exports){
  3150. (function() {
  3151. "use strict";
  3152. var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; };
  3153. window.PreziPlayer = (function() {
  3154. PreziPlayer.API_VERSION = 1;
  3155. PreziPlayer.CURRENT_STEP = 'currentStep';
  3156. PreziPlayer.CURRENT_ANIMATION_STEP = 'currentAnimationStep';
  3157. PreziPlayer.CURRENT_OBJECT = 'currentObject';
  3158. PreziPlayer.STATUS_LOADING = 'loading';
  3159. PreziPlayer.STATUS_READY = 'ready';
  3160. PreziPlayer.STATUS_CONTENT_READY = 'contentready';
  3161. PreziPlayer.EVENT_CURRENT_STEP = "currentStepChange";
  3162. PreziPlayer.EVENT_CURRENT_ANIMATION_STEP = "currentAnimationStepChange";
  3163. PreziPlayer.EVENT_CURRENT_OBJECT = "currentObjectChange";
  3164. PreziPlayer.EVENT_STATUS = "statusChange";
  3165. PreziPlayer.EVENT_PLAYING = "isAutoPlayingChange";
  3166. PreziPlayer.EVENT_IS_MOVING = "isMovingChange";
  3167. PreziPlayer.domain = "https://prezi.com";
  3168. PreziPlayer.path = "/player/";
  3169. PreziPlayer.players = {};
  3170. PreziPlayer.binded_methods = ['changesHandler'];
  3171. PreziPlayer.createMultiplePlayers = function(optionArray){
  3172. for(var i=0; i<optionArray.length; i++) {
  3173. var optionSet = optionArray[i];
  3174. new PreziPlayer(optionSet.id, optionSet);
  3175. };
  3176. };
  3177. PreziPlayer.messageReceived = function(event){
  3178. var message, item, player;
  3179. try {
  3180. message = JSON.parse(event.data);
  3181. if (message.id && (player = PreziPlayer.players[message.id])) {
  3182. if (player.options.debug === true) {
  3183. if (console && console.log)
  3184. console.log('received', message);
  3185. }
  3186. if (message.type === "changes") {
  3187. player.changesHandler(message);
  3188. }
  3189. for (var i = 0; i < player.callbacks.length; i++) {
  3190. item = player.callbacks[i];
  3191. if (item && message.type === item.event) {
  3192. item.callback(message);
  3193. }
  3194. }
  3195. }
  3196. } catch (e) { }
  3197. };
  3198. function PreziPlayer(id, options) {
  3199. var params, paramString = "", _this = this;
  3200. if (PreziPlayer.players[id]){
  3201. PreziPlayer.players[id].destroy();
  3202. }
  3203. for(var i=0; i<PreziPlayer.binded_methods.length; i++) {
  3204. var method_name = PreziPlayer.binded_methods[i];
  3205. _this[method_name] = __bind(_this[method_name], _this);
  3206. };
  3207. options = options || {};
  3208. this.options = options;
  3209. this.values = {'status': PreziPlayer.STATUS_LOADING};
  3210. this.values[PreziPlayer.CURRENT_STEP] = 0;
  3211. this.values[PreziPlayer.CURRENT_ANIMATION_STEP] = 0;
  3212. this.values[PreziPlayer.CURRENT_OBJECT] = null;
  3213. this.callbacks = [];
  3214. this.id = id;
  3215. this.embedTo = document.getElementById(id);
  3216. if (!this.embedTo) {
  3217. throw "The element id is not available.";
  3218. }
  3219. this.iframe = document.createElement('iframe');
  3220. params = [
  3221. { name: 'oid', value: options.preziId },
  3222. { name: 'explorable', value: options.explorable ? 1 : 0 },
  3223. { name: 'controls', value: options.controls ? 1 : 0 }
  3224. ];
  3225. for(var i=0; i<params.length; i++) {
  3226. var param = params[i];
  3227. paramString += (i===0 ? "?" : "&") + param.name + "=" + param.value;
  3228. };
  3229. this.iframe.src = PreziPlayer.domain + PreziPlayer.path + paramString;
  3230. this.iframe.frameBorder = 0;
  3231. this.iframe.scrolling = "no";
  3232. this.iframe.width = options.width || 640;
  3233. this.iframe.height = options.height || 480;
  3234. this.embedTo.innerHTML = '';
  3235. // JITSI: IN CASE SOMETHING GOES WRONG.
  3236. try {
  3237. this.embedTo.appendChild(this.iframe);
  3238. }
  3239. catch (err) {
  3240. console.log("CATCH ERROR");
  3241. }
  3242. // JITSI: Increase interval from 200 to 500, which fixes prezi
  3243. // crashes for us.
  3244. this.initPollInterval = setInterval(function(){
  3245. _this.sendMessage({'action': 'init'});
  3246. }, 500);
  3247. PreziPlayer.players[id] = this;
  3248. }
  3249. PreziPlayer.prototype.changesHandler = function(message) {
  3250. var key, value, j, item;
  3251. if (this.initPollInterval) {
  3252. clearInterval(this.initPollInterval);
  3253. this.initPollInterval = false;
  3254. }
  3255. for (key in message.data) {
  3256. if (message.data.hasOwnProperty(key)){
  3257. value = message.data[key];
  3258. this.values[key] = value;
  3259. for (j=0; j<this.callbacks.length; j++) {
  3260. item = this.callbacks[j];
  3261. if (item && item.event === key + "Change"){
  3262. item.callback({type: item.event, value: value});
  3263. }
  3264. }
  3265. }
  3266. }
  3267. };
  3268. PreziPlayer.prototype.destroy = function() {
  3269. if (this.initPollInterval) {
  3270. clearInterval(this.initPollInterval);
  3271. this.initPollInterval = false;
  3272. }
  3273. this.embedTo.innerHTML = '';
  3274. };
  3275. PreziPlayer.prototype.sendMessage = function(message) {
  3276. if (this.options.debug === true) {
  3277. if (console && console.log) console.log('sent', message);
  3278. }
  3279. message.version = PreziPlayer.API_VERSION;
  3280. message.id = this.id;
  3281. return this.iframe.contentWindow.postMessage(JSON.stringify(message), '*');
  3282. };
  3283. PreziPlayer.prototype.nextStep = /* nextStep is DEPRECATED */
  3284. PreziPlayer.prototype.flyToNextStep = function() {
  3285. return this.sendMessage({
  3286. 'action': 'present',
  3287. 'data': ['moveToNextStep']
  3288. });
  3289. };
  3290. PreziPlayer.prototype.previousStep = /* previousStep is DEPRECATED */
  3291. PreziPlayer.prototype.flyToPreviousStep = function() {
  3292. return this.sendMessage({
  3293. 'action': 'present',
  3294. 'data': ['moveToPrevStep']
  3295. });
  3296. };
  3297. PreziPlayer.prototype.toStep = /* toStep is DEPRECATED */
  3298. PreziPlayer.prototype.flyToStep = function(step, animation_step) {
  3299. var obj = this;
  3300. // check animation_step
  3301. if (animation_step > 0 &&
  3302. obj.values.animationCountOnSteps &&
  3303. obj.values.animationCountOnSteps[step] <= animation_step) {
  3304. animation_step = obj.values.animationCountOnSteps[step];
  3305. }
  3306. // jump to animation steps by calling flyToNextStep()
  3307. function doAnimationSteps() {
  3308. if (obj.values.isMoving == true) {
  3309. setTimeout(doAnimationSteps, 100); // wait until the flight ends
  3310. return;
  3311. }
  3312. while (animation_step-- > 0) {
  3313. obj.flyToNextStep(); // do the animation steps
  3314. }
  3315. }
  3316. setTimeout(doAnimationSteps, 200); // 200ms is the internal "reporting" time
  3317. // jump to the step
  3318. return this.sendMessage({
  3319. 'action': 'present',
  3320. 'data': ['moveToStep', step]
  3321. });
  3322. };
  3323. PreziPlayer.prototype.toObject = /* toObject is DEPRECATED */
  3324. PreziPlayer.prototype.flyToObject = function(objectId) {
  3325. return this.sendMessage({
  3326. 'action': 'present',
  3327. 'data': ['moveToObject', objectId]
  3328. });
  3329. };
  3330. PreziPlayer.prototype.play = function(defaultDelay) {
  3331. return this.sendMessage({
  3332. 'action': 'present',
  3333. 'data': ['startAutoPlay', defaultDelay]
  3334. });
  3335. };
  3336. PreziPlayer.prototype.stop = function() {
  3337. return this.sendMessage({
  3338. 'action': 'present',
  3339. 'data': ['stopAutoPlay']
  3340. });
  3341. };
  3342. PreziPlayer.prototype.pause = function(defaultDelay) {
  3343. return this.sendMessage({
  3344. 'action': 'present',
  3345. 'data': ['pauseAutoPlay', defaultDelay]
  3346. });
  3347. };
  3348. PreziPlayer.prototype.getCurrentStep = function() {
  3349. return this.values.currentStep;
  3350. };
  3351. PreziPlayer.prototype.getCurrentAnimationStep = function() {
  3352. return this.values.currentAnimationStep;
  3353. };
  3354. PreziPlayer.prototype.getCurrentObject = function() {
  3355. return this.values.currentObject;
  3356. };
  3357. PreziPlayer.prototype.getStatus = function() {
  3358. return this.values.status;
  3359. };
  3360. PreziPlayer.prototype.isPlaying = function() {
  3361. return this.values.isAutoPlaying;
  3362. };
  3363. PreziPlayer.prototype.getStepCount = function() {
  3364. return this.values.stepCount;
  3365. };
  3366. PreziPlayer.prototype.getAnimationCountOnSteps = function() {
  3367. return this.values.animationCountOnSteps;
  3368. };
  3369. PreziPlayer.prototype.getTitle = function() {
  3370. return this.values.title;
  3371. };
  3372. PreziPlayer.prototype.setDimensions = function(dims) {
  3373. for (var parameter in dims) {
  3374. this.iframe[parameter] = dims[parameter];
  3375. }
  3376. }
  3377. PreziPlayer.prototype.getDimensions = function() {
  3378. return {
  3379. width: parseInt(this.iframe.width, 10),
  3380. height: parseInt(this.iframe.height, 10)
  3381. }
  3382. }
  3383. PreziPlayer.prototype.on = function(event, callback) {
  3384. this.callbacks.push({
  3385. event: event,
  3386. callback: callback
  3387. });
  3388. };
  3389. PreziPlayer.prototype.off = function(event, callback) {
  3390. var j, item;
  3391. if (event === undefined) {
  3392. this.callbacks = [];
  3393. }
  3394. j = this.callbacks.length;
  3395. while (j--) {
  3396. item = this.callbacks[j];
  3397. if (item && item.event === event && (callback === undefined || item.callback === callback)){
  3398. this.callbacks.splice(j, 1);
  3399. }
  3400. }
  3401. };
  3402. if (window.addEventListener) {
  3403. window.addEventListener('message', PreziPlayer.messageReceived, false);
  3404. } else {
  3405. window.attachEvent('onmessage', PreziPlayer.messageReceived);
  3406. }
  3407. return PreziPlayer;
  3408. })();
  3409. })();
  3410. module.exports = PreziPlayer;
  3411. },{}],18:[function(require,module,exports){
  3412. var Chat = require("./chat/Chat");
  3413. var ContactList = require("./contactlist/ContactList");
  3414. var Settings = require("./../../settings/Settings");
  3415. var SettingsMenu = require("./settings/SettingsMenu");
  3416. var VideoLayout = require("../videolayout/VideoLayout");
  3417. var ToolbarToggler = require("../toolbars/ToolbarToggler");
  3418. var UIUtil = require("../util/UIUtil");
  3419. /**
  3420. * Toggler for the chat, contact list, settings menu, etc..
  3421. */
  3422. var PanelToggler = (function(my) {
  3423. var currentlyOpen = null;
  3424. var buttons = {
  3425. '#chatspace': '#chatBottomButton',
  3426. '#contactlist': '#contactListButton',
  3427. '#settingsmenu': '#settingsButton'
  3428. };
  3429. /**
  3430. * Resizes the video area
  3431. * @param isClosing whether the side panel is going to be closed or is going to open / remain opened
  3432. * @param completeFunction a function to be called when the video space is resized
  3433. */
  3434. var resizeVideoArea = function(isClosing, completeFunction) {
  3435. var videospace = $('#videospace');
  3436. var panelSize = isClosing ? [0, 0] : PanelToggler.getPanelSize();
  3437. var videospaceWidth = window.innerWidth - panelSize[0];
  3438. var videospaceHeight = window.innerHeight;
  3439. var videoSize
  3440. = VideoLayout.getVideoSize(null, null, videospaceWidth, videospaceHeight);
  3441. var videoWidth = videoSize[0];
  3442. var videoHeight = videoSize[1];
  3443. var videoPosition = VideoLayout.getVideoPosition(videoWidth,
  3444. videoHeight,
  3445. videospaceWidth,
  3446. videospaceHeight);
  3447. var horizontalIndent = videoPosition[0];
  3448. var verticalIndent = videoPosition[1];
  3449. var thumbnailSize = VideoLayout.calculateThumbnailSize(videospaceWidth);
  3450. var thumbnailsWidth = thumbnailSize[0];
  3451. var thumbnailsHeight = thumbnailSize[1];
  3452. //for chat
  3453. videospace.animate({
  3454. right: panelSize[0],
  3455. width: videospaceWidth,
  3456. height: videospaceHeight
  3457. },
  3458. {
  3459. queue: false,
  3460. duration: 500,
  3461. complete: completeFunction
  3462. });
  3463. $('#remoteVideos').animate({
  3464. height: thumbnailsHeight
  3465. },
  3466. {
  3467. queue: false,
  3468. duration: 500
  3469. });
  3470. $('#remoteVideos>span').animate({
  3471. height: thumbnailsHeight,
  3472. width: thumbnailsWidth
  3473. },
  3474. {
  3475. queue: false,
  3476. duration: 500,
  3477. complete: function () {
  3478. $(document).trigger(
  3479. "remotevideo.resized",
  3480. [thumbnailsWidth,
  3481. thumbnailsHeight]);
  3482. }
  3483. });
  3484. $('#largeVideoContainer').animate({
  3485. width: videospaceWidth,
  3486. height: videospaceHeight
  3487. },
  3488. {
  3489. queue: false,
  3490. duration: 500
  3491. });
  3492. $('#largeVideo').animate({
  3493. width: videoWidth,
  3494. height: videoHeight,
  3495. top: verticalIndent,
  3496. bottom: verticalIndent,
  3497. left: horizontalIndent,
  3498. right: horizontalIndent
  3499. },
  3500. {
  3501. queue: false,
  3502. duration: 500
  3503. });
  3504. };
  3505. /**
  3506. * Toggles the windows in the side panel
  3507. * @param object the window that should be shown
  3508. * @param selector the selector for the element containing the panel
  3509. * @param onOpenComplete function to be called when the panel is opened
  3510. * @param onOpen function to be called if the window is going to be opened
  3511. * @param onClose function to be called if the window is going to be closed
  3512. */
  3513. var toggle = function(object, selector, onOpenComplete, onOpen, onClose) {
  3514. UIUtil.buttonClick(buttons[selector], "active");
  3515. if (object.isVisible()) {
  3516. $("#toast-container").animate({
  3517. right: '5px'
  3518. },
  3519. {
  3520. queue: false,
  3521. duration: 500
  3522. });
  3523. $(selector).hide("slide", {
  3524. direction: "right",
  3525. queue: false,
  3526. duration: 500
  3527. });
  3528. if(typeof onClose === "function") {
  3529. onClose();
  3530. }
  3531. currentlyOpen = null;
  3532. }
  3533. else {
  3534. // Undock the toolbar when the chat is shown and if we're in a
  3535. // video mode.
  3536. if (VideoLayout.isLargeVideoVisible()) {
  3537. ToolbarToggler.dockToolbar(false);
  3538. }
  3539. if(currentlyOpen) {
  3540. var current = $(currentlyOpen);
  3541. UIUtil.buttonClick(buttons[currentlyOpen], "active");
  3542. current.css('z-index', 4);
  3543. setTimeout(function () {
  3544. current.css('display', 'none');
  3545. current.css('z-index', 5);
  3546. }, 500);
  3547. }
  3548. $("#toast-container").animate({
  3549. right: (PanelToggler.getPanelSize()[0] + 5) + 'px'
  3550. },
  3551. {
  3552. queue: false,
  3553. duration: 500
  3554. });
  3555. $(selector).show("slide", {
  3556. direction: "right",
  3557. queue: false,
  3558. duration: 500,
  3559. complete: onOpenComplete
  3560. });
  3561. if(typeof onOpen === "function") {
  3562. onOpen();
  3563. }
  3564. currentlyOpen = selector;
  3565. }
  3566. };
  3567. /**
  3568. * Opens / closes the chat area.
  3569. */
  3570. my.toggleChat = function() {
  3571. var chatCompleteFunction = Chat.isVisible() ?
  3572. function() {} : function () {
  3573. Chat.scrollChatToBottom();
  3574. $('#chatspace').trigger('shown');
  3575. };
  3576. resizeVideoArea(Chat.isVisible(), chatCompleteFunction);
  3577. toggle(Chat,
  3578. '#chatspace',
  3579. function () {
  3580. // Request the focus in the nickname field or the chat input field.
  3581. if ($('#nickname').css('visibility') === 'visible') {
  3582. $('#nickinput').focus();
  3583. } else {
  3584. $('#usermsg').focus();
  3585. }
  3586. },
  3587. null,
  3588. Chat.resizeChat,
  3589. null);
  3590. };
  3591. /**
  3592. * Opens / closes the contact list area.
  3593. */
  3594. my.toggleContactList = function () {
  3595. var completeFunction = ContactList.isVisible() ?
  3596. function() {} : function () { $('#contactlist').trigger('shown');};
  3597. resizeVideoArea(ContactList.isVisible(), completeFunction);
  3598. toggle(ContactList,
  3599. '#contactlist',
  3600. null,
  3601. function() {
  3602. ContactList.setVisualNotification(false);
  3603. },
  3604. null);
  3605. };
  3606. /**
  3607. * Opens / closes the settings menu
  3608. */
  3609. my.toggleSettingsMenu = function() {
  3610. resizeVideoArea(SettingsMenu.isVisible(), function (){});
  3611. toggle(SettingsMenu,
  3612. '#settingsmenu',
  3613. null,
  3614. function() {
  3615. var settings = Settings.getSettings();
  3616. $('#setDisplayName').get(0).value = settings.displayName;
  3617. $('#setEmail').get(0).value = settings.email;
  3618. },
  3619. null);
  3620. };
  3621. /**
  3622. * Returns the size of the side panel.
  3623. */
  3624. my.getPanelSize = function () {
  3625. var availableHeight = window.innerHeight;
  3626. var availableWidth = window.innerWidth;
  3627. var panelWidth = 200;
  3628. if (availableWidth * 0.2 < 200) {
  3629. panelWidth = availableWidth * 0.2;
  3630. }
  3631. return [panelWidth, availableHeight];
  3632. };
  3633. my.isVisible = function() {
  3634. return (Chat.isVisible() || ContactList.isVisible() || SettingsMenu.isVisible());
  3635. };
  3636. return my;
  3637. }(PanelToggler || {}));
  3638. module.exports = PanelToggler;
  3639. },{"../toolbars/ToolbarToggler":27,"../util/UIUtil":31,"../videolayout/VideoLayout":33,"./../../settings/Settings":40,"./chat/Chat":19,"./contactlist/ContactList":23,"./settings/SettingsMenu":24}],19:[function(require,module,exports){
  3640. /* global $, Util, nickname:true */
  3641. var Replacement = require("./Replacement");
  3642. var CommandsProcessor = require("./Commands");
  3643. var ToolbarToggler = require("../../toolbars/ToolbarToggler");
  3644. var smileys = require("./smileys.json").smileys;
  3645. var NicknameHandler = require("../../util/NicknameHandler");
  3646. var UIUtil = require("../../util/UIUtil");
  3647. var UIEvents = require("../../../../service/UI/UIEvents");
  3648. var notificationInterval = false;
  3649. var unreadMessages = 0;
  3650. /**
  3651. * Shows/hides a visual notification, indicating that a message has arrived.
  3652. */
  3653. function setVisualNotification(show) {
  3654. var unreadMsgElement = document.getElementById('unreadMessages');
  3655. var unreadMsgBottomElement
  3656. = document.getElementById('bottomUnreadMessages');
  3657. var glower = $('#chatButton');
  3658. var bottomGlower = $('#chatBottomButton');
  3659. if (unreadMessages) {
  3660. unreadMsgElement.innerHTML = unreadMessages.toString();
  3661. unreadMsgBottomElement.innerHTML = unreadMessages.toString();
  3662. ToolbarToggler.dockToolbar(true);
  3663. var chatButtonElement
  3664. = document.getElementById('chatButton').parentNode;
  3665. var leftIndent = (UIUtil.getTextWidth(chatButtonElement) -
  3666. UIUtil.getTextWidth(unreadMsgElement)) / 2;
  3667. var topIndent = (UIUtil.getTextHeight(chatButtonElement) -
  3668. UIUtil.getTextHeight(unreadMsgElement)) / 2 - 3;
  3669. unreadMsgElement.setAttribute(
  3670. 'style',
  3671. 'top:' + topIndent +
  3672. '; left:' + leftIndent + ';');
  3673. var chatBottomButtonElement
  3674. = document.getElementById('chatBottomButton').parentNode;
  3675. var bottomLeftIndent = (UIUtil.getTextWidth(chatBottomButtonElement) -
  3676. UIUtil.getTextWidth(unreadMsgBottomElement)) / 2;
  3677. var bottomTopIndent = (UIUtil.getTextHeight(chatBottomButtonElement) -
  3678. UIUtil.getTextHeight(unreadMsgBottomElement)) / 2 - 2;
  3679. unreadMsgBottomElement.setAttribute(
  3680. 'style',
  3681. 'top:' + bottomTopIndent +
  3682. '; left:' + bottomLeftIndent + ';');
  3683. if (!glower.hasClass('icon-chat-simple')) {
  3684. glower.removeClass('icon-chat');
  3685. glower.addClass('icon-chat-simple');
  3686. }
  3687. }
  3688. else {
  3689. unreadMsgElement.innerHTML = '';
  3690. unreadMsgBottomElement.innerHTML = '';
  3691. glower.removeClass('icon-chat-simple');
  3692. glower.addClass('icon-chat');
  3693. }
  3694. if (show && !notificationInterval) {
  3695. notificationInterval = window.setInterval(function () {
  3696. glower.toggleClass('active');
  3697. bottomGlower.toggleClass('active glowing');
  3698. }, 800);
  3699. }
  3700. else if (!show && notificationInterval) {
  3701. window.clearInterval(notificationInterval);
  3702. notificationInterval = false;
  3703. glower.removeClass('active');
  3704. bottomGlower.removeClass('glowing');
  3705. bottomGlower.addClass('active');
  3706. }
  3707. }
  3708. /**
  3709. * Returns the current time in the format it is shown to the user
  3710. * @returns {string}
  3711. */
  3712. function getCurrentTime() {
  3713. var now = new Date();
  3714. var hour = now.getHours();
  3715. var minute = now.getMinutes();
  3716. var second = now.getSeconds();
  3717. if(hour.toString().length === 1) {
  3718. hour = '0'+hour;
  3719. }
  3720. if(minute.toString().length === 1) {
  3721. minute = '0'+minute;
  3722. }
  3723. if(second.toString().length === 1) {
  3724. second = '0'+second;
  3725. }
  3726. return hour+':'+minute+':'+second;
  3727. }
  3728. function toggleSmileys()
  3729. {
  3730. var smileys = $('#smileysContainer');
  3731. if(!smileys.is(':visible')) {
  3732. smileys.show("slide", { direction: "down", duration: 300});
  3733. } else {
  3734. smileys.hide("slide", { direction: "down", duration: 300});
  3735. }
  3736. $('#usermsg').focus();
  3737. }
  3738. function addClickFunction(smiley, number) {
  3739. smiley.onclick = function addSmileyToMessage() {
  3740. var usermsg = $('#usermsg');
  3741. var message = usermsg.val();
  3742. message += smileys['smiley' + number];
  3743. usermsg.val(message);
  3744. usermsg.get(0).setSelectionRange(message.length, message.length);
  3745. toggleSmileys();
  3746. usermsg.focus();
  3747. };
  3748. }
  3749. /**
  3750. * Adds the smileys container to the chat
  3751. */
  3752. function addSmileys() {
  3753. var smileysContainer = document.createElement('div');
  3754. smileysContainer.id = 'smileysContainer';
  3755. for(var i = 1; i <= 21; i++) {
  3756. var smileyContainer = document.createElement('div');
  3757. smileyContainer.id = 'smiley' + i;
  3758. smileyContainer.className = 'smileyContainer';
  3759. var smiley = document.createElement('img');
  3760. smiley.src = 'images/smileys/smiley' + i + '.svg';
  3761. smiley.className = 'smiley';
  3762. addClickFunction(smiley, i);
  3763. smileyContainer.appendChild(smiley);
  3764. smileysContainer.appendChild(smileyContainer);
  3765. }
  3766. $("#chatspace").append(smileysContainer);
  3767. }
  3768. /**
  3769. * Resizes the chat conversation.
  3770. */
  3771. function resizeChatConversation() {
  3772. var msgareaHeight = $('#usermsg').outerHeight();
  3773. var chatspace = $('#chatspace');
  3774. var width = chatspace.width();
  3775. var chat = $('#chatconversation');
  3776. var smileys = $('#smileysarea');
  3777. smileys.height(msgareaHeight);
  3778. $("#smileys").css('bottom', (msgareaHeight - 26) / 2);
  3779. $('#smileysContainer').css('bottom', msgareaHeight);
  3780. chat.width(width - 10);
  3781. chat.height(window.innerHeight - 15 - msgareaHeight);
  3782. }
  3783. /**
  3784. * Chat related user interface.
  3785. */
  3786. var Chat = (function (my) {
  3787. /**
  3788. * Initializes chat related interface.
  3789. */
  3790. my.init = function () {
  3791. if(NicknameHandler.getNickname())
  3792. Chat.setChatConversationMode(true);
  3793. NicknameHandler.addListener(UIEvents.NICKNAME_CHANGED,
  3794. function (nickname) {
  3795. Chat.setChatConversationMode(true);
  3796. });
  3797. $('#nickinput').keydown(function (event) {
  3798. if (event.keyCode === 13) {
  3799. event.preventDefault();
  3800. var val = UIUtil.escapeHtml(this.value);
  3801. this.value = '';
  3802. if (!NicknameHandler.getNickname()) {
  3803. NicknameHandler.setNickname(val);
  3804. return;
  3805. }
  3806. }
  3807. });
  3808. $('#usermsg').keydown(function (event) {
  3809. if (event.keyCode === 13) {
  3810. event.preventDefault();
  3811. var value = this.value;
  3812. $('#usermsg').val('').trigger('autosize.resize');
  3813. this.focus();
  3814. var command = new CommandsProcessor(value);
  3815. if(command.isCommand())
  3816. {
  3817. command.processCommand();
  3818. }
  3819. else
  3820. {
  3821. var message = UIUtil.escapeHtml(value);
  3822. APP.xmpp.sendChatMessage(message, NicknameHandler.getNickname());
  3823. }
  3824. }
  3825. });
  3826. var onTextAreaResize = function () {
  3827. resizeChatConversation();
  3828. Chat.scrollChatToBottom();
  3829. };
  3830. $('#usermsg').autosize({callback: onTextAreaResize});
  3831. $("#chatspace").bind("shown",
  3832. function () {
  3833. unreadMessages = 0;
  3834. setVisualNotification(false);
  3835. });
  3836. addSmileys();
  3837. };
  3838. /**
  3839. * Appends the given message to the chat conversation.
  3840. */
  3841. my.updateChatConversation = function (from, displayName, message) {
  3842. var divClassName = '';
  3843. if (APP.xmpp.myJid() === from) {
  3844. divClassName = "localuser";
  3845. }
  3846. else {
  3847. divClassName = "remoteuser";
  3848. if (!Chat.isVisible()) {
  3849. unreadMessages++;
  3850. UIUtil.playSoundNotification('chatNotification');
  3851. setVisualNotification(true);
  3852. }
  3853. }
  3854. // replace links and smileys
  3855. // Strophe already escapes special symbols on sending,
  3856. // so we escape here only tags to avoid double &amp;
  3857. var escMessage = message.replace(/</g, '&lt;').
  3858. replace(/>/g, '&gt;').replace(/\n/g, '<br/>');
  3859. var escDisplayName = UIUtil.escapeHtml(displayName);
  3860. message = Replacement.processReplacements(escMessage);
  3861. var messageContainer =
  3862. '<div class="chatmessage">'+
  3863. '<img src="../images/chatArrow.svg" class="chatArrow">' +
  3864. '<div class="username ' + divClassName +'">' + escDisplayName +
  3865. '</div>' + '<div class="timestamp">' + getCurrentTime() +
  3866. '</div>' + '<div class="usermessage">' + message + '</div>' +
  3867. '</div>';
  3868. $('#chatconversation').append(messageContainer);
  3869. $('#chatconversation').animate(
  3870. { scrollTop: $('#chatconversation')[0].scrollHeight}, 1000);
  3871. };
  3872. /**
  3873. * Appends error message to the conversation
  3874. * @param errorMessage the received error message.
  3875. * @param originalText the original message.
  3876. */
  3877. my.chatAddError = function(errorMessage, originalText)
  3878. {
  3879. errorMessage = UIUtil.escapeHtml(errorMessage);
  3880. originalText = UIUtil.escapeHtml(originalText);
  3881. $('#chatconversation').append(
  3882. '<div class="errorMessage"><b>Error: </b>' + 'Your message' +
  3883. (originalText? (' \"'+ originalText + '\"') : "") +
  3884. ' was not sent.' +
  3885. (errorMessage? (' Reason: ' + errorMessage) : '') + '</div>');
  3886. $('#chatconversation').animate(
  3887. { scrollTop: $('#chatconversation')[0].scrollHeight}, 1000);
  3888. };
  3889. /**
  3890. * Sets the subject to the UI
  3891. * @param subject the subject
  3892. */
  3893. my.chatSetSubject = function(subject)
  3894. {
  3895. if(subject)
  3896. subject = subject.trim();
  3897. $('#subject').html(Replacement.linkify(UIUtil.escapeHtml(subject)));
  3898. if(subject === "")
  3899. {
  3900. $("#subject").css({display: "none"});
  3901. }
  3902. else
  3903. {
  3904. $("#subject").css({display: "block"});
  3905. }
  3906. };
  3907. /**
  3908. * Sets the chat conversation mode.
  3909. */
  3910. my.setChatConversationMode = function (isConversationMode) {
  3911. if (isConversationMode) {
  3912. $('#nickname').css({visibility: 'hidden'});
  3913. $('#chatconversation').css({visibility: 'visible'});
  3914. $('#usermsg').css({visibility: 'visible'});
  3915. $('#smileysarea').css({visibility: 'visible'});
  3916. $('#usermsg').focus();
  3917. }
  3918. };
  3919. /**
  3920. * Resizes the chat area.
  3921. */
  3922. my.resizeChat = function () {
  3923. var chatSize = require("../SidePanelToggler").getPanelSize();
  3924. $('#chatspace').width(chatSize[0]);
  3925. $('#chatspace').height(chatSize[1]);
  3926. resizeChatConversation();
  3927. };
  3928. /**
  3929. * Indicates if the chat is currently visible.
  3930. */
  3931. my.isVisible = function () {
  3932. return $('#chatspace').is(":visible");
  3933. };
  3934. /**
  3935. * Shows and hides the window with the smileys
  3936. */
  3937. my.toggleSmileys = toggleSmileys;
  3938. /**
  3939. * Scrolls chat to the bottom.
  3940. */
  3941. my.scrollChatToBottom = function() {
  3942. setTimeout(function () {
  3943. $('#chatconversation').scrollTop(
  3944. $('#chatconversation')[0].scrollHeight);
  3945. }, 5);
  3946. };
  3947. return my;
  3948. }(Chat || {}));
  3949. module.exports = Chat;
  3950. },{"../../../../service/UI/UIEvents":95,"../../toolbars/ToolbarToggler":27,"../../util/NicknameHandler":30,"../../util/UIUtil":31,"../SidePanelToggler":18,"./Commands":20,"./Replacement":21,"./smileys.json":22}],20:[function(require,module,exports){
  3951. var UIUtil = require("../../util/UIUtil");
  3952. /**
  3953. * List with supported commands. The keys are the names of the commands and
  3954. * the value is the function that processes the message.
  3955. * @type {{String: function}}
  3956. */
  3957. var commands = {
  3958. "topic" : processTopic
  3959. };
  3960. /**
  3961. * Extracts the command from the message.
  3962. * @param message the received message
  3963. * @returns {string} the command
  3964. */
  3965. function getCommand(message)
  3966. {
  3967. if(message)
  3968. {
  3969. for(var command in commands)
  3970. {
  3971. if(message.indexOf("/" + command) == 0)
  3972. return command;
  3973. }
  3974. }
  3975. return "";
  3976. };
  3977. /**
  3978. * Processes the data for topic command.
  3979. * @param commandArguments the arguments of the topic command.
  3980. */
  3981. function processTopic(commandArguments)
  3982. {
  3983. var topic = UIUtil.escapeHtml(commandArguments);
  3984. APP.xmpp.setSubject(topic);
  3985. }
  3986. /**
  3987. * Constructs new CommandProccessor instance from a message that
  3988. * handles commands received via chat messages.
  3989. * @param message the message
  3990. * @constructor
  3991. */
  3992. function CommandsProcessor(message)
  3993. {
  3994. var command = getCommand(message);
  3995. /**
  3996. * Returns the name of the command.
  3997. * @returns {String} the command
  3998. */
  3999. this.getCommand = function()
  4000. {
  4001. return command;
  4002. };
  4003. var messageArgument = message.substr(command.length + 2);
  4004. /**
  4005. * Returns the arguments of the command.
  4006. * @returns {string}
  4007. */
  4008. this.getArgument = function()
  4009. {
  4010. return messageArgument;
  4011. };
  4012. }
  4013. /**
  4014. * Checks whether this instance is valid command or not.
  4015. * @returns {boolean}
  4016. */
  4017. CommandsProcessor.prototype.isCommand = function()
  4018. {
  4019. if(this.getCommand())
  4020. return true;
  4021. return false;
  4022. };
  4023. /**
  4024. * Processes the command.
  4025. */
  4026. CommandsProcessor.prototype.processCommand = function()
  4027. {
  4028. if(!this.isCommand())
  4029. return;
  4030. commands[this.getCommand()](this.getArgument());
  4031. };
  4032. module.exports = CommandsProcessor;
  4033. },{"../../util/UIUtil":31}],21:[function(require,module,exports){
  4034. var Smileys = require("./smileys.json");
  4035. /**
  4036. * Processes links and smileys in "body"
  4037. */
  4038. function processReplacements(body)
  4039. {
  4040. //make links clickable
  4041. body = linkify(body);
  4042. //add smileys
  4043. body = smilify(body);
  4044. return body;
  4045. }
  4046. /**
  4047. * Finds and replaces all links in the links in "body"
  4048. * with their <a href=""></a>
  4049. */
  4050. function linkify(inputText)
  4051. {
  4052. var replacedText, replacePattern1, replacePattern2, replacePattern3;
  4053. //URLs starting with http://, https://, or ftp://
  4054. replacePattern1 = /(\b(https?|ftp):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/gim;
  4055. replacedText = inputText.replace(replacePattern1, '<a href="$1" target="_blank">$1</a>');
  4056. //URLs starting with "www." (without // before it, or it'd re-link the ones done above).
  4057. replacePattern2 = /(^|[^\/])(www\.[\S]+(\b|$))/gim;
  4058. replacedText = replacedText.replace(replacePattern2, '$1<a href="http://$2" target="_blank">$2</a>');
  4059. //Change email addresses to mailto:: links.
  4060. replacePattern3 = /(([a-zA-Z0-9\-\_\.])+@[a-zA-Z\_]+?(\.[a-zA-Z]{2,6})+)/gim;
  4061. replacedText = replacedText.replace(replacePattern3, '<a href="mailto:$1">$1</a>');
  4062. return replacedText;
  4063. }
  4064. /**
  4065. * Replaces common smiley strings with images
  4066. */
  4067. function smilify(body)
  4068. {
  4069. if(!body) {
  4070. return body;
  4071. }
  4072. var regexs = Smileys["regexs"];
  4073. for(var smiley in regexs) {
  4074. if(regexs.hasOwnProperty(smiley)) {
  4075. body = body.replace(regexs[smiley],
  4076. '<img class="smiley" src="images/smileys/' + smiley + '.svg">');
  4077. }
  4078. }
  4079. return body;
  4080. }
  4081. module.exports = {
  4082. processReplacements: processReplacements,
  4083. linkify: linkify
  4084. };
  4085. },{"./smileys.json":22}],22:[function(require,module,exports){
  4086. module.exports={
  4087. "smileys": {
  4088. "smiley1": ":)",
  4089. "smiley2": ":(",
  4090. "smiley3": ":D",
  4091. "smiley4": "(y)",
  4092. "smiley5": " :P",
  4093. "smiley6": "(wave)",
  4094. "smiley7": "(blush)",
  4095. "smiley8": "(chuckle)",
  4096. "smiley9": "(shocked)",
  4097. "smiley10": ":*",
  4098. "smiley11": "(n)",
  4099. "smiley12": "(search)",
  4100. "smiley13": " <3",
  4101. "smiley14": "(oops)",
  4102. "smiley15": "(angry)",
  4103. "smiley16": "(angel)",
  4104. "smiley17": "(sick)",
  4105. "smiley18": ";(",
  4106. "smiley19": "(bomb)",
  4107. "smiley20": "(clap)",
  4108. "smiley21": " ;)"
  4109. },
  4110. "regexs": {
  4111. "smiley2": /(:-\(\(|:-\(|:\(\(|:\(|\(sad\))/gi,
  4112. "smiley3": /(:-\)\)|:\)\)|\(lol\)|:-D|:D)/gi,
  4113. "smiley1": /(:-\)|:\))/gi,
  4114. "smiley4": /(\(y\)|\(Y\)|\(ok\))/gi,
  4115. "smiley5": /(:-P|:P|:-p|:p)/gi,
  4116. "smiley6": /(\(wave\))/gi,
  4117. "smiley7": /(\(blush\))/gi,
  4118. "smiley8": /(\(chuckle\))/gi,
  4119. "smiley9": /(:-0|\(shocked\))/gi,
  4120. "smiley10": /(:-\*|:\*|\(kiss\))/gi,
  4121. "smiley11": /(\(n\))/gi,
  4122. "smiley12": /(\(search\))/g,
  4123. "smiley13": /(<3|&lt;3|&amp;lt;3|\(L\)|\(l\)|\(H\)|\(h\))/gi,
  4124. "smiley14": /(\(oops\))/gi,
  4125. "smiley15": /(\(angry\))/gi,
  4126. "smiley16": /(\(angel\))/gi,
  4127. "smiley17": /(\(sick\))/gi,
  4128. "smiley18": /(;-\(\(|;\(\(|;-\(|;\(|:"\(|:"-\(|:~-\(|:~\(|\(upset\))/gi,
  4129. "smiley19": /(\(bomb\))/gi,
  4130. "smiley20": /(\(clap\))/gi,
  4131. "smiley21": /(;-\)|;\)|;-\)\)|;\)\)|;-D|;D|\(wink\))/gi
  4132. }
  4133. }
  4134. },{}],23:[function(require,module,exports){
  4135. var numberOfContacts = 0;
  4136. var notificationInterval;
  4137. /**
  4138. * Updates the number of participants in the contact list button and sets
  4139. * the glow
  4140. * @param delta indicates whether a new user has joined (1) or someone has
  4141. * left(-1)
  4142. */
  4143. function updateNumberOfParticipants(delta) {
  4144. //when the user is alone we don't show the number of participants
  4145. if(numberOfContacts === 0) {
  4146. $("#numberOfParticipants").text('');
  4147. numberOfContacts += delta;
  4148. } else if(numberOfContacts !== 0 && !ContactList.isVisible()) {
  4149. ContactList.setVisualNotification(true);
  4150. numberOfContacts += delta;
  4151. $("#numberOfParticipants").text(numberOfContacts);
  4152. }
  4153. }
  4154. /**
  4155. * Creates the avatar element.
  4156. *
  4157. * @return the newly created avatar element
  4158. */
  4159. function createAvatar(id) {
  4160. var avatar = document.createElement('img');
  4161. avatar.className = "icon-avatar avatar";
  4162. avatar.src = "https://www.gravatar.com/avatar/" + id + "?d=wavatar&size=30";
  4163. return avatar;
  4164. }
  4165. /**
  4166. * Creates the display name paragraph.
  4167. *
  4168. * @param displayName the display name to set
  4169. */
  4170. function createDisplayNameParagraph(key, displayName) {
  4171. var p = document.createElement('p');
  4172. if(displayName)
  4173. p.innerText = displayName;
  4174. else if(key)
  4175. {
  4176. p.setAttribute("data-i18n",key);
  4177. p.innerText = APP.translation.translateString(key);
  4178. }
  4179. return p;
  4180. }
  4181. function stopGlowing(glower) {
  4182. window.clearInterval(notificationInterval);
  4183. notificationInterval = false;
  4184. glower.removeClass('glowing');
  4185. if (!ContactList.isVisible()) {
  4186. glower.removeClass('active');
  4187. }
  4188. }
  4189. /**
  4190. * Contact list.
  4191. */
  4192. var ContactList = {
  4193. /**
  4194. * Indicates if the chat is currently visible.
  4195. *
  4196. * @return <tt>true</tt> if the chat is currently visible, <tt>false</tt> -
  4197. * otherwise
  4198. */
  4199. isVisible: function () {
  4200. return $('#contactlist').is(":visible");
  4201. },
  4202. /**
  4203. * Adds a contact for the given peerJid if such doesn't yet exist.
  4204. *
  4205. * @param peerJid the peerJid corresponding to the contact
  4206. * @param id the user's email or userId used to get the user's avatar
  4207. */
  4208. ensureAddContact: function (peerJid, id) {
  4209. var resourceJid = Strophe.getResourceFromJid(peerJid);
  4210. var contact = $('#contactlist>ul>li[id="' + resourceJid + '"]');
  4211. if (!contact || contact.length <= 0)
  4212. ContactList.addContact(peerJid, id);
  4213. },
  4214. /**
  4215. * Adds a contact for the given peer jid.
  4216. *
  4217. * @param peerJid the jid of the contact to add
  4218. * @param id the email or userId of the user
  4219. */
  4220. addContact: function (peerJid, id) {
  4221. var resourceJid = Strophe.getResourceFromJid(peerJid);
  4222. var contactlist = $('#contactlist>ul');
  4223. var newContact = document.createElement('li');
  4224. newContact.id = resourceJid;
  4225. newContact.className = "clickable";
  4226. newContact.onclick = function (event) {
  4227. if (event.currentTarget.className === "clickable") {
  4228. $(ContactList).trigger('contactclicked', [peerJid]);
  4229. }
  4230. };
  4231. newContact.appendChild(createAvatar(id));
  4232. newContact.appendChild(createDisplayNameParagraph("participant"));
  4233. var clElement = contactlist.get(0);
  4234. if (resourceJid === APP.xmpp.myResource()
  4235. && $('#contactlist>ul .title')[0].nextSibling.nextSibling) {
  4236. clElement.insertBefore(newContact,
  4237. $('#contactlist>ul .title')[0].nextSibling.nextSibling);
  4238. }
  4239. else {
  4240. clElement.appendChild(newContact);
  4241. }
  4242. updateNumberOfParticipants(1);
  4243. },
  4244. /**
  4245. * Removes a contact for the given peer jid.
  4246. *
  4247. * @param peerJid the peerJid corresponding to the contact to remove
  4248. */
  4249. removeContact: function (peerJid) {
  4250. var resourceJid = Strophe.getResourceFromJid(peerJid);
  4251. var contact = $('#contactlist>ul>li[id="' + resourceJid + '"]');
  4252. if (contact && contact.length > 0) {
  4253. var contactlist = $('#contactlist>ul');
  4254. contactlist.get(0).removeChild(contact.get(0));
  4255. updateNumberOfParticipants(-1);
  4256. }
  4257. },
  4258. setVisualNotification: function (show, stopGlowingIn) {
  4259. var glower = $('#contactListButton');
  4260. if (show && !notificationInterval) {
  4261. notificationInterval = window.setInterval(function () {
  4262. glower.toggleClass('active glowing');
  4263. }, 800);
  4264. }
  4265. else if (!show && notificationInterval) {
  4266. stopGlowing(glower);
  4267. }
  4268. if (stopGlowingIn) {
  4269. setTimeout(function () {
  4270. stopGlowing(glower);
  4271. }, stopGlowingIn);
  4272. }
  4273. },
  4274. setClickable: function (resourceJid, isClickable) {
  4275. var contact = $('#contactlist>ul>li[id="' + resourceJid + '"]');
  4276. if (isClickable) {
  4277. contact.addClass('clickable');
  4278. } else {
  4279. contact.removeClass('clickable');
  4280. }
  4281. },
  4282. onDisplayNameChange: function (peerJid, displayName) {
  4283. if (peerJid === 'localVideoContainer')
  4284. peerJid = APP.xmpp.myJid();
  4285. var resourceJid = Strophe.getResourceFromJid(peerJid);
  4286. var contactName = $('#contactlist #' + resourceJid + '>p');
  4287. if (contactName && displayName && displayName.length > 0)
  4288. contactName.html(displayName);
  4289. }
  4290. };
  4291. module.exports = ContactList;
  4292. },{}],24:[function(require,module,exports){
  4293. var Avatar = require("../../avatar/Avatar");
  4294. var Settings = require("./../../../settings/Settings");
  4295. var UIUtil = require("../../util/UIUtil");
  4296. var languages = require("../../../../service/translation/languages");
  4297. function generateLanguagesSelectBox()
  4298. {
  4299. var currentLang = APP.translation.getCurrentLanguage();
  4300. var html = "<select id=\"languages_selectbox\">";
  4301. var langArray = languages.getLanguages();
  4302. for(var i = 0; i < langArray.length; i++)
  4303. {
  4304. var lang = langArray[i];
  4305. html += "<option ";
  4306. if(lang === currentLang)
  4307. html += "selected ";
  4308. html += "value=\"" + lang + "\" data-i18n='languages:" + lang + "'>";
  4309. html += "</option>";
  4310. }
  4311. return html + "</select>";
  4312. }
  4313. var SettingsMenu = {
  4314. init: function () {
  4315. $("#updateSettings").before(generateLanguagesSelectBox());
  4316. APP.translation.translateElement($("#languages_selectbox"));
  4317. $('#settingsmenu>input').keyup(function(event){
  4318. if(event.keyCode === 13) {//enter
  4319. SettingsMenu.update();
  4320. }
  4321. });
  4322. $("#updateSettings").click(function () {
  4323. SettingsMenu.update();
  4324. });
  4325. },
  4326. update: function() {
  4327. var newDisplayName = UIUtil.escapeHtml($('#setDisplayName').get(0).value);
  4328. var newEmail = UIUtil.escapeHtml($('#setEmail').get(0).value);
  4329. if(newDisplayName) {
  4330. var displayName = Settings.setDisplayName(newDisplayName);
  4331. APP.xmpp.addToPresence("displayName", displayName, true);
  4332. }
  4333. var language = $("#languages_selectbox").val();
  4334. APP.translation.setLanguage(language);
  4335. Settings.setLanguage(language);
  4336. APP.xmpp.addToPresence("email", newEmail);
  4337. var email = Settings.setEmail(newEmail);
  4338. Avatar.setUserAvatar(APP.xmpp.myJid(), email);
  4339. },
  4340. isVisible: function() {
  4341. return $('#settingsmenu').is(':visible');
  4342. },
  4343. setDisplayName: function(newDisplayName) {
  4344. var displayName = Settings.setDisplayName(newDisplayName);
  4345. $('#setDisplayName').get(0).value = displayName;
  4346. },
  4347. onDisplayNameChange: function(peerJid, newDisplayName) {
  4348. if(peerJid === 'localVideoContainer' ||
  4349. peerJid === APP.xmpp.myJid()) {
  4350. this.setDisplayName(newDisplayName);
  4351. }
  4352. }
  4353. };
  4354. module.exports = SettingsMenu;
  4355. },{"../../../../service/translation/languages":100,"../../avatar/Avatar":14,"../../util/UIUtil":31,"./../../../settings/Settings":40}],25:[function(require,module,exports){
  4356. var PanelToggler = require("../side_pannels/SidePanelToggler");
  4357. var buttonHandlers = {
  4358. "bottom_toolbar_contact_list": function () {
  4359. BottomToolbar.toggleContactList();
  4360. },
  4361. "bottom_toolbar_film_strip": function () {
  4362. BottomToolbar.toggleFilmStrip();
  4363. },
  4364. "bottom_toolbar_chat": function () {
  4365. BottomToolbar.toggleChat();
  4366. }
  4367. };
  4368. var BottomToolbar = (function (my) {
  4369. my.init = function () {
  4370. for(var k in buttonHandlers)
  4371. $("#" + k).click(buttonHandlers[k]);
  4372. };
  4373. my.toggleChat = function() {
  4374. PanelToggler.toggleChat();
  4375. };
  4376. my.toggleContactList = function() {
  4377. PanelToggler.toggleContactList();
  4378. };
  4379. my.toggleFilmStrip = function() {
  4380. var filmstrip = $("#remoteVideos");
  4381. filmstrip.toggleClass("hidden");
  4382. };
  4383. $(document).bind("remotevideo.resized", function (event, width, height) {
  4384. var bottom = (height - $('#bottomToolbar').outerHeight())/2 + 18;
  4385. $('#bottomToolbar').css({bottom: bottom + 'px'});
  4386. });
  4387. return my;
  4388. }(BottomToolbar || {}));
  4389. module.exports = BottomToolbar;
  4390. },{"../side_pannels/SidePanelToggler":18}],26:[function(require,module,exports){
  4391. /* global APP,$, buttonClick, config, lockRoom,
  4392. setSharedKey, Util */
  4393. var messageHandler = require("../util/MessageHandler");
  4394. var BottomToolbar = require("./BottomToolbar");
  4395. var Prezi = require("../prezi/Prezi");
  4396. var Etherpad = require("../etherpad/Etherpad");
  4397. var PanelToggler = require("../side_pannels/SidePanelToggler");
  4398. var Authentication = require("../authentication/Authentication");
  4399. var UIUtil = require("../util/UIUtil");
  4400. var AuthenticationEvents
  4401. = require("../../../service/authentication/AuthenticationEvents");
  4402. var roomUrl = null;
  4403. var sharedKey = '';
  4404. var UI = null;
  4405. var buttonHandlers =
  4406. {
  4407. "toolbar_button_mute": function () {
  4408. return APP.UI.toggleAudio();
  4409. },
  4410. "toolbar_button_camera": function () {
  4411. return APP.UI.toggleVideo();
  4412. },
  4413. /*"toolbar_button_authentication": function () {
  4414. return Toolbar.authenticateClicked();
  4415. },*/
  4416. "toolbar_button_record": function () {
  4417. return toggleRecording();
  4418. },
  4419. "toolbar_button_security": function () {
  4420. return Toolbar.openLockDialog();
  4421. },
  4422. "toolbar_button_link": function () {
  4423. return Toolbar.openLinkDialog();
  4424. },
  4425. "toolbar_button_chat": function () {
  4426. return BottomToolbar.toggleChat();
  4427. },
  4428. "toolbar_button_prezi": function () {
  4429. return Prezi.openPreziDialog();
  4430. },
  4431. "toolbar_button_etherpad": function () {
  4432. return Etherpad.toggleEtherpad(0);
  4433. },
  4434. "toolbar_button_desktopsharing": function () {
  4435. return APP.desktopsharing.toggleScreenSharing();
  4436. },
  4437. "toolbar_button_fullScreen": function()
  4438. {
  4439. UIUtil.buttonClick("#fullScreen", "icon-full-screen icon-exit-full-screen");
  4440. return Toolbar.toggleFullScreen();
  4441. },
  4442. "toolbar_button_sip": function () {
  4443. return callSipButtonClicked();
  4444. },
  4445. "toolbar_button_dialpad": function () {
  4446. return dialpadButtonClicked();
  4447. },
  4448. "toolbar_button_settings": function () {
  4449. PanelToggler.toggleSettingsMenu();
  4450. },
  4451. "toolbar_button_hangup": function () {
  4452. return hangup();
  4453. },
  4454. "toolbar_button_login": function () {
  4455. Toolbar.authenticateClicked();
  4456. },
  4457. "toolbar_button_logout": function () {
  4458. // Ask for confirmation
  4459. messageHandler.openTwoButtonDialog(
  4460. "dialog.logoutTitle",
  4461. null,
  4462. "dialog.logoutQuestion",
  4463. null,
  4464. false,
  4465. "dialog.Yes",
  4466. function (evt, yes) {
  4467. if (yes) {
  4468. APP.xmpp.logout(function (url) {
  4469. if (url) {
  4470. window.location.href = url;
  4471. } else {
  4472. hangup();
  4473. }
  4474. });
  4475. }
  4476. });
  4477. }
  4478. };
  4479. function hangup() {
  4480. APP.xmpp.disposeConference();
  4481. if(config.enableWelcomePage)
  4482. {
  4483. setTimeout(function()
  4484. {
  4485. window.localStorage.welcomePageDisabled = false;
  4486. window.location.pathname = "/";
  4487. }, 10000);
  4488. }
  4489. var title = APP.translation.generateTranslatonHTML(
  4490. "dialog.sessTerminated");
  4491. var msg = APP.translation.generateTranslatonHTML(
  4492. "dialog.hungUp");
  4493. var button = APP.translation.generateTranslatonHTML(
  4494. "dialog.joinAgain");
  4495. var buttons = [];
  4496. buttons.push({title: button, value: true});
  4497. UI.messageHandler.openDialog(
  4498. title,
  4499. msg,
  4500. true,
  4501. buttons,
  4502. function(event, value, message, formVals)
  4503. {
  4504. window.location.reload();
  4505. return false;
  4506. }
  4507. );
  4508. }
  4509. /**
  4510. * Starts or stops the recording for the conference.
  4511. */
  4512. function toggleRecording() {
  4513. APP.xmpp.toggleRecording(function (callback) {
  4514. var msg = APP.translation.generateTranslatonHTML(
  4515. "dialog.recordingToken");
  4516. var token = APP.translation.translateString("dialog.token");
  4517. APP.UI.messageHandler.openTwoButtonDialog(null, null, null,
  4518. '<h2>' + msg + '</h2>' +
  4519. '<input name="recordingToken" type="text" ' +
  4520. ' data-i18n="[placeholder]dialog.token" ' +
  4521. 'placeholder="' + token + '" autofocus>',
  4522. false,
  4523. "dialog.Save",
  4524. function (e, v, m, f) {
  4525. if (v) {
  4526. var token = f.recordingToken;
  4527. if (token) {
  4528. callback(UIUtil.escapeHtml(token));
  4529. }
  4530. }
  4531. },
  4532. null,
  4533. function () { },
  4534. ':input:first'
  4535. );
  4536. }, Toolbar.setRecordingButtonState, Toolbar.setRecordingButtonState);
  4537. }
  4538. /**
  4539. * Locks / unlocks the room.
  4540. */
  4541. function lockRoom(lock) {
  4542. var currentSharedKey = '';
  4543. if (lock)
  4544. currentSharedKey = sharedKey;
  4545. APP.xmpp.lockRoom(currentSharedKey, function (res) {
  4546. // password is required
  4547. if (sharedKey)
  4548. {
  4549. console.log('set room password');
  4550. Toolbar.lockLockButton();
  4551. }
  4552. else
  4553. {
  4554. console.log('removed room password');
  4555. Toolbar.unlockLockButton();
  4556. }
  4557. }, function (err) {
  4558. console.warn('setting password failed', err);
  4559. messageHandler.showError("dialog.lockTitle",
  4560. "dialog.lockMessage");
  4561. Toolbar.setSharedKey('');
  4562. }, function () {
  4563. console.warn('room passwords not supported');
  4564. messageHandler.showError("dialog.warning",
  4565. "dialog.passwordNotSupported");
  4566. Toolbar.setSharedKey('');
  4567. });
  4568. };
  4569. /**
  4570. * Invite participants to conference.
  4571. */
  4572. function inviteParticipants() {
  4573. if (roomUrl === null)
  4574. return;
  4575. var sharedKeyText = "";
  4576. if (sharedKey && sharedKey.length > 0) {
  4577. sharedKeyText =
  4578. APP.translation.translateString("email.sharedKey",
  4579. {sharedKey: sharedKey});
  4580. sharedKeyText = sharedKeyText.replace(/\n/g, "%0D%0A");
  4581. }
  4582. var supportedBrowsers = "Chromium, Google Chrome " +
  4583. APP.translation.translateString("email.and") + " Opera";
  4584. var conferenceName = roomUrl.substring(roomUrl.lastIndexOf('/') + 1);
  4585. var subject = APP.translation.translateString("email.subject",
  4586. {appName:interfaceConfig.APP_NAME, conferenceName: conferenceName});
  4587. var body = APP.translation.translateString("email.body",
  4588. {appName:interfaceConfig.APP_NAME, sharedKeyText: sharedKeyText,
  4589. roomUrl: roomUrl, supportedBrowsers: supportedBrowsers});
  4590. body = body.replace(/\n/g, "%0D%0A");
  4591. if (window.localStorage.displayname) {
  4592. body += "%0D%0A%0D%0A" + window.localStorage.displayname;
  4593. }
  4594. if (interfaceConfig.INVITATION_POWERED_BY) {
  4595. body += "%0D%0A%0D%0A--%0D%0Apowered by jitsi.org";
  4596. }
  4597. window.open("mailto:?subject=" + subject + "&body=" + body, '_blank');
  4598. }
  4599. function dialpadButtonClicked()
  4600. {
  4601. //TODO show the dialpad window
  4602. }
  4603. function callSipButtonClicked()
  4604. {
  4605. var defaultNumber
  4606. = config.defaultSipNumber ? config.defaultSipNumber : '';
  4607. var sipMsg = APP.translation.generateTranslatonHTML(
  4608. "dialog.sipMsg");
  4609. messageHandler.openTwoButtonDialog(null, null, null,
  4610. '<h2>' + sipMsg + '</h2>' +
  4611. '<input name="sipNumber" type="text"' +
  4612. ' value="' + defaultNumber + '" autofocus>',
  4613. false,
  4614. "dialog.Dial",
  4615. function (e, v, m, f) {
  4616. if (v) {
  4617. var numberInput = f.sipNumber;
  4618. if (numberInput) {
  4619. APP.xmpp.dial(
  4620. numberInput, 'fromnumber', UI.getRoomName(), sharedKey);
  4621. }
  4622. }
  4623. },
  4624. null, null, ':input:first'
  4625. );
  4626. }
  4627. var Toolbar = (function (my) {
  4628. my.init = function (ui) {
  4629. for(var k in buttonHandlers)
  4630. $("#" + k).click(buttonHandlers[k]);
  4631. UI = ui;
  4632. // Update login info
  4633. APP.xmpp.addListener(
  4634. AuthenticationEvents.IDENTITY_UPDATED,
  4635. function (authenticationEnabled, userIdentity) {
  4636. var loggedIn = false;
  4637. if (userIdentity) {
  4638. loggedIn = true;
  4639. }
  4640. Toolbar.showAuthenticateButton(authenticationEnabled);
  4641. if (authenticationEnabled) {
  4642. Toolbar.setAuthenticatedIdentity(userIdentity);
  4643. Toolbar.showLoginButton(!loggedIn);
  4644. Toolbar.showLogoutButton(loggedIn);
  4645. }
  4646. }
  4647. );
  4648. },
  4649. /**
  4650. * Sets shared key
  4651. * @param sKey the shared key
  4652. */
  4653. my.setSharedKey = function (sKey) {
  4654. sharedKey = sKey;
  4655. };
  4656. my.authenticateClicked = function () {
  4657. Authentication.focusAuthenticationWindow();
  4658. if (!APP.xmpp.isExternalAuthEnabled()) {
  4659. Authentication.xmppAuthenticate();
  4660. return;
  4661. }
  4662. // Get authentication URL
  4663. if (!APP.xmpp.getMUCJoined()) {
  4664. APP.xmpp.getLoginUrl(UI.getRoomName(), function (url) {
  4665. // If conference has not been started yet - redirect to login page
  4666. window.location.href = url;
  4667. });
  4668. } else {
  4669. APP.xmpp.getPopupLoginUrl(UI.getRoomName(), function (url) {
  4670. // Otherwise - open popup with authentication URL
  4671. var authenticationWindow = Authentication.createAuthenticationWindow(
  4672. function () {
  4673. // On popup closed - retry room allocation
  4674. APP.xmpp.allocateConferenceFocus(
  4675. APP.UI.getRoomName(),
  4676. function () { console.info("AUTH DONE"); }
  4677. );
  4678. }, url);
  4679. if (!authenticationWindow) {
  4680. messageHandler.openMessageDialog(
  4681. null, "dialog.popupError");
  4682. }
  4683. });
  4684. }
  4685. };
  4686. /**
  4687. * Updates the room invite url.
  4688. */
  4689. my.updateRoomUrl = function (newRoomUrl) {
  4690. roomUrl = newRoomUrl;
  4691. // If the invite dialog has been already opened we update the information.
  4692. var inviteLink = document.getElementById('inviteLinkRef');
  4693. if (inviteLink) {
  4694. inviteLink.value = roomUrl;
  4695. inviteLink.select();
  4696. document.getElementById('jqi_state0_buttonInvite').disabled = false;
  4697. }
  4698. };
  4699. /**
  4700. * Disables and enables some of the buttons.
  4701. */
  4702. my.setupButtonsFromConfig = function () {
  4703. if (config.disablePrezi)
  4704. {
  4705. $("#prezi_button").css({display: "none"});
  4706. }
  4707. };
  4708. /**
  4709. * Opens the lock room dialog.
  4710. */
  4711. my.openLockDialog = function () {
  4712. // Only the focus is able to set a shared key.
  4713. if (!APP.xmpp.isModerator()) {
  4714. if (sharedKey) {
  4715. messageHandler.openMessageDialog(null,
  4716. "dialog.passwordError");
  4717. } else {
  4718. messageHandler.openMessageDialog(null, "dialog.passwordError2");
  4719. }
  4720. } else {
  4721. if (sharedKey) {
  4722. messageHandler.openTwoButtonDialog(null, null,
  4723. "dialog.passwordCheck",
  4724. null,
  4725. false,
  4726. "dialog.Remove",
  4727. function (e, v) {
  4728. if (v) {
  4729. Toolbar.setSharedKey('');
  4730. lockRoom(false);
  4731. }
  4732. });
  4733. } else {
  4734. var msg = APP.translation.generateTranslatonHTML(
  4735. "dialog.passwordMsg");
  4736. var yourPassword = APP.translation.translateString(
  4737. "dialog.yourPassword");
  4738. messageHandler.openTwoButtonDialog(null, null, null,
  4739. '<h2>' + msg + '</h2>' +
  4740. '<input name="lockKey" type="text"' +
  4741. ' data-i18n="[placeholder]dialog.yourPassword" ' +
  4742. 'placeholder="' + yourPassword + '" autofocus>',
  4743. false,
  4744. "dialog.Save",
  4745. function (e, v, m, f) {
  4746. if (v) {
  4747. var lockKey = f.lockKey;
  4748. if (lockKey) {
  4749. Toolbar.setSharedKey(
  4750. UIUtil.escapeHtml(lockKey));
  4751. lockRoom(true);
  4752. }
  4753. }
  4754. },
  4755. null, null, 'input:first'
  4756. );
  4757. }
  4758. }
  4759. };
  4760. /**
  4761. * Opens the invite link dialog.
  4762. */
  4763. my.openLinkDialog = function () {
  4764. var inviteAttreibutes;
  4765. if (roomUrl === null) {
  4766. inviteAttreibutes = 'data-i18n="[value]roomUrlDefaultMsg" value="' +
  4767. APP.translation.translateString("roomUrlDefaultMsg") + '"';
  4768. } else {
  4769. inviteAttreibutes = "value=\"" + encodeURI(roomUrl) + "\"";
  4770. }
  4771. messageHandler.openTwoButtonDialog("dialog.shareLink",
  4772. null, null,
  4773. '<input id="inviteLinkRef" type="text" ' +
  4774. inviteAttreibutes + ' onclick="this.select();" readonly>',
  4775. false,
  4776. "dialog.Invite",
  4777. function (e, v) {
  4778. if (v) {
  4779. if (roomUrl) {
  4780. inviteParticipants();
  4781. }
  4782. }
  4783. },
  4784. function () {
  4785. if (roomUrl) {
  4786. document.getElementById('inviteLinkRef').select();
  4787. } else {
  4788. document.getElementById('jqi_state0_buttonInvite')
  4789. .disabled = true;
  4790. }
  4791. }
  4792. );
  4793. };
  4794. /**
  4795. * Opens the settings dialog.
  4796. * FIXME: not used ?
  4797. */
  4798. my.openSettingsDialog = function () {
  4799. var settings1 = APP.translation.generateTranslatonHTML(
  4800. "dialog.settings1");
  4801. var settings2 = APP.translation.generateTranslatonHTML(
  4802. "dialog.settings2");
  4803. var settings3 = APP.translation.generateTranslatonHTML(
  4804. "dialog.settings3");
  4805. var yourPassword = APP.translation.translateString(
  4806. "dialog.yourPassword");
  4807. messageHandler.openTwoButtonDialog(null,
  4808. '<h2>' + settings1 + '</h2>' +
  4809. '<input type="checkbox" id="initMuted">' +
  4810. settings2 + '<br/>' +
  4811. '<input type="checkbox" id="requireNicknames">' +
  4812. settings3 +
  4813. '<input id="lockKey" type="text" placeholder="' + yourPassword +
  4814. '" data-i18n="[placeholder]dialog.yourPassword" autofocus>',
  4815. null,
  4816. null,
  4817. false,
  4818. "dialog.Save",
  4819. function () {
  4820. document.getElementById('lockKey').focus();
  4821. },
  4822. function (e, v) {
  4823. if (v) {
  4824. if ($('#initMuted').is(":checked")) {
  4825. // it is checked
  4826. }
  4827. if ($('#requireNicknames').is(":checked")) {
  4828. // it is checked
  4829. }
  4830. /*
  4831. var lockKey = document.getElementById('lockKey');
  4832. if (lockKey.value) {
  4833. setSharedKey(lockKey.value);
  4834. lockRoom(true);
  4835. }
  4836. */
  4837. }
  4838. }
  4839. );
  4840. };
  4841. /**
  4842. * Toggles the application in and out of full screen mode
  4843. * (a.k.a. presentation mode in Chrome).
  4844. */
  4845. my.toggleFullScreen = function () {
  4846. var fsElement = document.documentElement;
  4847. if (!document.mozFullScreen && !document.webkitIsFullScreen) {
  4848. //Enter Full Screen
  4849. if (fsElement.mozRequestFullScreen) {
  4850. fsElement.mozRequestFullScreen();
  4851. }
  4852. else {
  4853. fsElement.webkitRequestFullScreen(Element.ALLOW_KEYBOARD_INPUT);
  4854. }
  4855. } else {
  4856. //Exit Full Screen
  4857. if (document.mozCancelFullScreen) {
  4858. document.mozCancelFullScreen();
  4859. } else {
  4860. document.webkitCancelFullScreen();
  4861. }
  4862. }
  4863. };
  4864. /**
  4865. * Unlocks the lock button state.
  4866. */
  4867. my.unlockLockButton = function () {
  4868. if ($("#lockIcon").hasClass("icon-security-locked"))
  4869. UIUtil.buttonClick("#lockIcon", "icon-security icon-security-locked");
  4870. };
  4871. /**
  4872. * Updates the lock button state to locked.
  4873. */
  4874. my.lockLockButton = function () {
  4875. if ($("#lockIcon").hasClass("icon-security"))
  4876. UIUtil.buttonClick("#lockIcon", "icon-security icon-security-locked");
  4877. };
  4878. /**
  4879. * Shows or hides authentication button
  4880. * @param show <tt>true</tt> to show or <tt>false</tt> to hide
  4881. */
  4882. my.showAuthenticateButton = function (show) {
  4883. if (show) {
  4884. $('#authentication').css({display: "inline"});
  4885. }
  4886. else {
  4887. $('#authentication').css({display: "none"});
  4888. }
  4889. };
  4890. // Shows or hides the 'recording' button.
  4891. my.showRecordingButton = function (show) {
  4892. if (!config.enableRecording) {
  4893. return;
  4894. }
  4895. if (show) {
  4896. $('#recording').css({display: "inline"});
  4897. }
  4898. else {
  4899. $('#recording').css({display: "none"});
  4900. }
  4901. };
  4902. // Sets the state of the recording button
  4903. my.setRecordingButtonState = function (isRecording) {
  4904. var selector = $('#recordButton');
  4905. if (isRecording) {
  4906. selector.removeClass("icon-recEnable");
  4907. selector.addClass("icon-recEnable active");
  4908. } else {
  4909. selector.removeClass("icon-recEnable active");
  4910. selector.addClass("icon-recEnable");
  4911. }
  4912. };
  4913. // Shows or hides SIP calls button
  4914. my.showSipCallButton = function (show) {
  4915. if (APP.xmpp.isSipGatewayEnabled() && show) {
  4916. $('#sipCallButton').css({display: "inline-block"});
  4917. } else {
  4918. $('#sipCallButton').css({display: "none"});
  4919. }
  4920. };
  4921. // Shows or hides the dialpad button
  4922. my.showDialPadButton = function (show) {
  4923. if (show) {
  4924. $('#dialPadButton').css({display: "inline-block"});
  4925. } else {
  4926. $('#dialPadButton').css({display: "none"});
  4927. }
  4928. };
  4929. /**
  4930. * Displays user authenticated identity name(login).
  4931. * @param authIdentity identity name to be displayed.
  4932. */
  4933. my.setAuthenticatedIdentity = function (authIdentity) {
  4934. if (authIdentity) {
  4935. var selector = $('#toolbar_auth_identity');
  4936. selector.css({display: "list-item"});
  4937. selector.text(authIdentity);
  4938. } else {
  4939. $('#toolbar_auth_identity').css({display: "none"});
  4940. }
  4941. };
  4942. /**
  4943. * Shows/hides login button.
  4944. * @param show <tt>true</tt> to show
  4945. */
  4946. my.showLoginButton = function (show) {
  4947. if (show) {
  4948. $('#toolbar_button_login').css({display: "list-item"});
  4949. } else {
  4950. $('#toolbar_button_login').css({display: "none"});
  4951. }
  4952. };
  4953. /**
  4954. * Shows/hides logout button.
  4955. * @param show <tt>true</tt> to show
  4956. */
  4957. my.showLogoutButton = function (show) {
  4958. if (show) {
  4959. $('#toolbar_button_logout').css({display: "list-item"});
  4960. } else {
  4961. $('#toolbar_button_logout').css({display: "none"});
  4962. }
  4963. };
  4964. /**
  4965. * Sets the state of the button. The button has blue glow if desktop
  4966. * streaming is active.
  4967. * @param active the state of the desktop streaming.
  4968. */
  4969. my.changeDesktopSharingButtonState = function (active) {
  4970. var button = $("#desktopsharing > a");
  4971. if (active)
  4972. {
  4973. button.addClass("glow");
  4974. }
  4975. else
  4976. {
  4977. button.removeClass("glow");
  4978. }
  4979. };
  4980. return my;
  4981. }(Toolbar || {}));
  4982. module.exports = Toolbar;
  4983. },{"../../../service/authentication/AuthenticationEvents":96,"../authentication/Authentication":12,"../etherpad/Etherpad":15,"../prezi/Prezi":16,"../side_pannels/SidePanelToggler":18,"../util/MessageHandler":29,"../util/UIUtil":31,"./BottomToolbar":25}],27:[function(require,module,exports){
  4984. /* global $, interfaceConfig, Moderator, DesktopStreaming.showDesktopSharingButton */
  4985. var toolbarTimeoutObject,
  4986. toolbarTimeout = interfaceConfig.INITIAL_TOOLBAR_TIMEOUT;
  4987. function showDesktopSharingButton() {
  4988. if (APP.desktopsharing.isDesktopSharingEnabled()) {
  4989. $('#desktopsharing').css({display: "inline"});
  4990. } else {
  4991. $('#desktopsharing').css({display: "none"});
  4992. }
  4993. }
  4994. /**
  4995. * Hides the toolbar.
  4996. */
  4997. function hideToolbar() {
  4998. var header = $("#header"),
  4999. bottomToolbar = $("#bottomToolbar");
  5000. var isToolbarHover = false;
  5001. header.find('*').each(function () {
  5002. var id = $(this).attr('id');
  5003. if ($("#" + id + ":hover").length > 0) {
  5004. isToolbarHover = true;
  5005. }
  5006. });
  5007. if ($("#bottomToolbar:hover").length > 0) {
  5008. isToolbarHover = true;
  5009. }
  5010. clearTimeout(toolbarTimeoutObject);
  5011. toolbarTimeoutObject = null;
  5012. if (!isToolbarHover) {
  5013. header.hide("slide", { direction: "up", duration: 300});
  5014. $('#subject').animate({top: "-=40"}, 300);
  5015. if ($("#remoteVideos").hasClass("hidden")) {
  5016. bottomToolbar.hide(
  5017. "slide", {direction: "right", duration: 300});
  5018. }
  5019. }
  5020. else {
  5021. toolbarTimeoutObject = setTimeout(hideToolbar, toolbarTimeout);
  5022. }
  5023. }
  5024. var ToolbarToggler = {
  5025. /**
  5026. * Shows the main toolbar.
  5027. */
  5028. showToolbar: function () {
  5029. var header = $("#header"),
  5030. bottomToolbar = $("#bottomToolbar");
  5031. if (!header.is(':visible') || !bottomToolbar.is(":visible")) {
  5032. header.show("slide", { direction: "up", duration: 300});
  5033. $('#subject').animate({top: "+=40"}, 300);
  5034. if (!bottomToolbar.is(":visible")) {
  5035. bottomToolbar.show(
  5036. "slide", {direction: "right", duration: 300});
  5037. }
  5038. if (toolbarTimeoutObject) {
  5039. clearTimeout(toolbarTimeoutObject);
  5040. toolbarTimeoutObject = null;
  5041. }
  5042. toolbarTimeoutObject = setTimeout(hideToolbar, toolbarTimeout);
  5043. toolbarTimeout = interfaceConfig.TOOLBAR_TIMEOUT;
  5044. }
  5045. if (APP.xmpp.isModerator())
  5046. {
  5047. // TODO: Enable settings functionality.
  5048. // Need to uncomment the settings button in index.html.
  5049. // $('#settingsButton').css({visibility:"visible"});
  5050. }
  5051. // Show/hide desktop sharing button
  5052. showDesktopSharingButton();
  5053. },
  5054. /**
  5055. * Docks/undocks the toolbar.
  5056. *
  5057. * @param isDock indicates what operation to perform
  5058. */
  5059. dockToolbar: function (isDock) {
  5060. if (isDock) {
  5061. // First make sure the toolbar is shown.
  5062. if (!$('#header').is(':visible')) {
  5063. this.showToolbar();
  5064. }
  5065. // Then clear the time out, to dock the toolbar.
  5066. if (toolbarTimeoutObject) {
  5067. clearTimeout(toolbarTimeoutObject);
  5068. toolbarTimeoutObject = null;
  5069. }
  5070. }
  5071. else {
  5072. if (!$('#header').is(':visible')) {
  5073. this.showToolbar();
  5074. }
  5075. else {
  5076. toolbarTimeoutObject = setTimeout(hideToolbar, toolbarTimeout);
  5077. }
  5078. }
  5079. },
  5080. showDesktopSharingButton: showDesktopSharingButton
  5081. };
  5082. module.exports = ToolbarToggler;
  5083. },{}],28:[function(require,module,exports){
  5084. var JitsiPopover = (function () {
  5085. /**
  5086. * Constructs new JitsiPopover and attaches it to the element
  5087. * @param element jquery selector
  5088. * @param options the options for the popover.
  5089. * @constructor
  5090. */
  5091. function JitsiPopover(element, options)
  5092. {
  5093. this.options = {
  5094. skin: "white",
  5095. content: ""
  5096. };
  5097. if(options)
  5098. {
  5099. if(options.skin)
  5100. this.options.skin = options.skin;
  5101. if(options.content)
  5102. this.options.content = options.content;
  5103. }
  5104. this.elementIsHovered = false;
  5105. this.popoverIsHovered = false;
  5106. this.popoverShown = false;
  5107. element.data("jitsi_popover", this);
  5108. this.element = element;
  5109. this.template = ' <div class="jitsipopover ' + this.options.skin +
  5110. '"><div class="arrow"></div><div class="jitsipopover-content"></div>' +
  5111. '<div class="jitsiPopupmenuPadding"></div></div>';
  5112. var self = this;
  5113. this.element.on("mouseenter", function () {
  5114. self.elementIsHovered = true;
  5115. self.show();
  5116. }).on("mouseleave", function () {
  5117. self.elementIsHovered = false;
  5118. setTimeout(function () {
  5119. self.hide();
  5120. }, 10);
  5121. });
  5122. }
  5123. /**
  5124. * Shows the popover
  5125. */
  5126. JitsiPopover.prototype.show = function () {
  5127. this.createPopover();
  5128. this.popoverShown = true;
  5129. };
  5130. /**
  5131. * Hides the popover
  5132. */
  5133. JitsiPopover.prototype.hide = function () {
  5134. if(!this.elementIsHovered && !this.popoverIsHovered && this.popoverShown)
  5135. {
  5136. this.forceHide();
  5137. }
  5138. };
  5139. /**
  5140. * Hides the popover
  5141. */
  5142. JitsiPopover.prototype.forceHide = function () {
  5143. $(".jitsipopover").remove();
  5144. this.popoverShown = false;
  5145. };
  5146. /**
  5147. * Creates the popover html
  5148. */
  5149. JitsiPopover.prototype.createPopover = function () {
  5150. $("body").append(this.template);
  5151. $(".jitsipopover > .jitsipopover-content").html(this.options.content);
  5152. var self = this;
  5153. $(".jitsipopover").on("mouseenter", function () {
  5154. self.popoverIsHovered = true;
  5155. }).on("mouseleave", function () {
  5156. self.popoverIsHovered = false;
  5157. self.hide();
  5158. });
  5159. this.refreshPosition();
  5160. };
  5161. /**
  5162. * Refreshes the position of the popover
  5163. */
  5164. JitsiPopover.prototype.refreshPosition = function () {
  5165. $(".jitsipopover").position({
  5166. my: "bottom",
  5167. at: "top",
  5168. collision: "fit",
  5169. of: this.element,
  5170. using: function (position, elements) {
  5171. var calcLeft = elements.target.left - elements.element.left + elements.target.width/2;
  5172. $(".jitsipopover").css({top: position.top, left: position.left, display: "table"});
  5173. $(".jitsipopover > .arrow").css({left: calcLeft});
  5174. $(".jitsipopover > .jitsiPopupmenuPadding").css({left: calcLeft - 50});
  5175. }
  5176. });
  5177. };
  5178. /**
  5179. * Updates the content of popover.
  5180. * @param content new content
  5181. */
  5182. JitsiPopover.prototype.updateContent = function (content) {
  5183. this.options.content = content;
  5184. if(!this.popoverShown)
  5185. return;
  5186. $(".jitsipopover").remove();
  5187. this.createPopover();
  5188. };
  5189. return JitsiPopover;
  5190. })();
  5191. module.exports = JitsiPopover;
  5192. },{}],29:[function(require,module,exports){
  5193. /* global $, APP, jQuery, toastr */
  5194. var messageHandler = (function(my) {
  5195. /**
  5196. * Shows a message to the user.
  5197. *
  5198. * @param titleString the title of the message
  5199. * @param messageString the text of the message
  5200. */
  5201. my.openMessageDialog = function(titleKey, messageKey) {
  5202. var title = null;
  5203. if(titleKey)
  5204. {
  5205. title = APP.translation.generateTranslatonHTML(titleKey);
  5206. }
  5207. var message = APP.translation.generateTranslatonHTML(messageKey);
  5208. $.prompt(message,
  5209. {
  5210. title: title,
  5211. persistent: false
  5212. }
  5213. );
  5214. };
  5215. /**
  5216. * Shows a message to the user with two buttons: first is given as a parameter and the second is Cancel.
  5217. *
  5218. * @param titleString the title of the message
  5219. * @param msgString the text of the message
  5220. * @param persistent boolean value which determines whether the message is persistent or not
  5221. * @param leftButton the fist button's text
  5222. * @param submitFunction function to be called on submit
  5223. * @param loadedFunction function to be called after the prompt is fully loaded
  5224. * @param closeFunction function to be called after the prompt is closed
  5225. * @param focus optional focus selector or button index to be focused after
  5226. * the dialog is opened
  5227. * @param defaultButton index of default button which will be activated when
  5228. * the user press 'enter'. Indexed from 0.
  5229. */
  5230. my.openTwoButtonDialog = function(titleKey, titleString, msgKey, msgString,
  5231. persistent, leftButtonKey, submitFunction, loadedFunction,
  5232. closeFunction, focus, defaultButton)
  5233. {
  5234. var buttons = [];
  5235. var leftButton = APP.translation.generateTranslatonHTML(leftButtonKey);
  5236. buttons.push({ title: leftButton, value: true});
  5237. var cancelButton
  5238. = APP.translation.generateTranslatonHTML("dialog.Cancel");
  5239. buttons.push({title: cancelButton, value: false});
  5240. var message = msgString, title = titleString;
  5241. if (titleKey)
  5242. {
  5243. title = APP.translation.generateTranslatonHTML(titleKey);
  5244. }
  5245. if (msgKey) {
  5246. message = APP.translation.generateTranslatonHTML(msgKey);
  5247. }
  5248. $.prompt(message, {
  5249. title: title,
  5250. persistent: false,
  5251. buttons: buttons,
  5252. defaultButton: defaultButton,
  5253. focus: focus,
  5254. loaded: loadedFunction,
  5255. submit: submitFunction,
  5256. close: closeFunction
  5257. });
  5258. };
  5259. /**
  5260. * Shows a message to the user with two buttons: first is given as a parameter and the second is Cancel.
  5261. *
  5262. * @param titleString the title of the message
  5263. * @param msgString the text of the message
  5264. * @param persistent boolean value which determines whether the message is persistent or not
  5265. * @param buttons object with the buttons. The keys must be the name of the button and value is the value
  5266. * that will be passed to submitFunction
  5267. * @param submitFunction function to be called on submit
  5268. * @param loadedFunction function to be called after the prompt is fully loaded
  5269. */
  5270. my.openDialog = function (titleString, msgString, persistent, buttons,
  5271. submitFunction, loadedFunction) {
  5272. var args = {
  5273. title: titleString,
  5274. persistent: persistent,
  5275. buttons: buttons,
  5276. defaultButton: 1,
  5277. loaded: loadedFunction,
  5278. submit: submitFunction
  5279. };
  5280. if (persistent) {
  5281. args.closeText = '';
  5282. }
  5283. return new Impromptu(msgString, args);
  5284. };
  5285. /**
  5286. * Closes currently opened dialog.
  5287. */
  5288. my.closeDialog = function () {
  5289. $.prompt.close();
  5290. };
  5291. /**
  5292. * Shows a dialog with different states to the user.
  5293. *
  5294. * @param statesObject object containing all the states of the dialog
  5295. */
  5296. my.openDialogWithStates = function (statesObject, options) {
  5297. return new Impromptu(statesObject, options);
  5298. };
  5299. /**
  5300. * Opens new popup window for given <tt>url</tt> centered over current
  5301. * window.
  5302. *
  5303. * @param url the URL to be displayed in the popup window
  5304. * @param w the width of the popup window
  5305. * @param h the height of the popup window
  5306. * @param onPopupClosed optional callback function called when popup window
  5307. * has been closed.
  5308. *
  5309. * @returns popup window object if opened successfully or undefined
  5310. * in case we failed to open it(popup blocked)
  5311. */
  5312. my.openCenteredPopup = function (url, w, h, onPopupClosed) {
  5313. var l = window.screenX + (window.innerWidth / 2) - (w / 2);
  5314. var t = window.screenY + (window.innerHeight / 2) - (h / 2);
  5315. var popup = window.open(
  5316. url, '_blank',
  5317. 'top=' + t + ', left=' + l + ', width=' + w + ', height=' + h + '');
  5318. if (popup && onPopupClosed) {
  5319. var pollTimer = window.setInterval(function () {
  5320. if (popup.closed !== false) {
  5321. window.clearInterval(pollTimer);
  5322. onPopupClosed();
  5323. }
  5324. }, 200);
  5325. }
  5326. return popup;
  5327. };
  5328. /**
  5329. * Shows a dialog prompting the user to send an error report.
  5330. *
  5331. * @param titleString the title of the message
  5332. * @param msgString the text of the message
  5333. * @param error the error that is being reported
  5334. */
  5335. my.openReportDialog = function(titleKey, msgKey, error) {
  5336. my.openMessageDialog(titleKey, msgKey);
  5337. console.log(error);
  5338. //FIXME send the error to the server
  5339. };
  5340. /**
  5341. * Shows an error dialog to the user.
  5342. * @param title the title of the message
  5343. * @param message the text of the messafe
  5344. */
  5345. my.showError = function(titleKey, msgKey) {
  5346. if(!titleKey) {
  5347. titleKey = "dialog.oops";
  5348. }
  5349. if(!msgKey)
  5350. {
  5351. msgKey = "dialog.defaultError";
  5352. }
  5353. messageHandler.openMessageDialog(titleKey, msgKey);
  5354. };
  5355. my.notify = function(displayName, displayNameKey,
  5356. cls, messageKey, messageArguments) {
  5357. var displayNameSpan = '<span class="nickname" ';
  5358. if(displayName)
  5359. {
  5360. displayNameSpan += ">" + displayName;
  5361. }
  5362. else
  5363. {
  5364. displayNameSpan += "data-i18n='" + displayNameKey +
  5365. "'>" + APP.translation.translateString(displayNameKey);
  5366. }
  5367. displayNameSpan += "</span>";
  5368. toastr.info(
  5369. displayNameSpan + '<br>' +
  5370. '<span class=' + cls + ' data-i18n="' + messageKey + '"' +
  5371. (messageArguments?
  5372. " data-i18n-options='" + JSON.stringify(messageArguments) + "'"
  5373. : "") + ">" +
  5374. APP.translation.translateString(messageKey,
  5375. messageArguments) +
  5376. '</span>');
  5377. };
  5378. return my;
  5379. }(messageHandler || {}));
  5380. module.exports = messageHandler;
  5381. },{}],30:[function(require,module,exports){
  5382. var UIEvents = require("../../../service/UI/UIEvents");
  5383. var nickname = null;
  5384. var eventEmitter = null;
  5385. var NickanameHandler = {
  5386. init: function (emitter) {
  5387. eventEmitter = emitter;
  5388. var storedDisplayName = window.localStorage.displayname;
  5389. if (storedDisplayName) {
  5390. nickname = storedDisplayName;
  5391. }
  5392. },
  5393. setNickname: function (newNickname) {
  5394. if (!newNickname || nickname === newNickname)
  5395. return;
  5396. nickname = newNickname;
  5397. window.localStorage.displayname = nickname;
  5398. eventEmitter.emit(UIEvents.NICKNAME_CHANGED, newNickname);
  5399. },
  5400. getNickname: function () {
  5401. return nickname;
  5402. },
  5403. addListener: function (type, listener) {
  5404. eventEmitter.on(type, listener);
  5405. }
  5406. };
  5407. module.exports = NickanameHandler;
  5408. },{"../../../service/UI/UIEvents":95}],31:[function(require,module,exports){
  5409. /**
  5410. * Created by hristo on 12/22/14.
  5411. */
  5412. module.exports = {
  5413. /**
  5414. * Returns the available video width.
  5415. */
  5416. getAvailableVideoWidth: function () {
  5417. var PanelToggler = require("../side_pannels/SidePanelToggler");
  5418. var rightPanelWidth
  5419. = PanelToggler.isVisible() ? PanelToggler.getPanelSize()[0] : 0;
  5420. return window.innerWidth - rightPanelWidth;
  5421. },
  5422. /**
  5423. * Changes the style class of the element given by id.
  5424. */
  5425. buttonClick: function(id, classname) {
  5426. $(id).toggleClass(classname); // add the class to the clicked element
  5427. },
  5428. /**
  5429. * Returns the text width for the given element.
  5430. *
  5431. * @param el the element
  5432. */
  5433. getTextWidth: function (el) {
  5434. return (el.clientWidth + 1);
  5435. },
  5436. /**
  5437. * Returns the text height for the given element.
  5438. *
  5439. * @param el the element
  5440. */
  5441. getTextHeight: function (el) {
  5442. return (el.clientHeight + 1);
  5443. },
  5444. /**
  5445. * Plays the sound given by id.
  5446. *
  5447. * @param id the identifier of the audio element.
  5448. */
  5449. playSoundNotification: function (id) {
  5450. document.getElementById(id).play();
  5451. },
  5452. /**
  5453. * Escapes the given text.
  5454. */
  5455. escapeHtml: function (unsafeText) {
  5456. return $('<div/>').text(unsafeText).html();
  5457. },
  5458. imageToGrayScale: function (canvas) {
  5459. var context = canvas.getContext('2d');
  5460. var imgData = context.getImageData(0, 0, canvas.width, canvas.height);
  5461. var pixels = imgData.data;
  5462. for (var i = 0, n = pixels.length; i < n; i += 4) {
  5463. var grayscale
  5464. = pixels[i] * .3 + pixels[i+1] * .59 + pixels[i+2] * .11;
  5465. pixels[i ] = grayscale; // red
  5466. pixels[i+1] = grayscale; // green
  5467. pixels[i+2] = grayscale; // blue
  5468. // pixels[i+3] is alpha
  5469. }
  5470. // redraw the image in black & white
  5471. context.putImageData(imgData, 0, 0);
  5472. },
  5473. setTooltip: function (element, key, position) {
  5474. element.setAttribute("data-i18n", "[data-content]" + key);
  5475. element.setAttribute("data-toggle", "popover");
  5476. element.setAttribute("data-placement", position);
  5477. element.setAttribute("data-html", true);
  5478. element.setAttribute("data-container", "body");
  5479. }
  5480. };
  5481. },{"../side_pannels/SidePanelToggler":18}],32:[function(require,module,exports){
  5482. var JitsiPopover = require("../util/JitsiPopover");
  5483. /**
  5484. * Constructs new connection indicator.
  5485. * @param videoContainer the video container associated with the indicator.
  5486. * @constructor
  5487. */
  5488. function ConnectionIndicator(videoContainer, jid, VideoLayout)
  5489. {
  5490. this.videoContainer = videoContainer;
  5491. this.bandwidth = null;
  5492. this.packetLoss = null;
  5493. this.bitrate = null;
  5494. this.showMoreValue = false;
  5495. this.resolution = null;
  5496. this.transport = [];
  5497. this.popover = null;
  5498. this.jid = jid;
  5499. this.create();
  5500. this.videoLayout = VideoLayout;
  5501. }
  5502. /**
  5503. * Values for the connection quality
  5504. * @type {{98: string,
  5505. * 81: string,
  5506. * 64: string,
  5507. * 47: string,
  5508. * 30: string,
  5509. * 0: string}}
  5510. */
  5511. ConnectionIndicator.connectionQualityValues = {
  5512. 98: "18px", //full
  5513. 81: "15px",//4 bars
  5514. 64: "11px",//3 bars
  5515. 47: "7px",//2 bars
  5516. 30: "3px",//1 bar
  5517. 0: "0px"//empty
  5518. };
  5519. ConnectionIndicator.getIP = function(value)
  5520. {
  5521. return value.substring(0, value.lastIndexOf(":"));
  5522. };
  5523. ConnectionIndicator.getPort = function(value)
  5524. {
  5525. return value.substring(value.lastIndexOf(":") + 1, value.length);
  5526. };
  5527. ConnectionIndicator.getStringFromArray = function (array) {
  5528. var res = "";
  5529. for(var i = 0; i < array.length; i++)
  5530. {
  5531. res += (i === 0? "" : ", ") + array[i];
  5532. }
  5533. return res;
  5534. };
  5535. /**
  5536. * Generates the html content.
  5537. * @returns {string} the html content.
  5538. */
  5539. ConnectionIndicator.prototype.generateText = function () {
  5540. var downloadBitrate, uploadBitrate, packetLoss, resolution, i;
  5541. var translate = APP.translation.translateString;
  5542. if(this.bitrate === null)
  5543. {
  5544. downloadBitrate = "N/A";
  5545. uploadBitrate = "N/A";
  5546. }
  5547. else
  5548. {
  5549. downloadBitrate =
  5550. this.bitrate.download? this.bitrate.download + " Kbps" : "N/A";
  5551. uploadBitrate =
  5552. this.bitrate.upload? this.bitrate.upload + " Kbps" : "N/A";
  5553. }
  5554. if(this.packetLoss === null)
  5555. {
  5556. packetLoss = "N/A";
  5557. }
  5558. else
  5559. {
  5560. packetLoss = "<span class='jitsipopover_green'>&darr;</span>" +
  5561. (this.packetLoss.download !== null? this.packetLoss.download : "N/A") +
  5562. "% <span class='jitsipopover_orange'>&uarr;</span>" +
  5563. (this.packetLoss.upload !== null? this.packetLoss.upload : "N/A") + "%";
  5564. }
  5565. var resolutionValue = null;
  5566. if(this.resolution && this.jid != null)
  5567. {
  5568. var keys = Object.keys(this.resolution);
  5569. if(keys.length == 1)
  5570. {
  5571. for(var ssrc in this.resolution)
  5572. {
  5573. resolutionValue = this.resolution[ssrc];
  5574. }
  5575. }
  5576. else if(keys.length > 1)
  5577. {
  5578. var displayedSsrc = APP.simulcast.getReceivingSSRC(this.jid);
  5579. resolutionValue = this.resolution[displayedSsrc];
  5580. }
  5581. }
  5582. if(this.jid === null)
  5583. {
  5584. resolution = "";
  5585. if(this.resolution === null || !Object.keys(this.resolution) ||
  5586. Object.keys(this.resolution).length === 0)
  5587. {
  5588. resolution = "N/A";
  5589. }
  5590. else
  5591. for(i in this.resolution)
  5592. {
  5593. resolutionValue = this.resolution[i];
  5594. if(resolutionValue)
  5595. {
  5596. if(resolutionValue.height &&
  5597. resolutionValue.width)
  5598. {
  5599. resolution += (resolution === ""? "" : ", ") +
  5600. resolutionValue.width + "x" +
  5601. resolutionValue.height;
  5602. }
  5603. }
  5604. }
  5605. }
  5606. else if(!resolutionValue ||
  5607. !resolutionValue.height ||
  5608. !resolutionValue.width)
  5609. {
  5610. resolution = "N/A";
  5611. }
  5612. else
  5613. {
  5614. resolution = resolutionValue.width + "x" + resolutionValue.height;
  5615. }
  5616. var result = "<table style='width:100%'>" +
  5617. "<tr>" +
  5618. "<td><span class='jitsipopover_blue' data-i18n='connectionindicator.bitrate'>" +
  5619. translate("connectionindicator.bitrate") + "</span></td>" +
  5620. "<td><span class='jitsipopover_green'>&darr;</span>" +
  5621. downloadBitrate + " <span class='jitsipopover_orange'>&uarr;</span>" +
  5622. uploadBitrate + "</td>" +
  5623. "</tr><tr>" +
  5624. "<td><span class='jitsipopover_blue' data-i18n='connectionindicator.packetloss'>" +
  5625. translate("connectionindicator.packetloss") + "</span></td>" +
  5626. "<td>" + packetLoss + "</td>" +
  5627. "</tr><tr>" +
  5628. "<td><span class='jitsipopover_blue' data-i18n='connectionindicator.resolution'>" +
  5629. translate("connectionindicator.resolution") + "</span></td>" +
  5630. "<td>" + resolution + "</td></tr></table>";
  5631. if(this.videoContainer.id == "localVideoContainer") {
  5632. result += "<div class=\"jitsipopover_showmore\" " +
  5633. "onclick = \"APP.UI.connectionIndicatorShowMore('" +
  5634. this.videoContainer.id + "')\" data-i18n='connectionindicator." +
  5635. (this.showMoreValue ? "less" : "more") + "'>" +
  5636. translate("connectionindicator." + (this.showMoreValue ? "less" : "more")) +
  5637. "</div><br />";
  5638. }
  5639. if(this.showMoreValue)
  5640. {
  5641. var downloadBandwidth, uploadBandwidth, transport;
  5642. if(this.bandwidth === null)
  5643. {
  5644. downloadBandwidth = "N/A";
  5645. uploadBandwidth = "N/A";
  5646. }
  5647. else
  5648. {
  5649. downloadBandwidth = this.bandwidth.download?
  5650. this.bandwidth.download + " Kbps" :
  5651. "N/A";
  5652. uploadBandwidth = this.bandwidth.upload?
  5653. this.bandwidth.upload + " Kbps" :
  5654. "N/A";
  5655. }
  5656. if(!this.transport || this.transport.length === 0)
  5657. {
  5658. transport = "<tr>" +
  5659. "<td><span class='jitsipopover_blue' " +
  5660. "data-i18n='connectionindicator.address'>" +
  5661. translate("connectionindicator.address") + "</span></td>" +
  5662. "<td> N/A</td></tr>";
  5663. }
  5664. else
  5665. {
  5666. var data = {remoteIP: [], localIP:[], remotePort:[], localPort:[]};
  5667. for(i = 0; i < this.transport.length; i++)
  5668. {
  5669. var ip = ConnectionIndicator.getIP(this.transport[i].ip);
  5670. var port = ConnectionIndicator.getPort(this.transport[i].ip);
  5671. var localIP =
  5672. ConnectionIndicator.getIP(this.transport[i].localip);
  5673. var localPort =
  5674. ConnectionIndicator.getPort(this.transport[i].localip);
  5675. if(data.remoteIP.indexOf(ip) == -1)
  5676. {
  5677. data.remoteIP.push(ip);
  5678. }
  5679. if(data.remotePort.indexOf(port) == -1)
  5680. {
  5681. data.remotePort.push(port);
  5682. }
  5683. if(data.localIP.indexOf(localIP) == -1)
  5684. {
  5685. data.localIP.push(localIP);
  5686. }
  5687. if(data.localPort.indexOf(localPort) == -1)
  5688. {
  5689. data.localPort.push(localPort);
  5690. }
  5691. }
  5692. var local_address_key = "connectionindicator.localaddress";
  5693. var remote_address_key = "connectionindicator.remoteaddress";
  5694. var localTransport =
  5695. "<tr><td><span class='jitsipopover_blue' data-i18n='" +
  5696. local_address_key +"' data-i18n-options='" +
  5697. JSON.stringify({count: data.localIP.length}) + "'>" +
  5698. translate(local_address_key, {count: data.localIP.length}) +
  5699. "</span></td><td> " +
  5700. ConnectionIndicator.getStringFromArray(data.localIP) +
  5701. "</td></tr>";
  5702. transport =
  5703. "<tr><td><span class='jitsipopover_blue' data-i18n='" +
  5704. remote_address_key + "' data-i18n-options='" +
  5705. JSON.stringify({count: data.remoteIP.length}) + "'>" +
  5706. translate(remote_address_key,
  5707. {count: data.remoteIP.length}) +
  5708. "</span></td><td> " +
  5709. ConnectionIndicator.getStringFromArray(data.remoteIP) +
  5710. "</td></tr>";
  5711. var key_remote = "connectionindicator.remoteport",
  5712. key_local = "connectionindicator.localport";
  5713. transport += "<tr>" +
  5714. "<td>" +
  5715. "<span class='jitsipopover_blue' data-i18n='" + key_remote +
  5716. "' data-i18n-options='" +
  5717. JSON.stringify({count: this.transport.length}) + "'>" +
  5718. translate(key_remote, {count: this.transport.length}) +
  5719. "</span></td><td>";
  5720. localTransport += "<tr>" +
  5721. "<td>" +
  5722. "<span class='jitsipopover_blue' data-i18n='" + key_local +
  5723. "' data-i18n-options='" +
  5724. JSON.stringify({count: this.transport.length}) + "'>" +
  5725. translate(key_local, {count: this.transport.length}) +
  5726. "</span></td><td>";
  5727. transport +=
  5728. ConnectionIndicator.getStringFromArray(data.remotePort);
  5729. localTransport +=
  5730. ConnectionIndicator.getStringFromArray(data.localPort);
  5731. transport += "</td></tr>";
  5732. transport += localTransport + "</td></tr>";
  5733. transport +="<tr>" +
  5734. "<td><span class='jitsipopover_blue' data-i18n='connectionindicator.transport'>" +
  5735. translate("connectionindicator.transport") + "</span></td>" +
  5736. "<td>" + this.transport[0].type + "</td></tr>";
  5737. }
  5738. result += "<table style='width:100%'>" +
  5739. "<tr>" +
  5740. "<td>" +
  5741. "<span class='jitsipopover_blue' data-i18n='connectionindicator.bandwidth'>" +
  5742. translate("connectionindicator.bandwidth") + "</span>" +
  5743. "</td><td>" +
  5744. "<span class='jitsipopover_green'>&darr;</span>" +
  5745. downloadBandwidth +
  5746. " <span class='jitsipopover_orange'>&uarr;</span>" +
  5747. uploadBandwidth + "</td></tr>";
  5748. result += transport + "</table>";
  5749. }
  5750. return result;
  5751. };
  5752. /**
  5753. * Shows or hide the additional information.
  5754. */
  5755. ConnectionIndicator.prototype.showMore = function () {
  5756. this.showMoreValue = !this.showMoreValue;
  5757. this.updatePopoverData();
  5758. };
  5759. function createIcon(classes)
  5760. {
  5761. var icon = document.createElement("span");
  5762. for(var i in classes)
  5763. {
  5764. icon.classList.add(classes[i]);
  5765. }
  5766. icon.appendChild(
  5767. document.createElement("i")).classList.add("icon-connection");
  5768. return icon;
  5769. }
  5770. /**
  5771. * Creates the indicator
  5772. */
  5773. ConnectionIndicator.prototype.create = function () {
  5774. this.connectionIndicatorContainer = document.createElement("div");
  5775. this.connectionIndicatorContainer.className = "connectionindicator";
  5776. this.connectionIndicatorContainer.style.display = "none";
  5777. this.videoContainer.appendChild(this.connectionIndicatorContainer);
  5778. this.popover = new JitsiPopover(
  5779. $("#" + this.videoContainer.id + " > .connectionindicator"),
  5780. {content: "<div class=\"connection_info\" data-i18n='connectionindicator.na'>" +
  5781. APP.translation.translateString("connectionindicator.na") + "</div>",
  5782. skin: "black"});
  5783. this.emptyIcon = this.connectionIndicatorContainer.appendChild(
  5784. createIcon(["connection", "connection_empty"]));
  5785. this.fullIcon = this.connectionIndicatorContainer.appendChild(
  5786. createIcon(["connection", "connection_full"]));
  5787. };
  5788. /**
  5789. * Removes the indicator
  5790. */
  5791. ConnectionIndicator.prototype.remove = function()
  5792. {
  5793. this.connectionIndicatorContainer.remove();
  5794. this.popover.forceHide();
  5795. };
  5796. /**
  5797. * Updates the data of the indicator
  5798. * @param percent the percent of connection quality
  5799. * @param object the statistics data.
  5800. */
  5801. ConnectionIndicator.prototype.updateConnectionQuality =
  5802. function (percent, object) {
  5803. if(percent === null)
  5804. {
  5805. this.connectionIndicatorContainer.style.display = "none";
  5806. this.popover.forceHide();
  5807. return;
  5808. }
  5809. else
  5810. {
  5811. if(this.connectionIndicatorContainer.style.display == "none") {
  5812. this.connectionIndicatorContainer.style.display = "block";
  5813. this.videoLayout.updateMutePosition(this.videoContainer.id);
  5814. }
  5815. }
  5816. this.bandwidth = object.bandwidth;
  5817. this.bitrate = object.bitrate;
  5818. this.packetLoss = object.packetLoss;
  5819. this.transport = object.transport;
  5820. if(object.resolution)
  5821. {
  5822. this.resolution = object.resolution;
  5823. }
  5824. for(var quality in ConnectionIndicator.connectionQualityValues)
  5825. {
  5826. if(percent >= quality)
  5827. {
  5828. this.fullIcon.style.width =
  5829. ConnectionIndicator.connectionQualityValues[quality];
  5830. }
  5831. }
  5832. this.updatePopoverData();
  5833. };
  5834. /**
  5835. * Updates the resolution
  5836. * @param resolution the new resolution
  5837. */
  5838. ConnectionIndicator.prototype.updateResolution = function (resolution) {
  5839. this.resolution = resolution;
  5840. this.updatePopoverData();
  5841. };
  5842. /**
  5843. * Updates the content of the popover
  5844. */
  5845. ConnectionIndicator.prototype.updatePopoverData = function () {
  5846. this.popover.updateContent(
  5847. "<div class=\"connection_info\">" + this.generateText() + "</div>");
  5848. APP.translation.translateElement($(".connection_info"));
  5849. };
  5850. /**
  5851. * Hides the popover
  5852. */
  5853. ConnectionIndicator.prototype.hide = function () {
  5854. this.popover.forceHide();
  5855. };
  5856. /**
  5857. * Hides the indicator
  5858. */
  5859. ConnectionIndicator.prototype.hideIndicator = function () {
  5860. this.connectionIndicatorContainer.style.display = "none";
  5861. if(this.popover)
  5862. this.popover.forceHide();
  5863. };
  5864. module.exports = ConnectionIndicator;
  5865. },{"../util/JitsiPopover":28}],33:[function(require,module,exports){
  5866. var AudioLevels = require("../audio_levels/AudioLevels");
  5867. var Avatar = require("../avatar/Avatar");
  5868. var Chat = require("../side_pannels/chat/Chat");
  5869. var ContactList = require("../side_pannels/contactlist/ContactList");
  5870. var UIUtil = require("../util/UIUtil");
  5871. var ConnectionIndicator = require("./ConnectionIndicator");
  5872. var NicknameHandler = require("../util/NicknameHandler");
  5873. var MediaStreamType = require("../../../service/RTC/MediaStreamTypes");
  5874. var UIEvents = require("../../../service/UI/UIEvents");
  5875. var currentDominantSpeaker = null;
  5876. var lastNCount = config.channelLastN;
  5877. var localLastNCount = config.channelLastN;
  5878. var localLastNSet = [];
  5879. var lastNEndpointsCache = [];
  5880. var lastNPickupJid = null;
  5881. var largeVideoState = {
  5882. updateInProgress: false,
  5883. newSrc: ''
  5884. };
  5885. var eventEmitter = null;
  5886. /**
  5887. * Currently focused video "src"(displayed in large video).
  5888. * @type {String}
  5889. */
  5890. var focusedVideoInfo = null;
  5891. /**
  5892. * Indicates if we have muted our audio before the conference has started.
  5893. * @type {boolean}
  5894. */
  5895. var preMuted = false;
  5896. var mutedAudios = {};
  5897. var flipXLocalVideo = true;
  5898. var currentVideoWidth = null;
  5899. var currentVideoHeight = null;
  5900. var localVideoSrc = null;
  5901. function videoactive( videoelem) {
  5902. if (videoelem.attr('id').indexOf('mixedmslabel') === -1) {
  5903. // ignore mixedmslabela0 and v0
  5904. videoelem.show();
  5905. VideoLayout.resizeThumbnails();
  5906. var videoParent = videoelem.parent();
  5907. var parentResourceJid = null;
  5908. if (videoParent)
  5909. parentResourceJid
  5910. = VideoLayout.getPeerContainerResourceJid(videoParent[0]);
  5911. // Update the large video to the last added video only if there's no
  5912. // current dominant, focused speaker or prezi playing or update it to
  5913. // the current dominant speaker.
  5914. if ((!focusedVideoInfo &&
  5915. !VideoLayout.getDominantSpeakerResourceJid() &&
  5916. !require("../prezi/Prezi").isPresentationVisible()) ||
  5917. (parentResourceJid &&
  5918. VideoLayout.getDominantSpeakerResourceJid() === parentResourceJid)) {
  5919. VideoLayout.updateLargeVideo(
  5920. APP.RTC.getVideoSrc(videoelem[0]),
  5921. 1,
  5922. parentResourceJid);
  5923. }
  5924. VideoLayout.showModeratorIndicator();
  5925. }
  5926. }
  5927. function waitForRemoteVideo(selector, ssrc, stream, jid) {
  5928. // XXX(gp) so, every call to this function is *always* preceded by a call
  5929. // to the RTC.attachMediaStream() function but that call is *not* followed
  5930. // by an update to the videoSrcToSsrc map!
  5931. //
  5932. // The above way of doing things results in video SRCs that don't correspond
  5933. // to any SSRC for a short period of time (to be more precise, for as long
  5934. // the waitForRemoteVideo takes to complete). This causes problems (see
  5935. // bellow).
  5936. //
  5937. // I'm wondering why we need to do that; i.e. why call RTC.attachMediaStream()
  5938. // a second time in here and only then update the videoSrcToSsrc map? Why
  5939. // not simply update the videoSrcToSsrc map when the RTC.attachMediaStream()
  5940. // is called the first time? I actually do that in the lastN changed event
  5941. // handler because the "orphan" video SRC is causing troubles there. The
  5942. // purpose of this method would then be to fire the "videoactive.jingle".
  5943. //
  5944. // Food for though I guess :-)
  5945. if (selector.removed || !selector.parent().is(":visible")) {
  5946. console.warn("Media removed before had started", selector);
  5947. return;
  5948. }
  5949. if (stream.id === 'mixedmslabel') return;
  5950. if (selector[0].currentTime > 0) {
  5951. var videoStream = APP.simulcast.getReceivingVideoStream(stream);
  5952. APP.RTC.attachMediaStream(selector, videoStream); // FIXME: why do i have to do this for FF?
  5953. videoactive(selector);
  5954. } else {
  5955. setTimeout(function () {
  5956. waitForRemoteVideo(selector, ssrc, stream, jid);
  5957. }, 250);
  5958. }
  5959. }
  5960. /**
  5961. * Returns an array of the video horizontal and vertical indents,
  5962. * so that if fits its parent.
  5963. *
  5964. * @return an array with 2 elements, the horizontal indent and the vertical
  5965. * indent
  5966. */
  5967. function getCameraVideoPosition(videoWidth,
  5968. videoHeight,
  5969. videoSpaceWidth,
  5970. videoSpaceHeight) {
  5971. // Parent height isn't completely calculated when we position the video in
  5972. // full screen mode and this is why we use the screen height in this case.
  5973. // Need to think it further at some point and implement it properly.
  5974. var isFullScreen = document.fullScreen ||
  5975. document.mozFullScreen ||
  5976. document.webkitIsFullScreen;
  5977. if (isFullScreen)
  5978. videoSpaceHeight = window.innerHeight;
  5979. var horizontalIndent = (videoSpaceWidth - videoWidth) / 2;
  5980. var verticalIndent = (videoSpaceHeight - videoHeight) / 2;
  5981. return [horizontalIndent, verticalIndent];
  5982. }
  5983. /**
  5984. * Returns an array of the video horizontal and vertical indents.
  5985. * Centers horizontally and top aligns vertically.
  5986. *
  5987. * @return an array with 2 elements, the horizontal indent and the vertical
  5988. * indent
  5989. */
  5990. function getDesktopVideoPosition(videoWidth,
  5991. videoHeight,
  5992. videoSpaceWidth,
  5993. videoSpaceHeight) {
  5994. var horizontalIndent = (videoSpaceWidth - videoWidth) / 2;
  5995. var verticalIndent = 0;// Top aligned
  5996. return [horizontalIndent, verticalIndent];
  5997. }
  5998. /**
  5999. * Returns an array of the video dimensions, so that it covers the screen.
  6000. * It leaves no empty areas, but some parts of the video might not be visible.
  6001. *
  6002. * @return an array with 2 elements, the video width and the video height
  6003. */
  6004. function getCameraVideoSize(videoWidth,
  6005. videoHeight,
  6006. videoSpaceWidth,
  6007. videoSpaceHeight) {
  6008. if (!videoWidth)
  6009. videoWidth = currentVideoWidth;
  6010. if (!videoHeight)
  6011. videoHeight = currentVideoHeight;
  6012. var aspectRatio = videoWidth / videoHeight;
  6013. var availableWidth = Math.max(videoWidth, videoSpaceWidth);
  6014. var availableHeight = Math.max(videoHeight, videoSpaceHeight);
  6015. if (availableWidth / aspectRatio < videoSpaceHeight) {
  6016. availableHeight = videoSpaceHeight;
  6017. availableWidth = availableHeight * aspectRatio;
  6018. }
  6019. if (availableHeight * aspectRatio < videoSpaceWidth) {
  6020. availableWidth = videoSpaceWidth;
  6021. availableHeight = availableWidth / aspectRatio;
  6022. }
  6023. return [availableWidth, availableHeight];
  6024. }
  6025. /**
  6026. * Sets the display name for the given video span id.
  6027. */
  6028. function setDisplayName(videoSpanId, displayName, key) {
  6029. var nameSpan = $('#' + videoSpanId + '>span.displayname');
  6030. var defaultLocalDisplayName = APP.translation.generateTranslatonHTML(
  6031. interfaceConfig.DEFAULT_LOCAL_DISPLAY_NAME);
  6032. // If we already have a display name for this video.
  6033. if (nameSpan.length > 0) {
  6034. var nameSpanElement = nameSpan.get(0);
  6035. if (nameSpanElement.id === 'localDisplayName' &&
  6036. $('#localDisplayName').text() !== displayName) {
  6037. if (displayName && displayName.length > 0)
  6038. {
  6039. var meHTML = APP.translation.generateTranslatonHTML("me");
  6040. $('#localDisplayName').html(displayName + ' (' + meHTML + ')');
  6041. }
  6042. else
  6043. $('#localDisplayName').html(defaultLocalDisplayName);
  6044. } else {
  6045. if (displayName && displayName.length > 0)
  6046. {
  6047. $('#' + videoSpanId + '_name').html(displayName);
  6048. }
  6049. else if (key && key.length > 0)
  6050. {
  6051. var nameHtml = APP.translation.generateTranslatonHTML(key);
  6052. $('#' + videoSpanId + '_name').html(nameHtml);
  6053. }
  6054. else
  6055. $('#' + videoSpanId + '_name').text(
  6056. interfaceConfig.DEFAULT_REMOTE_DISPLAY_NAME);
  6057. }
  6058. } else {
  6059. var editButton = null;
  6060. nameSpan = document.createElement('span');
  6061. nameSpan.className = 'displayname';
  6062. $('#' + videoSpanId)[0].appendChild(nameSpan);
  6063. if (videoSpanId === 'localVideoContainer') {
  6064. editButton = createEditDisplayNameButton();
  6065. if (displayName && displayName.length > 0) {
  6066. var meHTML = APP.translation.generateTranslatonHTML("me");
  6067. nameSpan.innerHTML = displayName + meHTML;
  6068. }
  6069. else
  6070. nameSpan.innerHTML = defaultLocalDisplayName;
  6071. }
  6072. else {
  6073. if (displayName && displayName.length > 0) {
  6074. nameSpan.innerText = displayName;
  6075. }
  6076. else
  6077. nameSpan.innerText = interfaceConfig.DEFAULT_REMOTE_DISPLAY_NAME;
  6078. }
  6079. if (!editButton) {
  6080. nameSpan.id = videoSpanId + '_name';
  6081. } else {
  6082. nameSpan.id = 'localDisplayName';
  6083. $('#' + videoSpanId)[0].appendChild(editButton);
  6084. //translates popover of edit button
  6085. APP.translation.translateElement($("a.displayname"));
  6086. var editableText = document.createElement('input');
  6087. editableText.className = 'displayname';
  6088. editableText.type = 'text';
  6089. editableText.id = 'editDisplayName';
  6090. if (displayName && displayName.length) {
  6091. editableText.value
  6092. = displayName;
  6093. }
  6094. var defaultNickname = APP.translation.translateString(
  6095. "defaultNickname", {name: "Jane Pink"});
  6096. editableText.setAttribute('style', 'display:none;');
  6097. editableText.setAttribute('data-18n',
  6098. '[placeholder]defaultNickname');
  6099. editableText.setAttribute("data-i18n-options",
  6100. JSON.stringify({name: "Jane Pink"}));
  6101. editableText.setAttribute("placeholder", defaultNickname);
  6102. $('#' + videoSpanId)[0].appendChild(editableText);
  6103. $('#localVideoContainer .displayname')
  6104. .bind("click", function (e) {
  6105. e.preventDefault();
  6106. e.stopPropagation();
  6107. $('#localDisplayName').hide();
  6108. $('#editDisplayName').show();
  6109. $('#editDisplayName').focus();
  6110. $('#editDisplayName').select();
  6111. $('#editDisplayName').one("focusout", function (e) {
  6112. VideoLayout.inputDisplayNameHandler(this.value);
  6113. });
  6114. $('#editDisplayName').on('keydown', function (e) {
  6115. if (e.keyCode === 13) {
  6116. e.preventDefault();
  6117. VideoLayout.inputDisplayNameHandler(this.value);
  6118. }
  6119. });
  6120. });
  6121. }
  6122. }
  6123. }
  6124. /**
  6125. * Gets the selector of video thumbnail container for the user identified by
  6126. * given <tt>userJid</tt>
  6127. * @param resourceJid user's Jid for whom we want to get the video container.
  6128. */
  6129. function getParticipantContainer(resourceJid)
  6130. {
  6131. if (!resourceJid)
  6132. return null;
  6133. if (resourceJid === APP.xmpp.myResource())
  6134. return $("#localVideoContainer");
  6135. else
  6136. return $("#participant_" + resourceJid);
  6137. }
  6138. /**
  6139. * Sets the size and position of the given video element.
  6140. *
  6141. * @param video the video element to position
  6142. * @param width the desired video width
  6143. * @param height the desired video height
  6144. * @param horizontalIndent the left and right indent
  6145. * @param verticalIndent the top and bottom indent
  6146. */
  6147. function positionVideo(video,
  6148. width,
  6149. height,
  6150. horizontalIndent,
  6151. verticalIndent) {
  6152. video.width(width);
  6153. video.height(height);
  6154. video.css({ top: verticalIndent + 'px',
  6155. bottom: verticalIndent + 'px',
  6156. left: horizontalIndent + 'px',
  6157. right: horizontalIndent + 'px'});
  6158. }
  6159. /**
  6160. * Adds the remote video menu element for the given <tt>jid</tt> in the
  6161. * given <tt>parentElement</tt>.
  6162. *
  6163. * @param jid the jid indicating the video for which we're adding a menu.
  6164. * @param parentElement the parent element where this menu will be added
  6165. */
  6166. function addRemoteVideoMenu(jid, parentElement) {
  6167. var spanElement = document.createElement('span');
  6168. spanElement.className = 'remotevideomenu';
  6169. parentElement.appendChild(spanElement);
  6170. var menuElement = document.createElement('i');
  6171. menuElement.className = 'fa fa-angle-down';
  6172. menuElement.title = 'Remote user controls';
  6173. spanElement.appendChild(menuElement);
  6174. // <ul class="popupmenu">
  6175. // <li><a href="#">Mute</a></li>
  6176. // <li><a href="#">Eject</a></li>
  6177. // </ul>
  6178. var popupmenuElement = document.createElement('ul');
  6179. popupmenuElement.className = 'popupmenu';
  6180. popupmenuElement.id
  6181. = 'remote_popupmenu_' + Strophe.getResourceFromJid(jid);
  6182. spanElement.appendChild(popupmenuElement);
  6183. var muteMenuItem = document.createElement('li');
  6184. var muteLinkItem = document.createElement('a');
  6185. var mutedIndicator = "<i style='float:left;' class='icon-mic-disabled'></i>";
  6186. if (!mutedAudios[jid]) {
  6187. muteLinkItem.innerHTML = mutedIndicator +
  6188. " <div style='width: 90px;margin-left: 20px;' data-i18n='videothumbnail.domute'></div>";
  6189. muteLinkItem.className = 'mutelink';
  6190. }
  6191. else {
  6192. muteLinkItem.innerHTML = mutedIndicator +
  6193. " <div style='width: 90px;margin-left: 20px;' data-i18n='videothumbnail.muted'></div>";
  6194. muteLinkItem.className = 'mutelink disabled';
  6195. }
  6196. muteLinkItem.onclick = function(){
  6197. if ($(this).attr('disabled') != undefined) {
  6198. event.preventDefault();
  6199. }
  6200. var isMute = mutedAudios[jid] == true;
  6201. APP.xmpp.setMute(jid, !isMute);
  6202. popupmenuElement.setAttribute('style', 'display:none;');
  6203. if (isMute) {
  6204. this.innerHTML = mutedIndicator +
  6205. " <div style='width: 90px;margin-left: 20px;' data-i18n='videothumbnail.muted'></div>";
  6206. this.className = 'mutelink disabled';
  6207. }
  6208. else {
  6209. this.innerHTML = mutedIndicator +
  6210. " <div style='width: 90px;margin-left: 20px;' data-i18n='videothumbnail.domute'></div>";
  6211. this.className = 'mutelink';
  6212. }
  6213. };
  6214. muteMenuItem.appendChild(muteLinkItem);
  6215. popupmenuElement.appendChild(muteMenuItem);
  6216. var ejectIndicator = "<i style='float:left;' class='fa fa-eject'></i>";
  6217. var ejectMenuItem = document.createElement('li');
  6218. var ejectLinkItem = document.createElement('a');
  6219. var ejectText = "<div style='width: 90px;margin-left: 20px;' data-i18n='videothumbnail.kick'>&nbsp;</div>";
  6220. ejectLinkItem.innerHTML = ejectIndicator + ' ' + ejectText;
  6221. ejectLinkItem.onclick = function(){
  6222. APP.xmpp.eject(jid);
  6223. popupmenuElement.setAttribute('style', 'display:none;');
  6224. };
  6225. ejectMenuItem.appendChild(ejectLinkItem);
  6226. popupmenuElement.appendChild(ejectMenuItem);
  6227. var paddingSpan = document.createElement('span');
  6228. paddingSpan.className = 'popupmenuPadding';
  6229. popupmenuElement.appendChild(paddingSpan);
  6230. APP.translation.translateElement($("#" + popupmenuElement.id + " > li > a > div"));
  6231. }
  6232. /**
  6233. * Removes remote video menu element from video element identified by
  6234. * given <tt>videoElementId</tt>.
  6235. *
  6236. * @param videoElementId the id of local or remote video element.
  6237. */
  6238. function removeRemoteVideoMenu(videoElementId) {
  6239. var menuSpan = $('#' + videoElementId + '>span.remotevideomenu');
  6240. if (menuSpan.length) {
  6241. menuSpan.remove();
  6242. }
  6243. }
  6244. /**
  6245. * Updates the data for the indicator
  6246. * @param id the id of the indicator
  6247. * @param percent the percent for connection quality
  6248. * @param object the data
  6249. */
  6250. function updateStatsIndicator(id, percent, object) {
  6251. if(VideoLayout.connectionIndicators[id])
  6252. VideoLayout.connectionIndicators[id].updateConnectionQuality(percent, object);
  6253. }
  6254. /**
  6255. * Returns an array of the video dimensions, so that it keeps it's aspect
  6256. * ratio and fits available area with it's larger dimension. This method
  6257. * ensures that whole video will be visible and can leave empty areas.
  6258. *
  6259. * @return an array with 2 elements, the video width and the video height
  6260. */
  6261. function getDesktopVideoSize(videoWidth,
  6262. videoHeight,
  6263. videoSpaceWidth,
  6264. videoSpaceHeight) {
  6265. if (!videoWidth)
  6266. videoWidth = currentVideoWidth;
  6267. if (!videoHeight)
  6268. videoHeight = currentVideoHeight;
  6269. var aspectRatio = videoWidth / videoHeight;
  6270. var availableWidth = Math.max(videoWidth, videoSpaceWidth);
  6271. var availableHeight = Math.max(videoHeight, videoSpaceHeight);
  6272. videoSpaceHeight -= $('#remoteVideos').outerHeight();
  6273. if (availableWidth / aspectRatio >= videoSpaceHeight)
  6274. {
  6275. availableHeight = videoSpaceHeight;
  6276. availableWidth = availableHeight * aspectRatio;
  6277. }
  6278. if (availableHeight * aspectRatio >= videoSpaceWidth)
  6279. {
  6280. availableWidth = videoSpaceWidth;
  6281. availableHeight = availableWidth / aspectRatio;
  6282. }
  6283. return [availableWidth, availableHeight];
  6284. }
  6285. /**
  6286. * Creates the edit display name button.
  6287. *
  6288. * @returns the edit button
  6289. */
  6290. function createEditDisplayNameButton() {
  6291. var editButton = document.createElement('a');
  6292. editButton.className = 'displayname';
  6293. UIUtil.setTooltip(editButton,
  6294. "videothumbnail.editnickname",
  6295. "top");
  6296. editButton.innerHTML = '<i class="fa fa-pencil"></i>';
  6297. return editButton;
  6298. }
  6299. /**
  6300. * Creates the element indicating the moderator(owner) of the conference.
  6301. *
  6302. * @param parentElement the parent element where the owner indicator will
  6303. * be added
  6304. */
  6305. function createModeratorIndicatorElement(parentElement) {
  6306. var moderatorIndicator = document.createElement('i');
  6307. moderatorIndicator.className = 'fa fa-star';
  6308. parentElement.appendChild(moderatorIndicator);
  6309. UIUtil.setTooltip(parentElement,
  6310. "videothumbnail.moderator",
  6311. "top");
  6312. }
  6313. var VideoLayout = (function (my) {
  6314. my.connectionIndicators = {};
  6315. // By default we use camera
  6316. my.getVideoSize = getCameraVideoSize;
  6317. my.getVideoPosition = getCameraVideoPosition;
  6318. my.init = function (emitter) {
  6319. // Listen for large video size updates
  6320. document.getElementById('largeVideo')
  6321. .addEventListener('loadedmetadata', function (e) {
  6322. currentVideoWidth = this.videoWidth;
  6323. currentVideoHeight = this.videoHeight;
  6324. VideoLayout.positionLarge(currentVideoWidth, currentVideoHeight);
  6325. });
  6326. eventEmitter = emitter;
  6327. };
  6328. my.isInLastN = function(resource) {
  6329. return lastNCount < 0 // lastN is disabled, return true
  6330. || (lastNCount > 0 && lastNEndpointsCache.length == 0) // lastNEndpoints cache not built yet, return true
  6331. || (lastNEndpointsCache && lastNEndpointsCache.indexOf(resource) !== -1);
  6332. };
  6333. my.changeLocalStream = function (stream) {
  6334. VideoLayout.changeLocalVideo(stream);
  6335. };
  6336. my.changeLocalAudio = function(stream) {
  6337. APP.RTC.attachMediaStream($('#localAudio'), stream.getOriginalStream());
  6338. document.getElementById('localAudio').autoplay = true;
  6339. document.getElementById('localAudio').volume = 0;
  6340. if (preMuted) {
  6341. if(!APP.UI.setAudioMuted(true))
  6342. {
  6343. preMuted = mute;
  6344. }
  6345. preMuted = false;
  6346. }
  6347. };
  6348. my.changeLocalVideo = function(stream) {
  6349. var flipX = true;
  6350. if(stream.videoType == "screen")
  6351. flipX = false;
  6352. var localVideo = document.createElement('video');
  6353. localVideo.id = 'localVideo_' +
  6354. APP.RTC.getStreamID(stream.getOriginalStream());
  6355. localVideo.autoplay = true;
  6356. localVideo.volume = 0; // is it required if audio is separated ?
  6357. localVideo.oncontextmenu = function () { return false; };
  6358. var localVideoContainer = document.getElementById('localVideoWrapper');
  6359. localVideoContainer.appendChild(localVideo);
  6360. // Set default display name.
  6361. setDisplayName('localVideoContainer');
  6362. if(!VideoLayout.connectionIndicators["localVideoContainer"]) {
  6363. VideoLayout.connectionIndicators["localVideoContainer"]
  6364. = new ConnectionIndicator($("#localVideoContainer")[0], null, VideoLayout);
  6365. }
  6366. AudioLevels.updateAudioLevelCanvas(null, VideoLayout);
  6367. var localVideoSelector = $('#' + localVideo.id);
  6368. function localVideoClick(event) {
  6369. event.stopPropagation();
  6370. VideoLayout.handleVideoThumbClicked(
  6371. APP.RTC.getVideoSrc(localVideo),
  6372. false,
  6373. APP.xmpp.myResource());
  6374. }
  6375. // Add click handler to both video and video wrapper elements in case
  6376. // there's no video.
  6377. localVideoSelector.click(localVideoClick);
  6378. $('#localVideoContainer').click(localVideoClick);
  6379. // Add hover handler
  6380. $('#localVideoContainer').hover(
  6381. function() {
  6382. VideoLayout.showDisplayName('localVideoContainer', true);
  6383. },
  6384. function() {
  6385. if (!VideoLayout.isLargeVideoVisible()
  6386. || APP.RTC.getVideoSrc(localVideo) !== APP.RTC.getVideoSrc($('#largeVideo')[0]))
  6387. VideoLayout.showDisplayName('localVideoContainer', false);
  6388. }
  6389. );
  6390. // Add stream ended handler
  6391. stream.getOriginalStream().onended = function () {
  6392. localVideoContainer.removeChild(localVideo);
  6393. VideoLayout.updateRemovedVideo(APP.RTC.getVideoSrc(localVideo));
  6394. };
  6395. // Flip video x axis if needed
  6396. flipXLocalVideo = flipX;
  6397. if (flipX) {
  6398. localVideoSelector.addClass("flipVideoX");
  6399. }
  6400. // Attach WebRTC stream
  6401. var videoStream = APP.simulcast.getLocalVideoStream();
  6402. APP.RTC.attachMediaStream(localVideoSelector, videoStream);
  6403. localVideoSrc = APP.RTC.getVideoSrc(localVideo);
  6404. var myResourceJid = APP.xmpp.myResource();
  6405. VideoLayout.updateLargeVideo(localVideoSrc, 0,
  6406. myResourceJid);
  6407. };
  6408. /**
  6409. * Adds or removes icons for not available camera and microphone.
  6410. * @param resourceJid the jid of user
  6411. * @param devices available devices
  6412. */
  6413. my.setDeviceAvailabilityIcons = function (resourceJid, devices) {
  6414. if(!devices)
  6415. return;
  6416. var container = null
  6417. if(!resourceJid)
  6418. {
  6419. container = $("#localVideoContainer")[0];
  6420. }
  6421. else
  6422. {
  6423. container = $("#participant_" + resourceJid)[0];
  6424. }
  6425. if(!container)
  6426. return;
  6427. $("#" + container.id + " > .noMic").remove();
  6428. $("#" + container.id + " > .noVideo").remove();
  6429. if(!devices.audio)
  6430. {
  6431. container.appendChild(document.createElement("div")).setAttribute("class","noMic");
  6432. }
  6433. if(!devices.video)
  6434. {
  6435. container.appendChild(document.createElement("div")).setAttribute("class","noVideo");
  6436. }
  6437. if(!devices.audio && !devices.video)
  6438. {
  6439. $("#" + container.id + " > .noMic").css("background-position", "75%");
  6440. $("#" + container.id + " > .noVideo").css("background-position", "25%");
  6441. $("#" + container.id + " > .noVideo").css("background-color", "transparent");
  6442. }
  6443. }
  6444. /**
  6445. * Checks if removed video is currently displayed and tries to display
  6446. * another one instead.
  6447. * @param removedVideoSrc src stream identifier of the video.
  6448. */
  6449. my.updateRemovedVideo = function(removedVideoSrc) {
  6450. if (removedVideoSrc === APP.RTC.getVideoSrc($('#largeVideo')[0])) {
  6451. // this is currently displayed as large
  6452. // pick the last visible video in the row
  6453. // if nobody else is left, this picks the local video
  6454. var pick
  6455. = $('#remoteVideos>span[id!="mixedstream"]:visible:last>video')
  6456. .get(0);
  6457. if (!pick) {
  6458. console.info("Last visible video no longer exists");
  6459. pick = $('#remoteVideos>span[id!="mixedstream"]>video').get(0);
  6460. if (!pick || !APP.RTC.getVideoSrc(pick)) {
  6461. // Try local video
  6462. console.info("Fallback to local video...");
  6463. pick = $('#remoteVideos>span>span>video').get(0);
  6464. }
  6465. }
  6466. // mute if localvideo
  6467. if (pick) {
  6468. var container = pick.parentNode;
  6469. var jid = null;
  6470. if(container)
  6471. {
  6472. if(container.id == "localVideoWrapper")
  6473. {
  6474. jid = APP.xmpp.myResource();
  6475. }
  6476. else
  6477. {
  6478. jid = VideoLayout.getPeerContainerResourceJid(container);
  6479. }
  6480. }
  6481. VideoLayout.updateLargeVideo(APP.RTC.getVideoSrc(pick), pick.volume, jid);
  6482. } else {
  6483. console.warn("Failed to elect large video");
  6484. }
  6485. }
  6486. };
  6487. my.onRemoteStreamAdded = function (stream) {
  6488. var container;
  6489. var remotes = document.getElementById('remoteVideos');
  6490. if (stream.peerjid) {
  6491. VideoLayout.ensurePeerContainerExists(stream.peerjid);
  6492. container = document.getElementById(
  6493. 'participant_' + Strophe.getResourceFromJid(stream.peerjid));
  6494. } else {
  6495. var id = stream.getOriginalStream().id;
  6496. if (id !== 'mixedmslabel'
  6497. // FIXME: default stream is added always with new focus
  6498. // (to be investigated)
  6499. && id !== 'default') {
  6500. console.error('can not associate stream',
  6501. id,
  6502. 'with a participant');
  6503. // We don't want to add it here since it will cause troubles
  6504. return;
  6505. }
  6506. // FIXME: for the mixed ms we dont need a video -- currently
  6507. container = document.createElement('span');
  6508. container.id = 'mixedstream';
  6509. container.className = 'videocontainer';
  6510. remotes.appendChild(container);
  6511. UIUtil.playSoundNotification('userJoined');
  6512. }
  6513. if (container) {
  6514. VideoLayout.addRemoteStreamElement( container,
  6515. stream.sid,
  6516. stream.getOriginalStream(),
  6517. stream.peerjid,
  6518. stream.ssrc);
  6519. }
  6520. }
  6521. my.getLargeVideoState = function () {
  6522. return largeVideoState;
  6523. };
  6524. /**
  6525. * Updates the large video with the given new video source.
  6526. */
  6527. my.updateLargeVideo = function(newSrc, vol, resourceJid) {
  6528. console.log('hover in', newSrc);
  6529. if (APP.RTC.getVideoSrc($('#largeVideo')[0]) !== newSrc) {
  6530. $('#activeSpeaker').css('visibility', 'hidden');
  6531. // Due to the simulcast the localVideoSrc may have changed when the
  6532. // fadeOut event triggers. In that case the getJidFromVideoSrc and
  6533. // isVideoSrcDesktop methods will not function correctly.
  6534. //
  6535. // Also, again due to the simulcast, the updateLargeVideo method can
  6536. // be called multiple times almost simultaneously. Therefore, we
  6537. // store the state here and update only once.
  6538. largeVideoState.newSrc = newSrc;
  6539. largeVideoState.isVisible = $('#largeVideo').is(':visible');
  6540. largeVideoState.isDesktop = APP.RTC.isVideoSrcDesktop(
  6541. APP.xmpp.findJidFromResource(resourceJid));
  6542. if(largeVideoState.userResourceJid) {
  6543. largeVideoState.oldResourceJid = largeVideoState.userResourceJid;
  6544. } else {
  6545. largeVideoState.oldResourceJid = null;
  6546. }
  6547. largeVideoState.userResourceJid = resourceJid;
  6548. // Screen stream is already rotated
  6549. largeVideoState.flipX = (newSrc === localVideoSrc) && flipXLocalVideo;
  6550. var userChanged = false;
  6551. if (largeVideoState.oldResourceJid !== largeVideoState.userResourceJid) {
  6552. userChanged = true;
  6553. // we want the notification to trigger even if userJid is undefined,
  6554. // or null.
  6555. eventEmitter.emit(UIEvents.SELECTED_ENDPOINT,
  6556. largeVideoState.userResourceJid);
  6557. }
  6558. if (!largeVideoState.updateInProgress) {
  6559. largeVideoState.updateInProgress = true;
  6560. var doUpdate = function () {
  6561. Avatar.updateActiveSpeakerAvatarSrc(
  6562. APP.xmpp.findJidFromResource(
  6563. largeVideoState.userResourceJid));
  6564. if (!userChanged && largeVideoState.preload &&
  6565. largeVideoState.preload !== null &&
  6566. APP.RTC.getVideoSrc($(largeVideoState.preload)[0]) === newSrc)
  6567. {
  6568. console.info('Switching to preloaded video');
  6569. var attributes = $('#largeVideo').prop("attributes");
  6570. // loop through largeVideo attributes and apply them on
  6571. // preload.
  6572. $.each(attributes, function () {
  6573. if (this.name !== 'id' && this.name !== 'src') {
  6574. largeVideoState.preload.attr(this.name, this.value);
  6575. }
  6576. });
  6577. largeVideoState.preload.appendTo($('#largeVideoContainer'));
  6578. $('#largeVideo').attr('id', 'previousLargeVideo');
  6579. largeVideoState.preload.attr('id', 'largeVideo');
  6580. $('#previousLargeVideo').remove();
  6581. largeVideoState.preload.on('loadedmetadata', function (e) {
  6582. currentVideoWidth = this.videoWidth;
  6583. currentVideoHeight = this.videoHeight;
  6584. VideoLayout.positionLarge(currentVideoWidth, currentVideoHeight);
  6585. });
  6586. largeVideoState.preload = null;
  6587. largeVideoState.preload_ssrc = 0;
  6588. } else {
  6589. APP.RTC.setVideoSrc($('#largeVideo')[0], largeVideoState.newSrc);
  6590. }
  6591. var videoTransform = document.getElementById('largeVideo')
  6592. .style.webkitTransform;
  6593. if (largeVideoState.flipX && videoTransform !== 'scaleX(-1)') {
  6594. document.getElementById('largeVideo').style.webkitTransform
  6595. = "scaleX(-1)";
  6596. }
  6597. else if (!largeVideoState.flipX && videoTransform === 'scaleX(-1)') {
  6598. document.getElementById('largeVideo').style.webkitTransform
  6599. = "none";
  6600. }
  6601. // Change the way we'll be measuring and positioning large video
  6602. VideoLayout.getVideoSize = largeVideoState.isDesktop
  6603. ? getDesktopVideoSize
  6604. : getCameraVideoSize;
  6605. VideoLayout.getVideoPosition = largeVideoState.isDesktop
  6606. ? getDesktopVideoPosition
  6607. : getCameraVideoPosition;
  6608. // Only if the large video is currently visible.
  6609. // Disable previous dominant speaker video.
  6610. if (largeVideoState.oldResourceJid) {
  6611. VideoLayout.enableDominantSpeaker(
  6612. largeVideoState.oldResourceJid,
  6613. false);
  6614. }
  6615. // Enable new dominant speaker in the remote videos section.
  6616. if (largeVideoState.userResourceJid) {
  6617. VideoLayout.enableDominantSpeaker(
  6618. largeVideoState.userResourceJid,
  6619. true);
  6620. }
  6621. if (userChanged && largeVideoState.isVisible) {
  6622. // using "this" should be ok because we're called
  6623. // from within the fadeOut event.
  6624. $(this).fadeIn(300);
  6625. }
  6626. if(userChanged) {
  6627. Avatar.showUserAvatar(
  6628. APP.xmpp.findJidFromResource(
  6629. largeVideoState.oldResourceJid));
  6630. }
  6631. largeVideoState.updateInProgress = false;
  6632. };
  6633. if (userChanged) {
  6634. $('#largeVideo').fadeOut(300, doUpdate);
  6635. } else {
  6636. doUpdate();
  6637. }
  6638. }
  6639. } else {
  6640. Avatar.showUserAvatar(
  6641. APP.xmpp.findJidFromResource(
  6642. largeVideoState.userResourceJid));
  6643. }
  6644. };
  6645. my.handleVideoThumbClicked = function(videoSrc,
  6646. noPinnedEndpointChangedEvent,
  6647. resourceJid) {
  6648. // Restore style for previously focused video
  6649. var oldContainer = null;
  6650. if(focusedVideoInfo) {
  6651. var focusResourceJid = focusedVideoInfo.resourceJid;
  6652. oldContainer = getParticipantContainer(focusResourceJid);
  6653. }
  6654. if (oldContainer) {
  6655. oldContainer.removeClass("videoContainerFocused");
  6656. }
  6657. // Unlock current focused.
  6658. if (focusedVideoInfo && focusedVideoInfo.src === videoSrc)
  6659. {
  6660. focusedVideoInfo = null;
  6661. var dominantSpeakerVideo = null;
  6662. // Enable the currently set dominant speaker.
  6663. if (currentDominantSpeaker) {
  6664. dominantSpeakerVideo
  6665. = $('#participant_' + currentDominantSpeaker + '>video')
  6666. .get(0);
  6667. if (dominantSpeakerVideo) {
  6668. VideoLayout.updateLargeVideo(
  6669. APP.RTC.getVideoSrc(dominantSpeakerVideo),
  6670. 1,
  6671. currentDominantSpeaker);
  6672. }
  6673. }
  6674. if (!noPinnedEndpointChangedEvent) {
  6675. eventEmitter.emit(UIEvents.PINNED_ENDPOINT);
  6676. }
  6677. return;
  6678. }
  6679. // Lock new video
  6680. focusedVideoInfo = {
  6681. src: videoSrc,
  6682. resourceJid: resourceJid
  6683. };
  6684. // Update focused/pinned interface.
  6685. if (resourceJid)
  6686. {
  6687. var container = getParticipantContainer(resourceJid);
  6688. container.addClass("videoContainerFocused");
  6689. if (!noPinnedEndpointChangedEvent) {
  6690. eventEmitter.emit(UIEvents.PINNED_ENDPOINT, resourceJid);
  6691. }
  6692. }
  6693. if ($('#largeVideo').attr('src') === videoSrc &&
  6694. VideoLayout.isLargeVideoOnTop()) {
  6695. return;
  6696. }
  6697. // Triggers a "video.selected" event. The "false" parameter indicates
  6698. // this isn't a prezi.
  6699. $(document).trigger("video.selected", [false]);
  6700. VideoLayout.updateLargeVideo(videoSrc, 1, resourceJid);
  6701. $('audio').each(function (idx, el) {
  6702. if (el.id.indexOf('mixedmslabel') !== -1) {
  6703. el.volume = 0;
  6704. el.volume = 1;
  6705. }
  6706. });
  6707. };
  6708. /**
  6709. * Positions the large video.
  6710. *
  6711. * @param videoWidth the stream video width
  6712. * @param videoHeight the stream video height
  6713. */
  6714. my.positionLarge = function (videoWidth, videoHeight) {
  6715. var videoSpaceWidth = $('#videospace').width();
  6716. var videoSpaceHeight = window.innerHeight;
  6717. var videoSize = VideoLayout.getVideoSize(videoWidth,
  6718. videoHeight,
  6719. videoSpaceWidth,
  6720. videoSpaceHeight);
  6721. var largeVideoWidth = videoSize[0];
  6722. var largeVideoHeight = videoSize[1];
  6723. var videoPosition = VideoLayout.getVideoPosition(largeVideoWidth,
  6724. largeVideoHeight,
  6725. videoSpaceWidth,
  6726. videoSpaceHeight);
  6727. var horizontalIndent = videoPosition[0];
  6728. var verticalIndent = videoPosition[1];
  6729. positionVideo($('#largeVideo'),
  6730. largeVideoWidth,
  6731. largeVideoHeight,
  6732. horizontalIndent, verticalIndent);
  6733. };
  6734. /**
  6735. * Shows/hides the large video.
  6736. */
  6737. my.setLargeVideoVisible = function(isVisible) {
  6738. var resourceJid = largeVideoState.userResourceJid;
  6739. if (isVisible) {
  6740. $('#largeVideo').css({visibility: 'visible'});
  6741. $('.watermark').css({visibility: 'visible'});
  6742. VideoLayout.enableDominantSpeaker(resourceJid, true);
  6743. }
  6744. else {
  6745. $('#largeVideo').css({visibility: 'hidden'});
  6746. $('#activeSpeaker').css('visibility', 'hidden');
  6747. $('.watermark').css({visibility: 'hidden'});
  6748. VideoLayout.enableDominantSpeaker(resourceJid, false);
  6749. if(focusedVideoInfo) {
  6750. var focusResourceJid = focusedVideoInfo.resourceJid;
  6751. var oldContainer = getParticipantContainer(focusResourceJid);
  6752. if (oldContainer && oldContainer.length > 0) {
  6753. oldContainer.removeClass("videoContainerFocused");
  6754. }
  6755. focusedVideoInfo = null;
  6756. if(focusResourceJid) {
  6757. Avatar.showUserAvatar(
  6758. APP.xmpp.findJidFromResource(focusResourceJid));
  6759. }
  6760. }
  6761. }
  6762. };
  6763. /**
  6764. * Indicates if the large video is currently visible.
  6765. *
  6766. * @return <tt>true</tt> if visible, <tt>false</tt> - otherwise
  6767. */
  6768. my.isLargeVideoVisible = function() {
  6769. return $('#largeVideo').is(':visible');
  6770. };
  6771. my.isLargeVideoOnTop = function () {
  6772. var Etherpad = require("../etherpad/Etherpad");
  6773. var Prezi = require("../prezi/Prezi");
  6774. return !Prezi.isPresentationVisible() && !Etherpad.isVisible();
  6775. };
  6776. /**
  6777. * Checks if container for participant identified by given peerJid exists
  6778. * in the document and creates it eventually.
  6779. *
  6780. * @param peerJid peer Jid to check.
  6781. * @param userId user email or id for setting the avatar
  6782. *
  6783. * @return Returns <tt>true</tt> if the peer container exists,
  6784. * <tt>false</tt> - otherwise
  6785. */
  6786. my.ensurePeerContainerExists = function(peerJid, userId) {
  6787. ContactList.ensureAddContact(peerJid, userId);
  6788. var resourceJid = Strophe.getResourceFromJid(peerJid);
  6789. var videoSpanId = 'participant_' + resourceJid;
  6790. if (!$('#' + videoSpanId).length) {
  6791. var container =
  6792. VideoLayout.addRemoteVideoContainer(peerJid, videoSpanId, userId);
  6793. Avatar.setUserAvatar(peerJid, userId);
  6794. // Set default display name.
  6795. setDisplayName(videoSpanId);
  6796. VideoLayout.connectionIndicators[videoSpanId] =
  6797. new ConnectionIndicator(container, peerJid, VideoLayout);
  6798. var nickfield = document.createElement('span');
  6799. nickfield.className = "nick";
  6800. nickfield.appendChild(document.createTextNode(resourceJid));
  6801. container.appendChild(nickfield);
  6802. // In case this is not currently in the last n we don't show it.
  6803. if (localLastNCount
  6804. && localLastNCount > 0
  6805. && $('#remoteVideos>span').length >= localLastNCount + 2) {
  6806. showPeerContainer(resourceJid, 'hide');
  6807. }
  6808. else
  6809. VideoLayout.resizeThumbnails();
  6810. }
  6811. };
  6812. my.addRemoteVideoContainer = function(peerJid, spanId) {
  6813. var container = document.createElement('span');
  6814. container.id = spanId;
  6815. container.className = 'videocontainer';
  6816. var remotes = document.getElementById('remoteVideos');
  6817. remotes.appendChild(container);
  6818. // If the peerJid is null then this video span couldn't be directly
  6819. // associated with a participant (this could happen in the case of prezi).
  6820. if (APP.xmpp.isModerator() && peerJid !== null)
  6821. addRemoteVideoMenu(peerJid, container);
  6822. AudioLevels.updateAudioLevelCanvas(peerJid, VideoLayout);
  6823. return container;
  6824. };
  6825. /**
  6826. * Creates an audio or video stream element.
  6827. */
  6828. my.createStreamElement = function (sid, stream) {
  6829. var isVideo = stream.getVideoTracks().length > 0;
  6830. var element = isVideo
  6831. ? document.createElement('video')
  6832. : document.createElement('audio');
  6833. var id = (isVideo ? 'remoteVideo_' : 'remoteAudio_')
  6834. + sid + '_' + APP.RTC.getStreamID(stream);
  6835. element.id = id;
  6836. element.autoplay = true;
  6837. element.oncontextmenu = function () { return false; };
  6838. return element;
  6839. };
  6840. my.addRemoteStreamElement
  6841. = function (container, sid, stream, peerJid, thessrc) {
  6842. var newElementId = null;
  6843. var isVideo = stream.getVideoTracks().length > 0;
  6844. if (container) {
  6845. var streamElement = VideoLayout.createStreamElement(sid, stream);
  6846. newElementId = streamElement.id;
  6847. container.appendChild(streamElement);
  6848. var sel = $('#' + newElementId);
  6849. sel.hide();
  6850. // If the container is currently visible we attach the stream.
  6851. if (!isVideo
  6852. || (container.offsetParent !== null && isVideo)) {
  6853. var videoStream = APP.simulcast.getReceivingVideoStream(stream);
  6854. APP.RTC.attachMediaStream(sel, videoStream);
  6855. if (isVideo)
  6856. waitForRemoteVideo(sel, thessrc, stream, peerJid);
  6857. }
  6858. stream.onended = function () {
  6859. console.log('stream ended', this);
  6860. VideoLayout.removeRemoteStreamElement(
  6861. stream, isVideo, container, newElementId);
  6862. // NOTE(gp) it seems that under certain circumstances, the
  6863. // onended event is not fired and thus the contact list is not
  6864. // updated.
  6865. //
  6866. // The onended event of a stream should be fired when the SSRCs
  6867. // corresponding to that stream are removed from the SDP; but
  6868. // this doesn't seem to always be the case, resulting in ghost
  6869. // contacts.
  6870. //
  6871. // In an attempt to fix the ghost contacts problem, I'm moving
  6872. // the removeContact() method call in app.js, inside the
  6873. // 'muc.left' event handler.
  6874. //if (peerJid)
  6875. // ContactList.removeContact(peerJid);
  6876. };
  6877. // Add click handler.
  6878. container.onclick = function (event) {
  6879. /*
  6880. * FIXME It turns out that videoThumb may not exist (if there is
  6881. * no actual video).
  6882. */
  6883. var videoThumb = $('#' + container.id + '>video').get(0);
  6884. if (videoThumb) {
  6885. VideoLayout.handleVideoThumbClicked(
  6886. APP.RTC.getVideoSrc(videoThumb),
  6887. false,
  6888. Strophe.getResourceFromJid(peerJid));
  6889. }
  6890. event.stopPropagation();
  6891. event.preventDefault();
  6892. return false;
  6893. };
  6894. // Add hover handler
  6895. $(container).hover(
  6896. function() {
  6897. VideoLayout.showDisplayName(container.id, true);
  6898. },
  6899. function() {
  6900. var videoSrc = null;
  6901. if ($('#' + container.id + '>video')
  6902. && $('#' + container.id + '>video').length > 0) {
  6903. videoSrc = APP.RTC.getVideoSrc($('#' + container.id + '>video').get(0));
  6904. }
  6905. // If the video has been "pinned" by the user we want to
  6906. // keep the display name on place.
  6907. if (!VideoLayout.isLargeVideoVisible()
  6908. || videoSrc !== APP.RTC.getVideoSrc($('#largeVideo')[0]))
  6909. VideoLayout.showDisplayName(container.id, false);
  6910. }
  6911. );
  6912. }
  6913. return newElementId;
  6914. };
  6915. /**
  6916. * Removes the remote stream element corresponding to the given stream and
  6917. * parent container.
  6918. *
  6919. * @param stream the stream
  6920. * @param isVideo <tt>true</tt> if given <tt>stream</tt> is a video one.
  6921. * @param container
  6922. */
  6923. my.removeRemoteStreamElement = function (stream, isVideo, container, id) {
  6924. if (!container)
  6925. return;
  6926. var select = null;
  6927. var removedVideoSrc = null;
  6928. if (isVideo) {
  6929. select = $('#' + id);
  6930. removedVideoSrc = APP.RTC.getVideoSrc(select.get(0));
  6931. }
  6932. else
  6933. select = $('#' + container.id + '>audio');
  6934. // Mark video as removed to cancel waiting loop(if video is removed
  6935. // before has started)
  6936. select.removed = true;
  6937. select.remove();
  6938. var audioCount = $('#' + container.id + '>audio').length;
  6939. var videoCount = $('#' + container.id + '>video').length;
  6940. if (!audioCount && !videoCount) {
  6941. console.log("Remove whole user", container.id);
  6942. if(VideoLayout.connectionIndicators[container.id])
  6943. VideoLayout.connectionIndicators[container.id].remove();
  6944. // Remove whole container
  6945. container.remove();
  6946. UIUtil.playSoundNotification('userLeft');
  6947. VideoLayout.resizeThumbnails();
  6948. }
  6949. if (removedVideoSrc)
  6950. VideoLayout.updateRemovedVideo(removedVideoSrc);
  6951. };
  6952. /**
  6953. * Show/hide peer container for the given resourceJid.
  6954. */
  6955. function showPeerContainer(resourceJid, state) {
  6956. var peerContainer = $('#participant_' + resourceJid);
  6957. if (!peerContainer)
  6958. return;
  6959. var isHide = state === 'hide';
  6960. var resizeThumbnails = false;
  6961. if (!isHide) {
  6962. if (!peerContainer.is(':visible')) {
  6963. resizeThumbnails = true;
  6964. peerContainer.show();
  6965. }
  6966. var jid = APP.xmpp.findJidFromResource(resourceJid);
  6967. if (state == 'show')
  6968. {
  6969. // peerContainer.css('-webkit-filter', '');
  6970. Avatar.showUserAvatar(jid, false);
  6971. }
  6972. else // if (state == 'avatar')
  6973. {
  6974. // peerContainer.css('-webkit-filter', 'grayscale(100%)');
  6975. Avatar.showUserAvatar(jid, true);
  6976. }
  6977. }
  6978. else if (peerContainer.is(':visible') && isHide)
  6979. {
  6980. resizeThumbnails = true;
  6981. peerContainer.hide();
  6982. if(VideoLayout.connectionIndicators['participant_' + resourceJid])
  6983. VideoLayout.connectionIndicators['participant_' + resourceJid].hide();
  6984. }
  6985. if (resizeThumbnails) {
  6986. VideoLayout.resizeThumbnails();
  6987. }
  6988. // We want to be able to pin a participant from the contact list, even
  6989. // if he's not in the lastN set!
  6990. // ContactList.setClickable(resourceJid, !isHide);
  6991. };
  6992. my.inputDisplayNameHandler = function (name) {
  6993. NicknameHandler.setNickname(name);
  6994. if (!$('#localDisplayName').is(":visible")) {
  6995. if (NicknameHandler.getNickname())
  6996. {
  6997. var meHTML = APP.translation.generateTranslatonHTML("me");
  6998. $('#localDisplayName').html(NicknameHandler.getNickname() + " (" + meHTML + ")");
  6999. }
  7000. else
  7001. {
  7002. var defaultHTML = APP.translation.generateTranslatonHTML(
  7003. interfaceConfig.DEFAULT_LOCAL_DISPLAY_NAME);
  7004. $('#localDisplayName')
  7005. .html(defaultHTML);
  7006. }
  7007. $('#localDisplayName').show();
  7008. }
  7009. $('#editDisplayName').hide();
  7010. };
  7011. /**
  7012. * Shows/hides the display name on the remote video.
  7013. * @param videoSpanId the identifier of the video span element
  7014. * @param isShow indicates if the display name should be shown or hidden
  7015. */
  7016. my.showDisplayName = function(videoSpanId, isShow) {
  7017. var nameSpan = $('#' + videoSpanId + '>span.displayname').get(0);
  7018. if (isShow) {
  7019. if (nameSpan && nameSpan.innerHTML && nameSpan.innerHTML.length)
  7020. nameSpan.setAttribute("style", "display:inline-block;");
  7021. }
  7022. else {
  7023. if (nameSpan)
  7024. nameSpan.setAttribute("style", "display:none;");
  7025. }
  7026. };
  7027. /**
  7028. * Shows the presence status message for the given video.
  7029. */
  7030. my.setPresenceStatus = function (videoSpanId, statusMsg) {
  7031. if (!$('#' + videoSpanId).length) {
  7032. // No container
  7033. return;
  7034. }
  7035. var statusSpan = $('#' + videoSpanId + '>span.status');
  7036. if (!statusSpan.length) {
  7037. //Add status span
  7038. statusSpan = document.createElement('span');
  7039. statusSpan.className = 'status';
  7040. statusSpan.id = videoSpanId + '_status';
  7041. $('#' + videoSpanId)[0].appendChild(statusSpan);
  7042. statusSpan = $('#' + videoSpanId + '>span.status');
  7043. }
  7044. // Display status
  7045. if (statusMsg && statusMsg.length) {
  7046. $('#' + videoSpanId + '_status').text(statusMsg);
  7047. statusSpan.get(0).setAttribute("style", "display:inline-block;");
  7048. }
  7049. else {
  7050. // Hide
  7051. statusSpan.get(0).setAttribute("style", "display:none;");
  7052. }
  7053. };
  7054. /**
  7055. * Shows a visual indicator for the moderator of the conference.
  7056. */
  7057. my.showModeratorIndicator = function () {
  7058. var isModerator = APP.xmpp.isModerator();
  7059. if (isModerator) {
  7060. var indicatorSpan = $('#localVideoContainer .focusindicator');
  7061. if (indicatorSpan.children().length === 0)
  7062. {
  7063. createModeratorIndicatorElement(indicatorSpan[0]);
  7064. //translates text in focus indicator
  7065. APP.translation.translateElement($('#localVideoContainer .focusindicator'));
  7066. }
  7067. }
  7068. var members = APP.xmpp.getMembers();
  7069. Object.keys(members).forEach(function (jid) {
  7070. if (Strophe.getResourceFromJid(jid) === 'focus') {
  7071. // Skip server side focus
  7072. return;
  7073. }
  7074. var resourceJid = Strophe.getResourceFromJid(jid);
  7075. var videoSpanId = 'participant_' + resourceJid;
  7076. var videoContainer = document.getElementById(videoSpanId);
  7077. if (!videoContainer) {
  7078. console.error("No video container for " + jid);
  7079. return;
  7080. }
  7081. var member = members[jid];
  7082. if (member.role === 'moderator') {
  7083. // Remove menu if peer is moderator
  7084. var menuSpan = $('#' + videoSpanId + '>span.remotevideomenu');
  7085. if (menuSpan.length) {
  7086. removeRemoteVideoMenu(videoSpanId);
  7087. }
  7088. // Show moderator indicator
  7089. var indicatorSpan
  7090. = $('#' + videoSpanId + ' .focusindicator');
  7091. if (!indicatorSpan || indicatorSpan.length === 0) {
  7092. indicatorSpan = document.createElement('span');
  7093. indicatorSpan.className = 'focusindicator';
  7094. videoContainer.appendChild(indicatorSpan);
  7095. createModeratorIndicatorElement(indicatorSpan);
  7096. //translates text in focus indicators
  7097. APP.translation.translateElement($('#' + videoSpanId + ' .focusindicator'));
  7098. }
  7099. } else if (isModerator) {
  7100. // We are moderator, but user is not - add menu
  7101. if ($('#remote_popupmenu_' + resourceJid).length <= 0) {
  7102. addRemoteVideoMenu(
  7103. jid,
  7104. document.getElementById('participant_' + resourceJid));
  7105. }
  7106. }
  7107. });
  7108. };
  7109. /**
  7110. * Shows video muted indicator over small videos.
  7111. */
  7112. my.showVideoIndicator = function(videoSpanId, isMuted) {
  7113. var videoMutedSpan = $('#' + videoSpanId + '>span.videoMuted');
  7114. if (isMuted === 'false') {
  7115. if (videoMutedSpan.length > 0) {
  7116. videoMutedSpan.remove();
  7117. }
  7118. }
  7119. else {
  7120. if(videoMutedSpan.length == 0) {
  7121. videoMutedSpan = document.createElement('span');
  7122. videoMutedSpan.className = 'videoMuted';
  7123. $('#' + videoSpanId)[0].appendChild(videoMutedSpan);
  7124. var mutedIndicator = document.createElement('i');
  7125. mutedIndicator.className = 'icon-camera-disabled';
  7126. UIUtil.setTooltip(mutedIndicator,
  7127. "videothumbnail.videomute",
  7128. "top");
  7129. videoMutedSpan.appendChild(mutedIndicator);
  7130. //translate texts for muted indicator
  7131. APP.translation.translateElement($('#' + videoSpanId + " > span > i"));
  7132. }
  7133. VideoLayout.updateMutePosition(videoSpanId);
  7134. }
  7135. };
  7136. my.updateMutePosition = function (videoSpanId) {
  7137. var audioMutedSpan = $('#' + videoSpanId + '>span.audioMuted');
  7138. var connectionIndicator = $('#' + videoSpanId + '>div.connectionindicator');
  7139. var videoMutedSpan = $('#' + videoSpanId + '>span.videoMuted');
  7140. if(connectionIndicator.length > 0
  7141. && connectionIndicator[0].style.display != "none") {
  7142. audioMutedSpan.css({right: "23px"});
  7143. videoMutedSpan.css({right: ((audioMutedSpan.length > 0? 23 : 0) + 30) + "px"});
  7144. }
  7145. else
  7146. {
  7147. audioMutedSpan.css({right: "0px"});
  7148. videoMutedSpan.css({right: (audioMutedSpan.length > 0? 30 : 0) + "px"});
  7149. }
  7150. }
  7151. /**
  7152. * Shows audio muted indicator over small videos.
  7153. * @param {string} isMuted
  7154. */
  7155. my.showAudioIndicator = function(videoSpanId, isMuted) {
  7156. var audioMutedSpan = $('#' + videoSpanId + '>span.audioMuted');
  7157. if (isMuted === 'false') {
  7158. if (audioMutedSpan.length > 0) {
  7159. audioMutedSpan.popover('hide');
  7160. audioMutedSpan.remove();
  7161. }
  7162. }
  7163. else {
  7164. if(audioMutedSpan.length == 0 ) {
  7165. audioMutedSpan = document.createElement('span');
  7166. audioMutedSpan.className = 'audioMuted';
  7167. UIUtil.setTooltip(audioMutedSpan,
  7168. "videothumbnail.mute",
  7169. "top");
  7170. $('#' + videoSpanId)[0].appendChild(audioMutedSpan);
  7171. APP.translation.translateElement($('#' + videoSpanId + " > span"));
  7172. var mutedIndicator = document.createElement('i');
  7173. mutedIndicator.className = 'icon-mic-disabled';
  7174. audioMutedSpan.appendChild(mutedIndicator);
  7175. }
  7176. VideoLayout.updateMutePosition(videoSpanId);
  7177. }
  7178. };
  7179. /*
  7180. * Shows or hides the audio muted indicator over the local thumbnail video.
  7181. * @param {boolean} isMuted
  7182. */
  7183. my.showLocalAudioIndicator = function(isMuted) {
  7184. VideoLayout.showAudioIndicator('localVideoContainer', isMuted.toString());
  7185. };
  7186. /**
  7187. * Resizes the large video container.
  7188. */
  7189. my.resizeLargeVideoContainer = function () {
  7190. Chat.resizeChat();
  7191. var availableHeight = window.innerHeight;
  7192. var availableWidth = UIUtil.getAvailableVideoWidth();
  7193. if (availableWidth < 0 || availableHeight < 0) return;
  7194. $('#videospace').width(availableWidth);
  7195. $('#videospace').height(availableHeight);
  7196. $('#largeVideoContainer').width(availableWidth);
  7197. $('#largeVideoContainer').height(availableHeight);
  7198. var avatarSize = interfaceConfig.ACTIVE_SPEAKER_AVATAR_SIZE;
  7199. var top = availableHeight / 2 - avatarSize / 4 * 3;
  7200. $('#activeSpeaker').css('top', top);
  7201. VideoLayout.resizeThumbnails();
  7202. };
  7203. /**
  7204. * Resizes thumbnails.
  7205. */
  7206. my.resizeThumbnails = function() {
  7207. var videoSpaceWidth = $('#remoteVideos').width();
  7208. var thumbnailSize = VideoLayout.calculateThumbnailSize(videoSpaceWidth);
  7209. var width = thumbnailSize[0];
  7210. var height = thumbnailSize[1];
  7211. // size videos so that while keeping AR and max height, we have a
  7212. // nice fit
  7213. $('#remoteVideos').height(height);
  7214. $('#remoteVideos>span').width(width);
  7215. $('#remoteVideos>span').height(height);
  7216. $('.userAvatar').css('left', (width - height) / 2);
  7217. $(document).trigger("remotevideo.resized", [width, height]);
  7218. };
  7219. /**
  7220. * Enables the dominant speaker UI.
  7221. *
  7222. * @param resourceJid the jid indicating the video element to
  7223. * activate/deactivate
  7224. * @param isEnable indicates if the dominant speaker should be enabled or
  7225. * disabled
  7226. */
  7227. my.enableDominantSpeaker = function(resourceJid, isEnable) {
  7228. var videoSpanId = null;
  7229. var videoContainerId = null;
  7230. if (resourceJid
  7231. === APP.xmpp.myResource()) {
  7232. videoSpanId = 'localVideoWrapper';
  7233. videoContainerId = 'localVideoContainer';
  7234. }
  7235. else {
  7236. videoSpanId = 'participant_' + resourceJid;
  7237. videoContainerId = videoSpanId;
  7238. }
  7239. var displayName = resourceJid;
  7240. var nameSpan = $('#' + videoContainerId + '>span.displayname');
  7241. if (nameSpan.length > 0)
  7242. displayName = nameSpan.html();
  7243. console.log("UI enable dominant speaker",
  7244. displayName,
  7245. resourceJid,
  7246. isEnable);
  7247. videoSpan = document.getElementById(videoContainerId);
  7248. if (!videoSpan) {
  7249. return;
  7250. }
  7251. var video = $('#' + videoSpanId + '>video');
  7252. if (video && video.length > 0) {
  7253. if (isEnable) {
  7254. var isLargeVideoVisible = VideoLayout.isLargeVideoOnTop();
  7255. VideoLayout.showDisplayName(videoContainerId, isLargeVideoVisible);
  7256. if (!videoSpan.classList.contains("dominantspeaker"))
  7257. videoSpan.classList.add("dominantspeaker");
  7258. }
  7259. else {
  7260. VideoLayout.showDisplayName(videoContainerId, false);
  7261. if (videoSpan.classList.contains("dominantspeaker"))
  7262. videoSpan.classList.remove("dominantspeaker");
  7263. }
  7264. Avatar.showUserAvatar(
  7265. APP.xmpp.findJidFromResource(resourceJid));
  7266. }
  7267. };
  7268. /**
  7269. * Calculates the thumbnail size.
  7270. *
  7271. * @param videoSpaceWidth the width of the video space
  7272. */
  7273. my.calculateThumbnailSize = function (videoSpaceWidth) {
  7274. // Calculate the available height, which is the inner window height minus
  7275. // 39px for the header minus 2px for the delimiter lines on the top and
  7276. // bottom of the large video, minus the 36px space inside the remoteVideos
  7277. // container used for highlighting shadow.
  7278. var availableHeight = 100;
  7279. var numvids = $('#remoteVideos>span:visible').length;
  7280. if (localLastNCount && localLastNCount > 0) {
  7281. numvids = Math.min(localLastNCount + 1, numvids);
  7282. }
  7283. // Remove the 3px borders arround videos and border around the remote
  7284. // videos area and the 4 pixels between the local video and the others
  7285. //TODO: Find out where the 4 pixels come from and remove them
  7286. var availableWinWidth = videoSpaceWidth - 2 * 3 * numvids - 70 - 4;
  7287. var availableWidth = availableWinWidth / numvids;
  7288. var aspectRatio = 16.0 / 9.0;
  7289. var maxHeight = Math.min(160, availableHeight);
  7290. availableHeight = Math.min(maxHeight, availableWidth / aspectRatio);
  7291. if (availableHeight < availableWidth / aspectRatio) {
  7292. availableWidth = Math.floor(availableHeight * aspectRatio);
  7293. }
  7294. return [availableWidth, availableHeight];
  7295. };
  7296. /**
  7297. * Updates the remote video menu.
  7298. *
  7299. * @param jid the jid indicating the video for which we're adding a menu.
  7300. * @param isMuted indicates the current mute state
  7301. */
  7302. my.updateRemoteVideoMenu = function(jid, isMuted) {
  7303. var muteMenuItem
  7304. = $('#remote_popupmenu_'
  7305. + Strophe.getResourceFromJid(jid)
  7306. + '>li>a.mutelink');
  7307. var mutedIndicator = "<i class='icon-mic-disabled'></i>";
  7308. if (muteMenuItem.length) {
  7309. var muteLink = muteMenuItem.get(0);
  7310. if (isMuted === 'true') {
  7311. muteLink.innerHTML = mutedIndicator + ' Muted';
  7312. muteLink.className = 'mutelink disabled';
  7313. }
  7314. else {
  7315. muteLink.innerHTML = mutedIndicator + ' Mute';
  7316. muteLink.className = 'mutelink';
  7317. }
  7318. }
  7319. };
  7320. /**
  7321. * Returns the current dominant speaker resource jid.
  7322. */
  7323. my.getDominantSpeakerResourceJid = function () {
  7324. return currentDominantSpeaker;
  7325. };
  7326. /**
  7327. * Returns the corresponding resource jid to the given peer container
  7328. * DOM element.
  7329. *
  7330. * @return the corresponding resource jid to the given peer container
  7331. * DOM element
  7332. */
  7333. my.getPeerContainerResourceJid = function (containerElement) {
  7334. var i = containerElement.id.indexOf('participant_');
  7335. if (i >= 0)
  7336. return containerElement.id.substring(i + 12);
  7337. };
  7338. /**
  7339. * On contact list item clicked.
  7340. */
  7341. $(ContactList).bind('contactclicked', function(event, jid) {
  7342. if (!jid) {
  7343. return;
  7344. }
  7345. var resource = Strophe.getResourceFromJid(jid);
  7346. var videoContainer = $("#participant_" + resource);
  7347. if (videoContainer.length > 0) {
  7348. var videoThumb = $('video', videoContainer).get(0);
  7349. // It is not always the case that a videoThumb exists (if there is
  7350. // no actual video).
  7351. if (videoThumb) {
  7352. if (videoThumb.src && videoThumb.src != '') {
  7353. // We have a video src, great! Let's update the large video
  7354. // now.
  7355. VideoLayout.handleVideoThumbClicked(
  7356. videoThumb.src,
  7357. false,
  7358. Strophe.getResourceFromJid(jid));
  7359. } else {
  7360. // If we don't have a video src for jid, there's absolutely
  7361. // no point in calling handleVideoThumbClicked; Quite
  7362. // simply, it won't work because it needs an src to attach
  7363. // to the large video.
  7364. //
  7365. // Instead, we trigger the pinned endpoint changed event to
  7366. // let the bridge adjust its lastN set for myjid and store
  7367. // the pinned user in the lastNPickupJid variable to be
  7368. // picked up later by the lastN changed event handler.
  7369. lastNPickupJid = jid;
  7370. eventEmitter.emit(UIEvents.PINNED_ENDPOINT,
  7371. Strophe.getResourceFromJid(jid));
  7372. }
  7373. } else if (jid == APP.xmpp.myJid()) {
  7374. $("#localVideoContainer").click();
  7375. }
  7376. }
  7377. });
  7378. /**
  7379. * On audio muted event.
  7380. */
  7381. $(document).bind('audiomuted.muc', function (event, jid, isMuted) {
  7382. /*
  7383. // FIXME: but focus can not mute in this case ? - check
  7384. if (jid === xmpp.myJid()) {
  7385. // The local mute indicator is controlled locally
  7386. return;
  7387. }*/
  7388. var videoSpanId = null;
  7389. if (jid === APP.xmpp.myJid()) {
  7390. videoSpanId = 'localVideoContainer';
  7391. } else {
  7392. VideoLayout.ensurePeerContainerExists(jid);
  7393. videoSpanId = 'participant_' + Strophe.getResourceFromJid(jid);
  7394. }
  7395. mutedAudios[jid] = isMuted;
  7396. if (APP.xmpp.isModerator()) {
  7397. VideoLayout.updateRemoteVideoMenu(jid, isMuted);
  7398. }
  7399. if (videoSpanId)
  7400. VideoLayout.showAudioIndicator(videoSpanId, isMuted);
  7401. });
  7402. /**
  7403. * On video muted event.
  7404. */
  7405. $(document).bind('videomuted.muc', function (event, jid, value) {
  7406. var isMuted = (value === "true");
  7407. if(jid !== APP.xmpp.myJid() && !APP.RTC.muteRemoteVideoStream(jid, isMuted))
  7408. return;
  7409. Avatar.showUserAvatar(jid, isMuted);
  7410. var videoSpanId = null;
  7411. if (jid === APP.xmpp.myJid()) {
  7412. videoSpanId = 'localVideoContainer';
  7413. } else {
  7414. VideoLayout.ensurePeerContainerExists(jid);
  7415. videoSpanId = 'participant_' + Strophe.getResourceFromJid(jid);
  7416. }
  7417. if (videoSpanId)
  7418. VideoLayout.showVideoIndicator(videoSpanId, value);
  7419. });
  7420. /**
  7421. * Display name changed.
  7422. */
  7423. my.onDisplayNameChanged =
  7424. function (jid, displayName, status) {
  7425. if (jid === 'localVideoContainer'
  7426. || jid === APP.xmpp.myJid()) {
  7427. setDisplayName('localVideoContainer',
  7428. displayName);
  7429. } else {
  7430. VideoLayout.ensurePeerContainerExists(jid);
  7431. setDisplayName(
  7432. 'participant_' + Strophe.getResourceFromJid(jid),
  7433. displayName,
  7434. status);
  7435. }
  7436. };
  7437. /**
  7438. * On dominant speaker changed event.
  7439. */
  7440. my.onDominantSpeakerChanged = function (resourceJid) {
  7441. // We ignore local user events.
  7442. if (resourceJid
  7443. === APP.xmpp.myResource())
  7444. return;
  7445. var members = APP.xmpp.getMembers();
  7446. // Update the current dominant speaker.
  7447. if (resourceJid !== currentDominantSpeaker) {
  7448. var oldSpeakerVideoSpanId = "participant_" + currentDominantSpeaker,
  7449. newSpeakerVideoSpanId = "participant_" + resourceJid;
  7450. var currentJID = APP.xmpp.findJidFromResource(currentDominantSpeaker);
  7451. var newJID = APP.xmpp.findJidFromResource(resourceJid);
  7452. if(currentDominantSpeaker && (!members || !members[currentJID] ||
  7453. !members[currentJID].displayName)) {
  7454. setDisplayName(oldSpeakerVideoSpanId, null);
  7455. }
  7456. if(resourceJid && (!members || !members[newJID] ||
  7457. !members[newJID].displayName)) {
  7458. setDisplayName(newSpeakerVideoSpanId, null,
  7459. interfaceConfig.DEFAULT_DOMINANT_SPEAKER_DISPLAY_NAME);
  7460. }
  7461. currentDominantSpeaker = resourceJid;
  7462. } else {
  7463. return;
  7464. }
  7465. // Obtain container for new dominant speaker.
  7466. var container = document.getElementById(
  7467. 'participant_' + resourceJid);
  7468. // Local video will not have container found, but that's ok
  7469. // since we don't want to switch to local video.
  7470. if (container && !focusedVideoInfo)
  7471. {
  7472. var video = container.getElementsByTagName("video");
  7473. // Update the large video if the video source is already available,
  7474. // otherwise wait for the "videoactive.jingle" event.
  7475. if (video.length && video[0].currentTime > 0)
  7476. VideoLayout.updateLargeVideo(APP.RTC.getVideoSrc(video[0]), resourceJid);
  7477. }
  7478. };
  7479. /**
  7480. * On last N change event.
  7481. *
  7482. * @param lastNEndpoints the list of last N endpoints
  7483. * @param endpointsEnteringLastN the list currently entering last N
  7484. * endpoints
  7485. */
  7486. my.onLastNEndpointsChanged = function ( lastNEndpoints,
  7487. endpointsEnteringLastN,
  7488. stream) {
  7489. if (lastNCount !== lastNEndpoints.length)
  7490. lastNCount = lastNEndpoints.length;
  7491. lastNEndpointsCache = lastNEndpoints;
  7492. // Say A, B, C, D, E, and F are in a conference and LastN = 3.
  7493. //
  7494. // If LastN drops to, say, 2, because of adaptivity, then E should see
  7495. // thumbnails for A, B and C. A and B are in E's server side LastN set,
  7496. // so E sees them. C is only in E's local LastN set.
  7497. //
  7498. // If F starts talking and LastN = 3, then E should see thumbnails for
  7499. // F, A, B. B gets "ejected" from E's server side LastN set, but it
  7500. // enters E's local LastN ejecting C.
  7501. // Increase the local LastN set size, if necessary.
  7502. if (lastNCount > localLastNCount) {
  7503. localLastNCount = lastNCount;
  7504. }
  7505. // Update the local LastN set preserving the order in which the
  7506. // endpoints appeared in the LastN/local LastN set.
  7507. var nextLocalLastNSet = lastNEndpoints.slice(0);
  7508. for (var i = 0; i < localLastNSet.length; i++) {
  7509. if (nextLocalLastNSet.length >= localLastNCount) {
  7510. break;
  7511. }
  7512. var resourceJid = localLastNSet[i];
  7513. if (nextLocalLastNSet.indexOf(resourceJid) === -1) {
  7514. nextLocalLastNSet.push(resourceJid);
  7515. }
  7516. }
  7517. localLastNSet = nextLocalLastNSet;
  7518. var updateLargeVideo = false;
  7519. // Handle LastN/local LastN changes.
  7520. $('#remoteVideos>span').each(function( index, element ) {
  7521. var resourceJid = VideoLayout.getPeerContainerResourceJid(element);
  7522. var isReceived = true;
  7523. if (resourceJid
  7524. && lastNEndpoints.indexOf(resourceJid) < 0
  7525. && localLastNSet.indexOf(resourceJid) < 0) {
  7526. console.log("Remove from last N", resourceJid);
  7527. showPeerContainer(resourceJid, 'hide');
  7528. isReceived = false;
  7529. } else if (resourceJid
  7530. && $('#participant_' + resourceJid).is(':visible')
  7531. && lastNEndpoints.indexOf(resourceJid) < 0
  7532. && localLastNSet.indexOf(resourceJid) >= 0) {
  7533. showPeerContainer(resourceJid, 'avatar');
  7534. isReceived = false;
  7535. }
  7536. if (!isReceived) {
  7537. // resourceJid has dropped out of the server side lastN set, so
  7538. // it is no longer being received. If resourceJid was being
  7539. // displayed in the large video we have to switch to another
  7540. // user.
  7541. var largeVideoResource = largeVideoState.userResourceJid;
  7542. if (!updateLargeVideo && resourceJid === largeVideoResource) {
  7543. updateLargeVideo = true;
  7544. }
  7545. }
  7546. });
  7547. if (!endpointsEnteringLastN || endpointsEnteringLastN.length < 0)
  7548. endpointsEnteringLastN = lastNEndpoints;
  7549. if (endpointsEnteringLastN && endpointsEnteringLastN.length > 0) {
  7550. endpointsEnteringLastN.forEach(function (resourceJid) {
  7551. var isVisible = $('#participant_' + resourceJid).is(':visible');
  7552. showPeerContainer(resourceJid, 'show');
  7553. if (!isVisible) {
  7554. console.log("Add to last N", resourceJid);
  7555. var jid = APP.xmpp.findJidFromResource(resourceJid);
  7556. var mediaStream = APP.RTC.remoteStreams[jid][MediaStreamType.VIDEO_TYPE];
  7557. var sel = $('#participant_' + resourceJid + '>video');
  7558. var videoStream = APP.simulcast.getReceivingVideoStream(
  7559. mediaStream.stream);
  7560. APP.RTC.attachMediaStream(sel, videoStream);
  7561. if (lastNPickupJid == mediaStream.peerjid) {
  7562. // Clean up the lastN pickup jid.
  7563. lastNPickupJid = null;
  7564. // Don't fire the events again, they've already
  7565. // been fired in the contact list click handler.
  7566. VideoLayout.handleVideoThumbClicked(
  7567. $(sel).attr('src'),
  7568. false,
  7569. Strophe.getResourceFromJid(mediaStream.peerjid));
  7570. updateLargeVideo = false;
  7571. }
  7572. waitForRemoteVideo(sel, mediaStream.ssrc, mediaStream.stream, resourceJid);
  7573. }
  7574. })
  7575. }
  7576. // The endpoint that was being shown in the large video has dropped out
  7577. // of the lastN set and there was no lastN pickup jid. We need to update
  7578. // the large video now.
  7579. if (updateLargeVideo) {
  7580. var resource, container, src;
  7581. var myResource
  7582. = APP.xmpp.myResource();
  7583. // Find out which endpoint to show in the large video.
  7584. for (var i = 0; i < lastNEndpoints.length; i++) {
  7585. resource = lastNEndpoints[i];
  7586. if (!resource || resource === myResource)
  7587. continue;
  7588. container = $("#participant_" + resource);
  7589. if (container.length == 0)
  7590. continue;
  7591. src = $('video', container).attr('src');
  7592. if (!src)
  7593. continue;
  7594. // videoSrcToSsrc needs to be update for this call to succeed.
  7595. VideoLayout.updateLargeVideo(src);
  7596. break;
  7597. }
  7598. }
  7599. };
  7600. my.onSimulcastLayersChanging = function (endpointSimulcastLayers) {
  7601. endpointSimulcastLayers.forEach(function (esl) {
  7602. var resource = esl.endpoint;
  7603. // if lastN is enabled *and* the endpoint is *not* in the lastN set,
  7604. // then ignore the event (= do not preload anything).
  7605. //
  7606. // The bridge could probably stop sending this message if it's for
  7607. // an endpoint that's not in lastN.
  7608. if (lastNCount != -1
  7609. && (lastNCount < 1 || lastNEndpointsCache.indexOf(resource) === -1)) {
  7610. return;
  7611. }
  7612. var primarySSRC = esl.simulcastLayer.primarySSRC;
  7613. // Get session and stream from primary ssrc.
  7614. var res = APP.simulcast.getReceivingVideoStreamBySSRC(primarySSRC);
  7615. var sid = res.sid;
  7616. var electedStream = res.stream;
  7617. if (sid && electedStream) {
  7618. var msid = APP.simulcast.getRemoteVideoStreamIdBySSRC(primarySSRC);
  7619. console.info([esl, primarySSRC, msid, sid, electedStream]);
  7620. var preload = (Strophe.getResourceFromJid(APP.xmpp.getJidFromSSRC(primarySSRC)) == largeVideoState.userResourceJid);
  7621. if (preload) {
  7622. if (largeVideoState.preload)
  7623. {
  7624. $(largeVideoState.preload).remove();
  7625. }
  7626. console.info('Preloading remote video');
  7627. largeVideoState.preload = $('<video autoplay></video>');
  7628. // ssrcs are unique in an rtp session
  7629. largeVideoState.preload_ssrc = primarySSRC;
  7630. APP.RTC.attachMediaStream(largeVideoState.preload, electedStream)
  7631. }
  7632. } else {
  7633. console.error('Could not find a stream or a session.', sid, electedStream);
  7634. }
  7635. });
  7636. };
  7637. /**
  7638. * On simulcast layers changed event.
  7639. */
  7640. my.onSimulcastLayersChanged = function (endpointSimulcastLayers) {
  7641. endpointSimulcastLayers.forEach(function (esl) {
  7642. var resource = esl.endpoint;
  7643. // if lastN is enabled *and* the endpoint is *not* in the lastN set,
  7644. // then ignore the event (= do not change large video/thumbnail
  7645. // SRCs).
  7646. //
  7647. // Note that even if we ignore the "changed" event in this event
  7648. // handler, the bridge must continue sending these events because
  7649. // the simulcast code in simulcast.js uses it to know what's going
  7650. // to be streamed by the bridge when/if the endpoint gets back into
  7651. // the lastN set.
  7652. if (lastNCount != -1
  7653. && (lastNCount < 1 || lastNEndpointsCache.indexOf(resource) === -1)) {
  7654. return;
  7655. }
  7656. var primarySSRC = esl.simulcastLayer.primarySSRC;
  7657. // Get session and stream from primary ssrc.
  7658. var res = APP.simulcast.getReceivingVideoStreamBySSRC(primarySSRC);
  7659. var sid = res.sid;
  7660. var electedStream = res.stream;
  7661. if (sid && electedStream) {
  7662. var msid = APP.simulcast.getRemoteVideoStreamIdBySSRC(primarySSRC);
  7663. console.info('Switching simulcast substream.');
  7664. console.info([esl, primarySSRC, msid, sid, electedStream]);
  7665. var msidParts = msid.split(' ');
  7666. var selRemoteVideo = $(['#', 'remoteVideo_', sid, '_', msidParts[0]].join(''));
  7667. var updateLargeVideo = (Strophe.getResourceFromJid(APP.xmpp.getJidFromSSRC(primarySSRC))
  7668. == largeVideoState.userResourceJid);
  7669. var updateFocusedVideoSrc = (focusedVideoInfo && focusedVideoInfo.src && focusedVideoInfo.src != '' &&
  7670. (APP.RTC.getVideoSrc(selRemoteVideo[0]) == focusedVideoInfo.src));
  7671. var electedStreamUrl;
  7672. if (largeVideoState.preload_ssrc == primarySSRC)
  7673. {
  7674. APP.RTC.setVideoSrc(selRemoteVideo[0], APP.RTC.getVideoSrc(largeVideoState.preload[0]));
  7675. }
  7676. else
  7677. {
  7678. if (largeVideoState.preload
  7679. && largeVideoState.preload != null) {
  7680. $(largeVideoState.preload).remove();
  7681. }
  7682. largeVideoState.preload_ssrc = 0;
  7683. APP.RTC.attachMediaStream(selRemoteVideo, electedStream);
  7684. }
  7685. var jid = APP.xmpp.getJidFromSSRC(primarySSRC);
  7686. if (updateLargeVideo) {
  7687. VideoLayout.updateLargeVideo(APP.RTC.getVideoSrc(selRemoteVideo[0]), null,
  7688. Strophe.getResourceFromJid(jid));
  7689. }
  7690. if (updateFocusedVideoSrc) {
  7691. focusedVideoInfo.src = APP.RTC.getVideoSrc(selRemoteVideo[0]);
  7692. }
  7693. var videoId;
  7694. if(resource == APP.xmpp.myResource())
  7695. {
  7696. videoId = "localVideoContainer";
  7697. }
  7698. else
  7699. {
  7700. videoId = "participant_" + resource;
  7701. }
  7702. var connectionIndicator = VideoLayout.connectionIndicators[videoId];
  7703. if(connectionIndicator)
  7704. connectionIndicator.updatePopoverData();
  7705. } else {
  7706. console.error('Could not find a stream or a sid.', sid, electedStream);
  7707. }
  7708. });
  7709. };
  7710. /**
  7711. * Updates local stats
  7712. * @param percent
  7713. * @param object
  7714. */
  7715. my.updateLocalConnectionStats = function (percent, object) {
  7716. var resolution = null;
  7717. if(object.resolution !== null)
  7718. {
  7719. resolution = object.resolution;
  7720. object.resolution = resolution[APP.xmpp.myJid()];
  7721. delete resolution[APP.xmpp.myJid()];
  7722. }
  7723. updateStatsIndicator("localVideoContainer", percent, object);
  7724. for(var jid in resolution)
  7725. {
  7726. if(resolution[jid] === null)
  7727. continue;
  7728. var id = 'participant_' + Strophe.getResourceFromJid(jid);
  7729. if(VideoLayout.connectionIndicators[id])
  7730. {
  7731. VideoLayout.connectionIndicators[id].updateResolution(resolution[jid]);
  7732. }
  7733. }
  7734. };
  7735. /**
  7736. * Updates remote stats.
  7737. * @param jid the jid associated with the stats
  7738. * @param percent the connection quality percent
  7739. * @param object the stats data
  7740. */
  7741. my.updateConnectionStats = function (jid, percent, object) {
  7742. var resourceJid = Strophe.getResourceFromJid(jid);
  7743. var videoSpanId = 'participant_' + resourceJid;
  7744. updateStatsIndicator(videoSpanId, percent, object);
  7745. };
  7746. /**
  7747. * Removes the connection
  7748. * @param jid
  7749. */
  7750. my.removeConnectionIndicator = function (jid) {
  7751. if(VideoLayout.connectionIndicators['participant_' + Strophe.getResourceFromJid(jid)])
  7752. VideoLayout.connectionIndicators['participant_' + Strophe.getResourceFromJid(jid)].remove();
  7753. };
  7754. /**
  7755. * Hides the connection indicator
  7756. * @param jid
  7757. */
  7758. my.hideConnectionIndicator = function (jid) {
  7759. if(VideoLayout.connectionIndicators['participant_' + Strophe.getResourceFromJid(jid)])
  7760. VideoLayout.connectionIndicators['participant_' + Strophe.getResourceFromJid(jid)].hide();
  7761. };
  7762. /**
  7763. * Hides all the indicators
  7764. */
  7765. my.onStatsStop = function () {
  7766. for(var indicator in VideoLayout.connectionIndicators)
  7767. {
  7768. VideoLayout.connectionIndicators[indicator].hideIndicator();
  7769. }
  7770. };
  7771. my.participantLeft = function (jid) {
  7772. // Unlock large video
  7773. if (focusedVideoInfo && focusedVideoInfo.jid === jid)
  7774. {
  7775. console.info("Focused video owner has left the conference");
  7776. focusedVideoInfo = null;
  7777. }
  7778. }
  7779. my.onVideoTypeChanged = function (jid) {
  7780. if(jid &&
  7781. Strophe.getResourceFromJid(jid) === largeVideoState.userResourceJid)
  7782. {
  7783. largeVideoState.isDesktop = APP.RTC.isVideoSrcDesktop(jid);
  7784. VideoLayout.getVideoSize = largeVideoState.isDesktop
  7785. ? getDesktopVideoSize
  7786. : getCameraVideoSize;
  7787. VideoLayout.getVideoPosition = largeVideoState.isDesktop
  7788. ? getDesktopVideoPosition
  7789. : getCameraVideoPosition;
  7790. VideoLayout.positionLarge(null, null);
  7791. }
  7792. }
  7793. return my;
  7794. }(VideoLayout || {}));
  7795. module.exports = VideoLayout;
  7796. },{"../../../service/RTC/MediaStreamTypes":90,"../../../service/UI/UIEvents":95,"../audio_levels/AudioLevels":10,"../avatar/Avatar":14,"../etherpad/Etherpad":15,"../prezi/Prezi":16,"../side_pannels/chat/Chat":19,"../side_pannels/contactlist/ContactList":23,"../util/NicknameHandler":30,"../util/UIUtil":31,"./ConnectionIndicator":32}],34:[function(require,module,exports){
  7797. //var nouns = [
  7798. //];
  7799. var pluralNouns = [
  7800. "Aliens", "Animals", "Antelopes", "Ants", "Apes", "Apples", "Baboons", "Bacteria", "Badgers", "Bananas", "Bats",
  7801. "Bears", "Birds", "Bonobos", "Brides", "Bugs", "Bulls", "Butterflies", "Cheetahs",
  7802. "Cherries", "Chicken", "Children", "Chimps", "Clowns", "Cows", "Creatures", "Dinosaurs", "Dogs", "Dolphins",
  7803. "Donkeys", "Dragons", "Ducks", "Dwarfs", "Eagles", "Elephants", "Elves", "FAIL", "Fathers",
  7804. "Fish", "Flowers", "Frogs", "Fruit", "Fungi", "Galaxies", "Geese", "Goats",
  7805. "Gorillas", "Hedgehogs", "Hippos", "Horses", "Hunters", "Insects", "Kids", "Knights",
  7806. "Lemons", "Lemurs", "Leopards", "LifeForms", "Lions", "Lizards", "Mice", "Monkeys", "Monsters",
  7807. "Mushrooms", "Octopodes", "Oranges", "Orangutans", "Organisms", "Pants", "Parrots", "Penguins",
  7808. "People", "Pigeons", "Pigs", "Pineapples", "Plants", "Potatoes", "Priests", "Rats", "Reptiles", "Reptilians",
  7809. "Rhinos", "Seagulls", "Sheep", "Siblings", "Snakes", "Spaghetti", "Spiders", "Squid", "Squirrels",
  7810. "Stars", "Students", "Teachers", "Tigers", "Tomatoes", "Trees", "Vampires", "Vegetables", "Viruses", "Vulcans",
  7811. "Warewolves", "Weasels", "Whales", "Witches", "Wizards", "Wolves", "Workers", "Worms", "Zebras"
  7812. ];
  7813. //var places = [
  7814. //"Pub", "University", "Airport", "Library", "Mall", "Theater", "Stadium", "Office", "Show", "Gallows", "Beach",
  7815. // "Cemetery", "Hospital", "Reception", "Restaurant", "Bar", "Church", "House", "School", "Square", "Village",
  7816. // "Cinema", "Movies", "Party", "Restroom", "End", "Jail", "PostOffice", "Station", "Circus", "Gates", "Entrance",
  7817. // "Bridge"
  7818. //];
  7819. var verbs = [
  7820. "Abandon", "Adapt", "Advertise", "Answer", "Anticipate", "Appreciate",
  7821. "Approach", "Argue", "Ask", "Bite", "Blossom", "Blush", "Breathe", "Breed", "Bribe", "Burn", "Calculate",
  7822. "Clean", "Code", "Communicate", "Compute", "Confess", "Confiscate", "Conjugate", "Conjure", "Consume",
  7823. "Contemplate", "Crawl", "Dance", "Delegate", "Devour", "Develop", "Differ", "Discuss",
  7824. "Dissolve", "Drink", "Eat", "Elaborate", "Emancipate", "Estimate", "Expire", "Extinguish",
  7825. "Extract", "FAIL", "Facilitate", "Fall", "Feed", "Finish", "Floss", "Fly", "Follow", "Fragment", "Freeze",
  7826. "Gather", "Glow", "Grow", "Hex", "Hide", "Hug", "Hurry", "Improve", "Intersect", "Investigate", "Jinx",
  7827. "Joke", "Jubilate", "Kiss", "Laugh", "Manage", "Meet", "Merge", "Move", "Object", "Observe", "Offer",
  7828. "Paint", "Participate", "Party", "Perform", "Plan", "Pursue", "Pierce", "Play", "Postpone", "Pray", "Proclaim",
  7829. "Question", "Read", "Reckon", "Rejoice", "Represent", "Resize", "Rhyme", "Scream", "Search", "Select", "Share", "Shoot",
  7830. "Shout", "Signal", "Sing", "Skate", "Sleep", "Smile", "Smoke", "Solve", "Spell", "Steer", "Stink",
  7831. "Substitute", "Swim", "Taste", "Teach", "Terminate", "Think", "Type", "Unite", "Vanish", "Worship"
  7832. ];
  7833. var adverbs = [
  7834. "Absently", "Accurately", "Accusingly", "Adorably", "AllTheTime", "Alone", "Always", "Amazingly", "Angrily",
  7835. "Anxiously", "Anywhere", "Appallingly", "Apparently", "Articulately", "Astonishingly", "Badly", "Barely",
  7836. "Beautifully", "Blindly", "Bravely", "Brightly", "Briskly", "Brutally", "Calmly", "Carefully", "Casually",
  7837. "Cautiously", "Cleverly", "Constantly", "Correctly", "Crazily", "Curiously", "Cynically", "Daily",
  7838. "Dangerously", "Deliberately", "Delicately", "Desperately", "Discreetly", "Eagerly", "Easily", "Euphoricly",
  7839. "Evenly", "Everywhere", "Exactly", "Expectantly", "Extensively", "FAIL", "Ferociously", "Fiercely", "Finely",
  7840. "Flatly", "Frequently", "Frighteningly", "Gently", "Gloriously", "Grimly", "Guiltily", "Happily",
  7841. "Hard", "Hastily", "Heroically", "High", "Highly", "Hourly", "Humbly", "Hysterically", "Immensely",
  7842. "Impartially", "Impolitely", "Indifferently", "Intensely", "Jealously", "Jovially", "Kindly", "Lazily",
  7843. "Lightly", "Loudly", "Lovingly", "Loyally", "Magnificently", "Malevolently", "Merrily", "Mightily", "Miserably",
  7844. "Mysteriously", "NOT", "Nervously", "Nicely", "Nowhere", "Objectively", "Obnoxiously", "Obsessively",
  7845. "Obviously", "Often", "Painfully", "Patiently", "Playfully", "Politely", "Poorly", "Precisely", "Promptly",
  7846. "Quickly", "Quietly", "Randomly", "Rapidly", "Rarely", "Recklessly", "Regularly", "Remorsefully", "Responsibly",
  7847. "Rudely", "Ruthlessly", "Sadly", "Scornfully", "Seamlessly", "Seldom", "Selfishly", "Seriously", "Shakily",
  7848. "Sharply", "Sideways", "Silently", "Sleepily", "Slightly", "Slowly", "Slyly", "Smoothly", "Softly", "Solemnly", "Steadily", "Sternly", "Strangely", "Strongly", "Stunningly", "Surely", "Tenderly", "Thoughtfully",
  7849. "Tightly", "Uneasily", "Vanishingly", "Violently", "Warmly", "Weakly", "Wearily", "Weekly", "Weirdly", "Well",
  7850. "Well", "Wickedly", "Wildly", "Wisely", "Wonderfully", "Yearly"
  7851. ];
  7852. var adjectives = [
  7853. "Abominable", "Accurate", "Adorable", "All", "Alleged", "Ancient", "Angry", "Angry", "Anxious", "Appalling",
  7854. "Apparent", "Astonishing", "Attractive", "Awesome", "Baby", "Bad", "Beautiful", "Benign", "Big", "Bitter",
  7855. "Blind", "Blue", "Bold", "Brave", "Bright", "Brisk", "Calm", "Camouflaged", "Casual", "Cautious",
  7856. "Choppy", "Chosen", "Clever", "Cold", "Cool", "Crawly", "Crazy", "Creepy", "Cruel", "Curious", "Cynical",
  7857. "Dangerous", "Dark", "Delicate", "Desperate", "Difficult", "Discreet", "Disguised", "Dizzy",
  7858. "Dumb", "Eager", "Easy", "Edgy", "Electric", "Elegant", "Emancipated", "Enormous", "Euphoric", "Evil",
  7859. "FAIL", "Fast", "Ferocious", "Fierce", "Fine", "Flawed", "Flying", "Foolish", "Foxy",
  7860. "Freezing", "Funny", "Furious", "Gentle", "Glorious", "Golden", "Good", "Green", "Green", "Guilty",
  7861. "Hairy", "Happy", "Hard", "Hasty", "Hazy", "Heroic", "Hostile", "Hot", "Humble", "Humongous",
  7862. "Humorous", "Hysterical", "Idealistic", "Ignorant", "Immense", "Impartial", "Impolite", "Indifferent",
  7863. "Infuriated", "Insightful", "Intense", "Interesting", "Intimidated", "Intriguing", "Jealous", "Jolly", "Jovial",
  7864. "Jumpy", "Kind", "Laughing", "Lazy", "Liquid", "Lonely", "Longing", "Loud", "Loving", "Loyal", "Macabre", "Mad",
  7865. "Magical", "Magnificent", "Malevolent", "Medieval", "Memorable", "Mere", "Merry", "Mighty",
  7866. "Mischievous", "Miserable", "Modified", "Moody", "Most", "Mysterious", "Mystical", "Needy",
  7867. "Nervous", "Nice", "Objective", "Obnoxious", "Obsessive", "Obvious", "Opinionated", "Orange",
  7868. "Painful", "Passionate", "Perfect", "Pink", "Playful", "Poisonous", "Polite", "Poor", "Popular", "Powerful",
  7869. "Precise", "Preserved", "Pretty", "Purple", "Quick", "Quiet", "Random", "Rapid", "Rare", "Real",
  7870. "Reassuring", "Reckless", "Red", "Regular", "Remorseful", "Responsible", "Rich", "Rude", "Ruthless",
  7871. "Sad", "Scared", "Scary", "Scornful", "Screaming", "Selfish", "Serious", "Shady", "Shaky", "Sharp",
  7872. "Shiny", "Shy", "Simple", "Sleepy", "Slow", "Sly", "Small", "Smart", "Smelly", "Smiling", "Smooth",
  7873. "Smug", "Sober", "Soft", "Solemn", "Square", "Square", "Steady", "Strange", "Strong",
  7874. "Stunning", "Subjective", "Successful", "Surly", "Sweet", "Tactful", "Tense",
  7875. "Thoughtful", "Tight", "Tiny", "Tolerant", "Uneasy", "Unique", "Unseen", "Warm", "Weak",
  7876. "Weird", "WellCooked", "Wild", "Wise", "Witty", "Wonderful", "Worried", "Yellow", "Young",
  7877. "Zealous"
  7878. ];
  7879. //var pronouns = [
  7880. //];
  7881. //var conjunctions = [
  7882. //"And", "Or", "For", "Above", "Before", "Against", "Between"
  7883. //];
  7884. /*
  7885. * Maps a string (category name) to the array of words from that category.
  7886. */
  7887. var CATEGORIES =
  7888. {
  7889. //"_NOUN_": nouns,
  7890. "_PLURALNOUN_": pluralNouns,
  7891. //"_PLACE_": places,
  7892. "_VERB_": verbs,
  7893. "_ADVERB_": adverbs,
  7894. "_ADJECTIVE_": adjectives
  7895. //"_PRONOUN_": pronouns,
  7896. //"_CONJUNCTION_": conjunctions,
  7897. };
  7898. var PATTERNS = [
  7899. "_ADJECTIVE__PLURALNOUN__VERB__ADVERB_"
  7900. // BeautifulFungiOrSpaghetti
  7901. //"_ADJECTIVE__PLURALNOUN__CONJUNCTION__PLURALNOUN_",
  7902. // AmazinglyScaryToy
  7903. //"_ADVERB__ADJECTIVE__NOUN_",
  7904. // NeitherTrashNorRifle
  7905. //"Neither_NOUN_Nor_NOUN_",
  7906. //"Either_NOUN_Or_NOUN_",
  7907. // EitherCopulateOrInvestigate
  7908. //"Either_VERB_Or_VERB_",
  7909. //"Neither_VERB_Nor_VERB_",
  7910. //"The_ADJECTIVE__ADJECTIVE__NOUN_",
  7911. //"The_ADVERB__ADJECTIVE__NOUN_",
  7912. //"The_ADVERB__ADJECTIVE__NOUN_s",
  7913. //"The_ADVERB__ADJECTIVE__PLURALNOUN__VERB_",
  7914. // WolvesComputeBadly
  7915. //"_PLURALNOUN__VERB__ADVERB_",
  7916. // UniteFacilitateAndMerge
  7917. //"_VERB__VERB_And_VERB_",
  7918. //NastyWitchesAtThePub
  7919. //"_ADJECTIVE__PLURALNOUN_AtThe_PLACE_",
  7920. ];
  7921. /*
  7922. * Returns a random element from the array 'arr'
  7923. */
  7924. function randomElement(arr)
  7925. {
  7926. return arr[Math.floor(Math.random() * arr.length)];
  7927. }
  7928. /*
  7929. * Returns true if the string 's' contains one of the
  7930. * template strings.
  7931. */
  7932. function hasTemplate(s)
  7933. {
  7934. for (var template in CATEGORIES){
  7935. if (s.indexOf(template) >= 0){
  7936. return true;
  7937. }
  7938. }
  7939. }
  7940. /**
  7941. * Generates new room name.
  7942. */
  7943. var RoomNameGenerator = {
  7944. generateRoomWithoutSeparator: function()
  7945. {
  7946. // Note that if more than one pattern is available, the choice of 'name' won't be random (names from patterns
  7947. // with fewer options will have higher probability of being chosen that names from patterns with more options).
  7948. var name = randomElement(PATTERNS);
  7949. var word;
  7950. while (hasTemplate(name)){
  7951. for (var template in CATEGORIES){
  7952. word = randomElement(CATEGORIES[template]);
  7953. name = name.replace(template, word);
  7954. }
  7955. }
  7956. return name;
  7957. }
  7958. }
  7959. module.exports = RoomNameGenerator;
  7960. },{}],35:[function(require,module,exports){
  7961. var animateTimeout, updateTimeout;
  7962. var RoomNameGenerator = require("./RoomnameGenerator");
  7963. function enter_room()
  7964. {
  7965. var val = $("#enter_room_field").val();
  7966. if(!val) {
  7967. val = $("#enter_room_field").attr("room_name");
  7968. }
  7969. if (val) {
  7970. window.location.pathname = "/" + val;
  7971. }
  7972. }
  7973. function animate(word) {
  7974. var currentVal = $("#enter_room_field").attr("placeholder");
  7975. $("#enter_room_field").attr("placeholder", currentVal + word.substr(0, 1));
  7976. animateTimeout = setTimeout(function() {
  7977. animate(word.substring(1, word.length))
  7978. }, 70);
  7979. }
  7980. function update_roomname()
  7981. {
  7982. var word = RoomNameGenerator.generateRoomWithoutSeparator();
  7983. $("#enter_room_field").attr("room_name", word);
  7984. $("#enter_room_field").attr("placeholder", "");
  7985. clearTimeout(animateTimeout);
  7986. animate(word);
  7987. updateTimeout = setTimeout(update_roomname, 10000);
  7988. }
  7989. function setupWelcomePage()
  7990. {
  7991. $("#videoconference_page").hide();
  7992. $("#domain_name").text(
  7993. window.location.protocol + "//" + window.location.host + "/");
  7994. if (interfaceConfig.SHOW_JITSI_WATERMARK) {
  7995. var leftWatermarkDiv
  7996. = $("#welcome_page_header div[class='watermark leftwatermark']");
  7997. if(leftWatermarkDiv && leftWatermarkDiv.length > 0)
  7998. {
  7999. leftWatermarkDiv.css({display: 'block'});
  8000. leftWatermarkDiv.parent().get(0).href
  8001. = interfaceConfig.JITSI_WATERMARK_LINK;
  8002. }
  8003. }
  8004. if (interfaceConfig.SHOW_BRAND_WATERMARK) {
  8005. var rightWatermarkDiv
  8006. = $("#welcome_page_header div[class='watermark rightwatermark']");
  8007. if(rightWatermarkDiv && rightWatermarkDiv.length > 0) {
  8008. rightWatermarkDiv.css({display: 'block'});
  8009. rightWatermarkDiv.parent().get(0).href
  8010. = interfaceConfig.BRAND_WATERMARK_LINK;
  8011. rightWatermarkDiv.get(0).style.backgroundImage
  8012. = "url(images/rightwatermark.png)";
  8013. }
  8014. }
  8015. if (interfaceConfig.SHOW_POWERED_BY) {
  8016. $("#welcome_page_header>a[class='poweredby']")
  8017. .css({display: 'block'});
  8018. }
  8019. $("#enter_room_button").click(function()
  8020. {
  8021. enter_room();
  8022. });
  8023. $("#enter_room_field").keydown(function (event) {
  8024. if (event.keyCode === 13 /* enter */) {
  8025. enter_room();
  8026. }
  8027. });
  8028. if (!(interfaceConfig.GENERATE_ROOMNAMES_ON_WELCOME_PAGE === false)){
  8029. var updateTimeout;
  8030. var animateTimeout;
  8031. $("#reload_roomname").click(function () {
  8032. clearTimeout(updateTimeout);
  8033. clearTimeout(animateTimeout);
  8034. update_roomname();
  8035. });
  8036. $("#reload_roomname").show();
  8037. update_roomname();
  8038. }
  8039. $("#disable_welcome").click(function () {
  8040. window.localStorage.welcomePageDisabled
  8041. = $("#disable_welcome").is(":checked");
  8042. });
  8043. }
  8044. module.exports = setupWelcomePage;
  8045. },{"./RoomnameGenerator":34}],36:[function(require,module,exports){
  8046. var EventEmitter = require("events");
  8047. var eventEmitter = new EventEmitter();
  8048. var CQEvents = require("../../service/connectionquality/CQEvents");
  8049. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  8050. /**
  8051. * local stats
  8052. * @type {{}}
  8053. */
  8054. var stats = {};
  8055. /**
  8056. * remote stats
  8057. * @type {{}}
  8058. */
  8059. var remoteStats = {};
  8060. /**
  8061. * Interval for sending statistics to other participants
  8062. * @type {null}
  8063. */
  8064. var sendIntervalId = null;
  8065. /**
  8066. * Start statistics sending.
  8067. */
  8068. function startSendingStats() {
  8069. sendStats();
  8070. sendIntervalId = setInterval(sendStats, 10000);
  8071. }
  8072. /**
  8073. * Sends statistics to other participants
  8074. */
  8075. function sendStats() {
  8076. APP.xmpp.addToPresence("connectionQuality", convertToMUCStats(stats));
  8077. }
  8078. /**
  8079. * Converts statistics to format for sending through XMPP
  8080. * @param stats the statistics
  8081. * @returns {{bitrate_donwload: *, bitrate_uplpoad: *, packetLoss_total: *, packetLoss_download: *, packetLoss_upload: *}}
  8082. */
  8083. function convertToMUCStats(stats) {
  8084. return {
  8085. "bitrate_download": stats.bitrate.download,
  8086. "bitrate_upload": stats.bitrate.upload,
  8087. "packetLoss_total": stats.packetLoss.total,
  8088. "packetLoss_download": stats.packetLoss.download,
  8089. "packetLoss_upload": stats.packetLoss.upload
  8090. };
  8091. }
  8092. /**
  8093. * Converts statitistics to format used by VideoLayout
  8094. * @param stats
  8095. * @returns {{bitrate: {download: *, upload: *}, packetLoss: {total: *, download: *, upload: *}}}
  8096. */
  8097. function parseMUCStats(stats) {
  8098. return {
  8099. bitrate: {
  8100. download: stats.bitrate_download,
  8101. upload: stats.bitrate_upload
  8102. },
  8103. packetLoss: {
  8104. total: stats.packetLoss_total,
  8105. download: stats.packetLoss_download,
  8106. upload: stats.packetLoss_upload
  8107. }
  8108. };
  8109. }
  8110. var ConnectionQuality = {
  8111. init: function () {
  8112. APP.xmpp.addListener(XMPPEvents.REMOTE_STATS, this.updateRemoteStats);
  8113. APP.statistics.addConnectionStatsListener(this.updateLocalStats);
  8114. APP.statistics.addRemoteStatsStopListener(this.stopSendingStats);
  8115. },
  8116. /**
  8117. * Updates the local statistics
  8118. * @param data new statistics
  8119. */
  8120. updateLocalStats: function (data) {
  8121. stats = data;
  8122. eventEmitter.emit(CQEvents.LOCALSTATS_UPDATED, 100 - stats.packetLoss.total, stats);
  8123. if (sendIntervalId == null) {
  8124. startSendingStats();
  8125. }
  8126. },
  8127. /**
  8128. * Updates remote statistics
  8129. * @param jid the jid associated with the statistics
  8130. * @param data the statistics
  8131. */
  8132. updateRemoteStats: function (jid, data) {
  8133. if (data == null || data.packetLoss_total == null) {
  8134. eventEmitter.emit(CQEvents.REMOTESTATS_UPDATED, jid, null, null);
  8135. return;
  8136. }
  8137. remoteStats[jid] = parseMUCStats(data);
  8138. eventEmitter.emit(CQEvents.REMOTESTATS_UPDATED,
  8139. jid, 100 - data.packetLoss_total, remoteStats[jid]);
  8140. },
  8141. /**
  8142. * Stops statistics sending.
  8143. */
  8144. stopSendingStats: function () {
  8145. clearInterval(sendIntervalId);
  8146. sendIntervalId = null;
  8147. //notify UI about stopping statistics gathering
  8148. eventEmitter.emit(CQEvents.STOP);
  8149. },
  8150. /**
  8151. * Returns the local statistics.
  8152. */
  8153. getStats: function () {
  8154. return stats;
  8155. },
  8156. addListener: function (type, listener) {
  8157. eventEmitter.on(type, listener);
  8158. }
  8159. };
  8160. module.exports = ConnectionQuality;
  8161. },{"../../service/connectionquality/CQEvents":97,"../../service/xmpp/XMPPEvents":101,"events":102}],37:[function(require,module,exports){
  8162. /* global $, alert, APP, changeLocalVideo, chrome, config, getConferenceHandler,
  8163. getUserMediaWithConstraints */
  8164. /**
  8165. * Indicates that desktop stream is currently in use(for toggle purpose).
  8166. * @type {boolean}
  8167. */
  8168. var isUsingScreenStream = false;
  8169. /**
  8170. * Indicates that switch stream operation is in progress and prevent from
  8171. * triggering new events.
  8172. * @type {boolean}
  8173. */
  8174. var switchInProgress = false;
  8175. /**
  8176. * Method used to get screen sharing stream.
  8177. *
  8178. * @type {function (stream_callback, failure_callback}
  8179. */
  8180. var obtainDesktopStream = null;
  8181. /**
  8182. * Indicates whether desktop sharing extension is installed.
  8183. * @type {boolean}
  8184. */
  8185. var extInstalled = false;
  8186. /**
  8187. * Indicates whether update of desktop sharing extension is required.
  8188. * @type {boolean}
  8189. */
  8190. var extUpdateRequired = false;
  8191. /**
  8192. * Flag used to cache desktop sharing enabled state. Do not use directly as
  8193. * it can be <tt>null</tt>.
  8194. *
  8195. * @type {null|boolean}
  8196. */
  8197. var _desktopSharingEnabled = null;
  8198. var EventEmitter = require("events");
  8199. var eventEmitter = new EventEmitter();
  8200. var DesktopSharingEventTypes
  8201. = require("../../service/desktopsharing/DesktopSharingEventTypes");
  8202. /**
  8203. * Method obtains desktop stream from WebRTC 'screen' source.
  8204. * Flag 'chrome://flags/#enable-usermedia-screen-capture' must be enabled.
  8205. */
  8206. function obtainWebRTCScreen(streamCallback, failCallback) {
  8207. APP.RTC.getUserMediaWithConstraints(
  8208. ['screen'],
  8209. streamCallback,
  8210. failCallback
  8211. );
  8212. }
  8213. /**
  8214. * Constructs inline install URL for Chrome desktop streaming extension.
  8215. * The 'chromeExtensionId' must be defined in config.js.
  8216. * @returns {string}
  8217. */
  8218. function getWebStoreInstallUrl()
  8219. {
  8220. return "https://chrome.google.com/webstore/detail/" +
  8221. config.chromeExtensionId;
  8222. }
  8223. /**
  8224. * Checks whether extension update is required.
  8225. * @param minVersion minimal required version
  8226. * @param extVersion current extension version
  8227. * @returns {boolean}
  8228. */
  8229. function isUpdateRequired(minVersion, extVersion)
  8230. {
  8231. try
  8232. {
  8233. var s1 = minVersion.split('.');
  8234. var s2 = extVersion.split('.');
  8235. var len = Math.max(s1.length, s2.length);
  8236. for (var i = 0; i < len; i++)
  8237. {
  8238. var n1 = 0,
  8239. n2 = 0;
  8240. if (i < s1.length)
  8241. n1 = parseInt(s1[i]);
  8242. if (i < s2.length)
  8243. n2 = parseInt(s2[i]);
  8244. if (isNaN(n1) || isNaN(n2))
  8245. {
  8246. return true;
  8247. }
  8248. else if (n1 !== n2)
  8249. {
  8250. return n1 > n2;
  8251. }
  8252. }
  8253. // will happen if boths version has identical numbers in
  8254. // their components (even if one of them is longer, has more components)
  8255. return false;
  8256. }
  8257. catch (e)
  8258. {
  8259. console.error("Failed to parse extension version", e);
  8260. APP.UI.messageHandler.showError("dialog.error",
  8261. "dialog.detectext");
  8262. return true;
  8263. }
  8264. }
  8265. function checkExtInstalled(callback) {
  8266. if (!chrome.runtime) {
  8267. // No API, so no extension for sure
  8268. callback(false, false);
  8269. return;
  8270. }
  8271. chrome.runtime.sendMessage(
  8272. config.chromeExtensionId,
  8273. { getVersion: true },
  8274. function (response) {
  8275. if (!response || !response.version) {
  8276. // Communication failure - assume that no endpoint exists
  8277. console.warn(
  8278. "Extension not installed?: ", chrome.runtime.lastError);
  8279. callback(false, false);
  8280. return;
  8281. }
  8282. // Check installed extension version
  8283. var extVersion = response.version;
  8284. console.log('Extension version is: ' + extVersion);
  8285. var updateRequired
  8286. = isUpdateRequired(config.minChromeExtVersion, extVersion);
  8287. callback(!updateRequired, updateRequired);
  8288. }
  8289. );
  8290. }
  8291. function doGetStreamFromExtension(streamCallback, failCallback) {
  8292. // Sends 'getStream' msg to the extension.
  8293. // Extension id must be defined in the config.
  8294. chrome.runtime.sendMessage(
  8295. config.chromeExtensionId,
  8296. { getStream: true, sources: config.desktopSharingSources },
  8297. function (response) {
  8298. if (!response) {
  8299. failCallback(chrome.runtime.lastError);
  8300. return;
  8301. }
  8302. console.log("Response from extension: " + response);
  8303. if (response.streamId) {
  8304. APP.RTC.getUserMediaWithConstraints(
  8305. ['desktop'],
  8306. function (stream) {
  8307. streamCallback(stream);
  8308. },
  8309. failCallback,
  8310. null, null, null,
  8311. response.streamId);
  8312. } else {
  8313. failCallback("Extension failed to get the stream");
  8314. }
  8315. }
  8316. );
  8317. }
  8318. /**
  8319. * Asks Chrome extension to call chooseDesktopMedia and gets chrome 'desktop'
  8320. * stream for returned stream token.
  8321. */
  8322. function obtainScreenFromExtension(streamCallback, failCallback) {
  8323. if (extInstalled) {
  8324. doGetStreamFromExtension(streamCallback, failCallback);
  8325. } else {
  8326. if (extUpdateRequired) {
  8327. alert(
  8328. 'Jitsi Desktop Streamer requires update. ' +
  8329. 'Changes will take effect after next Chrome restart.');
  8330. }
  8331. chrome.webstore.install(
  8332. getWebStoreInstallUrl(),
  8333. function (arg) {
  8334. console.log("Extension installed successfully", arg);
  8335. // We need to reload the page in order to get the access to
  8336. // chrome.runtime
  8337. window.location.reload(false);
  8338. },
  8339. function (arg) {
  8340. console.log("Failed to install the extension", arg);
  8341. failCallback(arg);
  8342. APP.UI.messageHandler.showError("dialog.error",
  8343. "dialog.failtoinstall");
  8344. }
  8345. );
  8346. }
  8347. }
  8348. /**
  8349. * Call this method to toggle desktop sharing feature.
  8350. * @param method pass "ext" to use chrome extension for desktop capture(chrome
  8351. * extension required), pass "webrtc" to use WebRTC "screen" desktop
  8352. * source('chrome://flags/#enable-usermedia-screen-capture' must be
  8353. * enabled), pass any other string or nothing in order to disable this
  8354. * feature completely.
  8355. */
  8356. function setDesktopSharing(method) {
  8357. // Check if we are running chrome
  8358. if (!navigator.webkitGetUserMedia) {
  8359. obtainDesktopStream = null;
  8360. console.info("Desktop sharing disabled");
  8361. } else if (method == "ext") {
  8362. obtainDesktopStream = obtainScreenFromExtension;
  8363. console.info("Using Chrome extension for desktop sharing");
  8364. } else if (method == "webrtc") {
  8365. obtainDesktopStream = obtainWebRTCScreen;
  8366. console.info("Using Chrome WebRTC for desktop sharing");
  8367. }
  8368. // Reset enabled cache
  8369. _desktopSharingEnabled = null;
  8370. }
  8371. /**
  8372. * Initializes <link rel=chrome-webstore-item /> with extension id set in
  8373. * config.js to support inline installs. Host site must be selected as main
  8374. * website of published extension.
  8375. */
  8376. function initInlineInstalls()
  8377. {
  8378. $("link[rel=chrome-webstore-item]").attr("href", getWebStoreInstallUrl());
  8379. }
  8380. function getVideoStreamFailed(error) {
  8381. console.error("Failed to obtain the stream to switch to", error);
  8382. switchInProgress = false;
  8383. isUsingScreenStream = false;
  8384. newStreamCreated(null);
  8385. }
  8386. function getDesktopStreamFailed(error) {
  8387. console.error("Failed to obtain the stream to switch to", error);
  8388. switchInProgress = false;
  8389. }
  8390. function streamSwitchDone() {
  8391. switchInProgress = false;
  8392. eventEmitter.emit(
  8393. DesktopSharingEventTypes.SWITCHING_DONE,
  8394. isUsingScreenStream);
  8395. }
  8396. function newStreamCreated(stream)
  8397. {
  8398. eventEmitter.emit(DesktopSharingEventTypes.NEW_STREAM_CREATED,
  8399. stream, isUsingScreenStream, streamSwitchDone);
  8400. }
  8401. module.exports = {
  8402. isUsingScreenStream: function () {
  8403. return isUsingScreenStream;
  8404. },
  8405. /**
  8406. * @returns {boolean} <tt>true</tt> if desktop sharing feature is available
  8407. * and enabled.
  8408. */
  8409. isDesktopSharingEnabled: function () {
  8410. if (_desktopSharingEnabled === null) {
  8411. if (obtainDesktopStream === obtainScreenFromExtension) {
  8412. // Parse chrome version
  8413. var userAgent = navigator.userAgent.toLowerCase();
  8414. // We can assume that user agent is chrome, because it's
  8415. // enforced when 'ext' streaming method is set
  8416. var ver = parseInt(userAgent.match(/chrome\/(\d+)\./)[1], 10);
  8417. console.log("Chrome version" + userAgent, ver);
  8418. _desktopSharingEnabled = ver >= 34;
  8419. } else {
  8420. _desktopSharingEnabled =
  8421. obtainDesktopStream === obtainWebRTCScreen;
  8422. }
  8423. }
  8424. return _desktopSharingEnabled;
  8425. },
  8426. init: function () {
  8427. setDesktopSharing(config.desktopSharing);
  8428. // Initialize Chrome extension inline installs
  8429. if (config.chromeExtensionId) {
  8430. initInlineInstalls();
  8431. // Check if extension is installed
  8432. checkExtInstalled(function (installed, updateRequired) {
  8433. extInstalled = installed;
  8434. extUpdateRequired = updateRequired;
  8435. console.info(
  8436. "Chrome extension installed: " + extInstalled +
  8437. " updateRequired: " + extUpdateRequired);
  8438. });
  8439. }
  8440. eventEmitter.emit(DesktopSharingEventTypes.INIT);
  8441. },
  8442. addListener: function (listener, type)
  8443. {
  8444. eventEmitter.on(type, listener);
  8445. },
  8446. removeListener: function (listener, type) {
  8447. eventEmitter.removeListener(type, listener);
  8448. },
  8449. /*
  8450. * Toggles screen sharing.
  8451. */
  8452. toggleScreenSharing: function () {
  8453. if (switchInProgress || !obtainDesktopStream) {
  8454. console.warn("Switch in progress or no method defined");
  8455. return;
  8456. }
  8457. switchInProgress = true;
  8458. if (!isUsingScreenStream)
  8459. {
  8460. // Switch to desktop stream
  8461. obtainDesktopStream(
  8462. function (stream) {
  8463. // We now use screen stream
  8464. isUsingScreenStream = true;
  8465. // Hook 'ended' event to restore camera
  8466. // when screen stream stops
  8467. stream.addEventListener('ended',
  8468. function (e) {
  8469. if (!switchInProgress && isUsingScreenStream) {
  8470. APP.desktopsharing.toggleScreenSharing();
  8471. }
  8472. }
  8473. );
  8474. newStreamCreated(stream);
  8475. },
  8476. getDesktopStreamFailed);
  8477. } else {
  8478. // Disable screen stream
  8479. APP.RTC.getUserMediaWithConstraints(
  8480. ['video'],
  8481. function (stream) {
  8482. // We are now using camera stream
  8483. isUsingScreenStream = false;
  8484. newStreamCreated(stream);
  8485. },
  8486. getVideoStreamFailed, config.resolution || '360'
  8487. );
  8488. }
  8489. }
  8490. };
  8491. },{"../../service/desktopsharing/DesktopSharingEventTypes":98,"events":102}],38:[function(require,module,exports){
  8492. //maps keycode to character, id of popover for given function and function
  8493. var shortcuts = {
  8494. 67: {
  8495. character: "C",
  8496. id: "toggleChatPopover",
  8497. function: APP.UI.toggleChat
  8498. },
  8499. 70: {
  8500. character: "F",
  8501. id: "filmstripPopover",
  8502. function: APP.UI.toggleFilmStrip
  8503. },
  8504. 77: {
  8505. character: "M",
  8506. id: "mutePopover",
  8507. function: APP.UI.toggleAudio
  8508. },
  8509. 84: {
  8510. character: "T",
  8511. function: function() {
  8512. if(!APP.RTC.localAudio.isMuted()) {
  8513. APP.UI.toggleAudio();
  8514. }
  8515. }
  8516. },
  8517. 86: {
  8518. character: "V",
  8519. id: "toggleVideoPopover",
  8520. function: APP.UI.toggleVideo
  8521. }
  8522. };
  8523. var KeyboardShortcut = {
  8524. init: function () {
  8525. window.onkeyup = function(e) {
  8526. var keycode = e.which;
  8527. if(!($(":focus").is("input[type=text]") ||
  8528. $(":focus").is("input[type=password]") ||
  8529. $(":focus").is("textarea"))) {
  8530. if (typeof shortcuts[keycode] === "object") {
  8531. shortcuts[keycode].function();
  8532. }
  8533. else if (keycode >= "0".charCodeAt(0) &&
  8534. keycode <= "9".charCodeAt(0)) {
  8535. APP.UI.clickOnVideo(keycode - "0".charCodeAt(0) + 1);
  8536. }
  8537. //esc while the smileys are visible hides them
  8538. } else if (keycode === 27 && $('#smileysContainer').is(':visible')) {
  8539. APP.UI.toggleSmileys();
  8540. }
  8541. };
  8542. window.onkeydown = function(e) {
  8543. if(!($(":focus").is("input[type=text]") ||
  8544. $(":focus").is("input[type=password]") ||
  8545. $(":focus").is("textarea"))) {
  8546. if(e.which === "T".charCodeAt(0)) {
  8547. if(APP.RTC.localAudio.isMuted()) {
  8548. APP.UI.toggleAudio();
  8549. }
  8550. }
  8551. }
  8552. };
  8553. var self = this;
  8554. $('body').popover({ selector: '[data-toggle=popover]',
  8555. trigger: 'click hover',
  8556. content: function() {
  8557. return this.getAttribute("content") +
  8558. self.getShortcut(this.getAttribute("shortcut"));
  8559. }
  8560. });
  8561. },
  8562. /**
  8563. *
  8564. * @param id indicates the popover associated with the shortcut
  8565. * @returns {string} the keyboard shortcut used for the id given
  8566. */
  8567. getShortcut: function (id) {
  8568. for (var keycode in shortcuts) {
  8569. if (shortcuts.hasOwnProperty(keycode)) {
  8570. if (shortcuts[keycode].id === id) {
  8571. return " (" + shortcuts[keycode].character + ")";
  8572. }
  8573. }
  8574. }
  8575. return "";
  8576. }
  8577. };
  8578. module.exports = KeyboardShortcut;
  8579. },{}],39:[function(require,module,exports){
  8580. /* global APP */
  8581. /**
  8582. * This module is meant to (eventually) contain and manage all information
  8583. * about members/participants of the conference, so that other modules don't
  8584. * have to do it on their own, and so that other modules can access members'
  8585. * information from a single place.
  8586. *
  8587. * Currently this module only manages information about the support of jingle
  8588. * DTMF of the members. Other fields, as well as accessor methods are meant to
  8589. * be added as needed.
  8590. */
  8591. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  8592. var Events = require("../../service/members/Events");
  8593. var EventEmitter = require("events");
  8594. var eventEmitter = new EventEmitter();
  8595. /**
  8596. * The actual container.
  8597. */
  8598. var members = {};
  8599. /**
  8600. * There is at least one member that supports DTMF (i.e. is jigasi).
  8601. */
  8602. var atLeastOneDtmf = false;
  8603. function registerListeners() {
  8604. APP.xmpp.addListener(XMPPEvents.MUC_MEMBER_JOINED, onMucMemberJoined);
  8605. APP.xmpp.addListener(XMPPEvents.MUC_MEMBER_LEFT, onMucMemberLeft);
  8606. }
  8607. /**
  8608. * Handles a new member joining the MUC.
  8609. */
  8610. function onMucMemberJoined(jid, id, displayName) {
  8611. var member = {
  8612. displayName: displayName
  8613. };
  8614. APP.xmpp.getConnection().disco.info(
  8615. jid, "" /* node */, function(iq) { onDiscoInfoReceived(jid, iq); });
  8616. members[jid] = member;
  8617. }
  8618. /**
  8619. * Handles a member leaving the MUC.
  8620. */
  8621. function onMucMemberLeft(jid) {
  8622. delete members[jid];
  8623. updateAtLeastOneDtmf();
  8624. }
  8625. /**
  8626. * Handles the reception of a disco#info packet from a particular JID.
  8627. * @param jid the JID sending the packet.
  8628. * @param iq the packet.
  8629. */
  8630. function onDiscoInfoReceived(jid, iq) {
  8631. if (!members[jid])
  8632. return;
  8633. var supportsDtmf
  8634. = $(iq).find('>query>feature[var="urn:xmpp:jingle:dtmf:0"]').length > 0;
  8635. updateDtmf(jid, supportsDtmf);
  8636. }
  8637. /**
  8638. * Updates the 'supportsDtmf' field for a member.
  8639. * @param jid the jid of the member.
  8640. * @param newValue the new value for the 'supportsDtmf' field.
  8641. */
  8642. function updateDtmf(jid, newValue) {
  8643. var oldValue = members[jid].supportsDtmf;
  8644. members[jid].supportsDtmf = newValue;
  8645. if (newValue != oldValue) {
  8646. updateAtLeastOneDtmf();
  8647. }
  8648. }
  8649. /**
  8650. * Checks each member's 'supportsDtmf' field and updates
  8651. * 'atLastOneSupportsDtmf'.
  8652. */
  8653. function updateAtLeastOneDtmf(){
  8654. var newAtLeastOneDtmf = false;
  8655. for (var key in members) {
  8656. if (typeof members[key].supportsDtmf !== 'undefined'
  8657. && members[key].supportsDtmf) {
  8658. newAtLeastOneDtmf= true;
  8659. break;
  8660. }
  8661. }
  8662. if (atLeastOneDtmf != newAtLeastOneDtmf) {
  8663. atLeastOneDtmf = newAtLeastOneDtmf;
  8664. eventEmitter.emit(Events.DTMF_SUPPORT_CHANGED, atLeastOneDtmf);
  8665. }
  8666. }
  8667. /**
  8668. * Exported interface.
  8669. */
  8670. var Members = {
  8671. start: function(){
  8672. registerListeners();
  8673. },
  8674. addListener: function(type, listener)
  8675. {
  8676. eventEmitter.on(type, listener);
  8677. },
  8678. removeListener: function (type, listener) {
  8679. eventEmitter.removeListener(type, listener);
  8680. }
  8681. };
  8682. module.exports = Members;
  8683. },{"../../service/members/Events":99,"../../service/xmpp/XMPPEvents":101,"events":102}],40:[function(require,module,exports){
  8684. var email = '';
  8685. var displayName = '';
  8686. var userId;
  8687. var language = null;
  8688. function supportsLocalStorage() {
  8689. try {
  8690. return 'localStorage' in window && window.localStorage !== null;
  8691. } catch (e) {
  8692. console.log("localstorage is not supported");
  8693. return false;
  8694. }
  8695. }
  8696. function generateUniqueId() {
  8697. function _p8() {
  8698. return (Math.random().toString(16) + "000000000").substr(2, 8);
  8699. }
  8700. return _p8() + _p8() + _p8() + _p8();
  8701. }
  8702. if (supportsLocalStorage()) {
  8703. if (!window.localStorage.jitsiMeetId) {
  8704. window.localStorage.jitsiMeetId = generateUniqueId();
  8705. console.log("generated id", window.localStorage.jitsiMeetId);
  8706. }
  8707. userId = window.localStorage.jitsiMeetId || '';
  8708. email = window.localStorage.email || '';
  8709. displayName = window.localStorage.displayname || '';
  8710. language = window.localStorage.language;
  8711. } else {
  8712. console.log("local storage is not supported");
  8713. userId = generateUniqueId();
  8714. }
  8715. var Settings =
  8716. {
  8717. setDisplayName: function (newDisplayName) {
  8718. displayName = newDisplayName;
  8719. window.localStorage.displayname = displayName;
  8720. return displayName;
  8721. },
  8722. setEmail: function (newEmail)
  8723. {
  8724. email = newEmail;
  8725. window.localStorage.email = newEmail;
  8726. return email;
  8727. },
  8728. getSettings: function () {
  8729. return {
  8730. email: email,
  8731. displayName: displayName,
  8732. uid: userId,
  8733. language: language
  8734. };
  8735. },
  8736. setLanguage: function (lang) {
  8737. language = lang;
  8738. window.localStorage.language = lang;
  8739. }
  8740. };
  8741. module.exports = Settings;
  8742. },{}],41:[function(require,module,exports){
  8743. /**
  8744. *
  8745. * @constructor
  8746. */
  8747. function SimulcastLogger(name, lvl) {
  8748. this.name = name;
  8749. this.lvl = lvl;
  8750. }
  8751. SimulcastLogger.prototype.log = function (text) {
  8752. if (this.lvl) {
  8753. console.log(text);
  8754. }
  8755. };
  8756. SimulcastLogger.prototype.info = function (text) {
  8757. if (this.lvl > 1) {
  8758. console.info(text);
  8759. }
  8760. };
  8761. SimulcastLogger.prototype.fine = function (text) {
  8762. if (this.lvl > 2) {
  8763. console.log(text);
  8764. }
  8765. };
  8766. SimulcastLogger.prototype.error = function (text) {
  8767. console.error(text);
  8768. };
  8769. module.exports = SimulcastLogger;
  8770. },{}],42:[function(require,module,exports){
  8771. var SimulcastLogger = require("./SimulcastLogger");
  8772. var SimulcastUtils = require("./SimulcastUtils");
  8773. var MediaStreamType = require("../../service/RTC/MediaStreamTypes");
  8774. function SimulcastReceiver() {
  8775. this.simulcastUtils = new SimulcastUtils();
  8776. this.logger = new SimulcastLogger('SimulcastReceiver', 1);
  8777. }
  8778. SimulcastReceiver.prototype._remoteVideoSourceCache = '';
  8779. SimulcastReceiver.prototype._remoteMaps = {
  8780. msid2Quality: {},
  8781. ssrc2Msid: {},
  8782. msid2ssrc: {},
  8783. receivingVideoStreams: {}
  8784. };
  8785. SimulcastReceiver.prototype._cacheRemoteVideoSources = function (lines) {
  8786. this._remoteVideoSourceCache = this.simulcastUtils._getVideoSources(lines);
  8787. };
  8788. SimulcastReceiver.prototype._restoreRemoteVideoSources = function (lines) {
  8789. this.simulcastUtils._replaceVideoSources(lines, this._remoteVideoSourceCache);
  8790. };
  8791. SimulcastReceiver.prototype._ensureGoogConference = function (lines) {
  8792. var sb;
  8793. this.logger.info('Ensuring x-google-conference flag...')
  8794. if (this.simulcastUtils._indexOfArray('a=x-google-flag:conference', lines) === this.simulcastUtils._emptyCompoundIndex) {
  8795. // TODO(gp) do that for the audio as well as suggested by fippo.
  8796. // Add the google conference flag
  8797. sb = this.simulcastUtils._getVideoSources(lines);
  8798. sb = ['a=x-google-flag:conference'].concat(sb);
  8799. this.simulcastUtils._replaceVideoSources(lines, sb);
  8800. }
  8801. };
  8802. SimulcastReceiver.prototype._restoreSimulcastGroups = function (sb) {
  8803. this._restoreRemoteVideoSources(sb);
  8804. };
  8805. /**
  8806. * Restores the simulcast groups of the remote description. In
  8807. * transformRemoteDescription we remove those in order for the set remote
  8808. * description to succeed. The focus needs the signal the groups to new
  8809. * participants.
  8810. *
  8811. * @param desc
  8812. * @returns {*}
  8813. */
  8814. SimulcastReceiver.prototype.reverseTransformRemoteDescription = function (desc) {
  8815. var sb;
  8816. if (!this.simulcastUtils.isValidDescription(desc)) {
  8817. return desc;
  8818. }
  8819. if (config.enableSimulcast) {
  8820. sb = desc.sdp.split('\r\n');
  8821. this._restoreSimulcastGroups(sb);
  8822. desc = new RTCSessionDescription({
  8823. type: desc.type,
  8824. sdp: sb.join('\r\n')
  8825. });
  8826. }
  8827. return desc;
  8828. };
  8829. SimulcastUtils.prototype._ensureOrder = function (lines) {
  8830. var videoSources, sb;
  8831. videoSources = this.parseMedia(lines, ['video'])[0];
  8832. sb = this._compileVideoSources(videoSources);
  8833. this._replaceVideoSources(lines, sb);
  8834. };
  8835. SimulcastReceiver.prototype._updateRemoteMaps = function (lines) {
  8836. var remoteVideoSources = this.simulcastUtils.parseMedia(lines, ['video'])[0],
  8837. videoSource, quality;
  8838. // (re) initialize the remote maps.
  8839. this._remoteMaps.msid2Quality = {};
  8840. this._remoteMaps.ssrc2Msid = {};
  8841. this._remoteMaps.msid2ssrc = {};
  8842. var self = this;
  8843. if (remoteVideoSources.groups && remoteVideoSources.groups.length !== 0) {
  8844. remoteVideoSources.groups.forEach(function (group) {
  8845. if (group.semantics === 'SIM' && group.ssrcs && group.ssrcs.length !== 0) {
  8846. quality = 0;
  8847. group.ssrcs.forEach(function (ssrc) {
  8848. videoSource = remoteVideoSources.sources[ssrc];
  8849. self._remoteMaps.msid2Quality[videoSource.msid] = quality++;
  8850. self._remoteMaps.ssrc2Msid[videoSource.ssrc] = videoSource.msid;
  8851. self._remoteMaps.msid2ssrc[videoSource.msid] = videoSource.ssrc;
  8852. });
  8853. }
  8854. });
  8855. }
  8856. };
  8857. SimulcastReceiver.prototype._setReceivingVideoStream = function (resource, ssrc) {
  8858. this._remoteMaps.receivingVideoStreams[resource] = ssrc;
  8859. };
  8860. /**
  8861. * Returns a stream with single video track, the one currently being
  8862. * received by this endpoint.
  8863. *
  8864. * @param stream the remote simulcast stream.
  8865. * @returns {webkitMediaStream}
  8866. */
  8867. SimulcastReceiver.prototype.getReceivingVideoStream = function (stream) {
  8868. var tracks, i, electedTrack, msid, quality = 0, receivingTrackId;
  8869. var self = this;
  8870. if (config.enableSimulcast) {
  8871. stream.getVideoTracks().some(function (track) {
  8872. return Object.keys(self._remoteMaps.receivingVideoStreams).some(function (resource) {
  8873. var ssrc = self._remoteMaps.receivingVideoStreams[resource];
  8874. var msid = self._remoteMaps.ssrc2Msid[ssrc];
  8875. if (msid == [stream.id, track.id].join(' ')) {
  8876. electedTrack = track;
  8877. return true;
  8878. }
  8879. });
  8880. });
  8881. if (!electedTrack) {
  8882. // we don't have an elected track, choose by initial quality.
  8883. tracks = stream.getVideoTracks();
  8884. for (i = 0; i < tracks.length; i++) {
  8885. msid = [stream.id, tracks[i].id].join(' ');
  8886. if (this._remoteMaps.msid2Quality[msid] === quality) {
  8887. electedTrack = tracks[i];
  8888. break;
  8889. }
  8890. }
  8891. // TODO(gp) if the initialQuality could not be satisfied, lower
  8892. // the requirement and try again.
  8893. }
  8894. }
  8895. return (electedTrack)
  8896. ? new webkitMediaStream([electedTrack])
  8897. : stream;
  8898. };
  8899. SimulcastReceiver.prototype.getReceivingSSRC = function (jid) {
  8900. var resource = Strophe.getResourceFromJid(jid);
  8901. var ssrc = this._remoteMaps.receivingVideoStreams[resource];
  8902. // If we haven't receiving a "changed" event yet, then we must be receiving
  8903. // low quality (that the sender always streams).
  8904. if(!ssrc)
  8905. {
  8906. var remoteStreamObject = APP.RTC.remoteStreams[jid][MediaStreamType.VIDEO_TYPE];
  8907. var remoteStream = remoteStreamObject.getOriginalStream();
  8908. var tracks = remoteStream.getVideoTracks();
  8909. if (tracks) {
  8910. for (var k = 0; k < tracks.length; k++) {
  8911. var track = tracks[k];
  8912. var msid = [remoteStream.id, track.id].join(' ');
  8913. var _ssrc = this._remoteMaps.msid2ssrc[msid];
  8914. var quality = this._remoteMaps.msid2Quality[msid];
  8915. if (quality == 0) {
  8916. ssrc = _ssrc;
  8917. }
  8918. }
  8919. }
  8920. }
  8921. return ssrc;
  8922. };
  8923. SimulcastReceiver.prototype.getReceivingVideoStreamBySSRC = function (ssrc)
  8924. {
  8925. var sid, electedStream;
  8926. var i, j, k;
  8927. var jid = APP.xmpp.getJidFromSSRC(ssrc);
  8928. if(jid && APP.RTC.remoteStreams[jid])
  8929. {
  8930. var remoteStreamObject = APP.RTC.remoteStreams[jid][MediaStreamType.VIDEO_TYPE];
  8931. var remoteStream = remoteStreamObject.getOriginalStream();
  8932. var tracks = remoteStream.getVideoTracks();
  8933. if (tracks) {
  8934. for (k = 0; k < tracks.length; k++) {
  8935. var track = tracks[k];
  8936. var msid = [remoteStream.id, track.id].join(' ');
  8937. var tmp = this._remoteMaps.msid2ssrc[msid];
  8938. if (tmp == ssrc) {
  8939. electedStream = new webkitMediaStream([track]);
  8940. sid = remoteStreamObject.sid;
  8941. // stream found, stop.
  8942. break;
  8943. }
  8944. }
  8945. }
  8946. }
  8947. else
  8948. {
  8949. console.debug(APP.RTC.remoteStreams, jid, ssrc);
  8950. }
  8951. return {
  8952. sid: sid,
  8953. stream: electedStream
  8954. };
  8955. };
  8956. /**
  8957. * Gets the fully qualified msid (stream.id + track.id) associated to the
  8958. * SSRC.
  8959. *
  8960. * @param ssrc
  8961. * @returns {*}
  8962. */
  8963. SimulcastReceiver.prototype.getRemoteVideoStreamIdBySSRC = function (ssrc) {
  8964. return this._remoteMaps.ssrc2Msid[ssrc];
  8965. };
  8966. /**
  8967. * Removes the ssrc-group:SIM from the remote description bacause Chrome
  8968. * either gets confused and thinks this is an FID group or, if an FID group
  8969. * is already present, it fails to set the remote description.
  8970. *
  8971. * @param desc
  8972. * @returns {*}
  8973. */
  8974. SimulcastReceiver.prototype.transformRemoteDescription = function (desc) {
  8975. if (desc && desc.sdp) {
  8976. var sb = desc.sdp.split('\r\n');
  8977. this._updateRemoteMaps(sb);
  8978. this._cacheRemoteVideoSources(sb);
  8979. // NOTE(gp) this needs to be called after updateRemoteMaps because we
  8980. // need the simulcast group in the _updateRemoteMaps() method.
  8981. this.simulcastUtils._removeSimulcastGroup(sb);
  8982. if (desc.sdp.indexOf('a=ssrc-group:SIM') !== -1) {
  8983. // We don't need the goog conference flag if we're not doing
  8984. // simulcast.
  8985. this._ensureGoogConference(sb);
  8986. }
  8987. desc = new RTCSessionDescription({
  8988. type: desc.type,
  8989. sdp: sb.join('\r\n')
  8990. });
  8991. this.logger.fine(['Transformed remote description', desc.sdp].join(' '));
  8992. }
  8993. return desc;
  8994. };
  8995. module.exports = SimulcastReceiver;
  8996. },{"../../service/RTC/MediaStreamTypes":90,"./SimulcastLogger":41,"./SimulcastUtils":44}],43:[function(require,module,exports){
  8997. var SimulcastLogger = require("./SimulcastLogger");
  8998. var SimulcastUtils = require("./SimulcastUtils");
  8999. function SimulcastSender() {
  9000. this.simulcastUtils = new SimulcastUtils();
  9001. this.logger = new SimulcastLogger('SimulcastSender', 1);
  9002. }
  9003. SimulcastSender.prototype.displayedLocalVideoStream = null;
  9004. SimulcastSender.prototype._generateGuid = (function () {
  9005. function s4() {
  9006. return Math.floor((1 + Math.random()) * 0x10000)
  9007. .toString(16)
  9008. .substring(1);
  9009. }
  9010. return function () {
  9011. return s4() + s4() + '-' + s4() + '-' + s4() + '-' +
  9012. s4() + '-' + s4() + s4() + s4();
  9013. };
  9014. }());
  9015. // Returns a random integer between min (included) and max (excluded)
  9016. // Using Math.round() gives a non-uniform distribution!
  9017. SimulcastSender.prototype._generateRandomSSRC = function () {
  9018. var min = 0, max = 0xffffffff;
  9019. return Math.floor(Math.random() * (max - min)) + min;
  9020. };
  9021. SimulcastSender.prototype.getLocalVideoStream = function () {
  9022. return (this.displayedLocalVideoStream != null)
  9023. ? this.displayedLocalVideoStream
  9024. // in case we have no simulcast at all, i.e. we didn't perform the GUM
  9025. : APP.RTC.localVideo.getOriginalStream();
  9026. };
  9027. function NativeSimulcastSender() {
  9028. SimulcastSender.call(this); // call the super constructor.
  9029. }
  9030. NativeSimulcastSender.prototype = Object.create(SimulcastSender.prototype);
  9031. NativeSimulcastSender.prototype._localExplosionMap = {};
  9032. NativeSimulcastSender.prototype._isUsingScreenStream = false;
  9033. NativeSimulcastSender.prototype._localVideoSourceCache = '';
  9034. NativeSimulcastSender.prototype.reset = function () {
  9035. this._localExplosionMap = {};
  9036. this._isUsingScreenStream = APP.desktopsharing.isUsingScreenStream();
  9037. };
  9038. NativeSimulcastSender.prototype._cacheLocalVideoSources = function (lines) {
  9039. this._localVideoSourceCache = this.simulcastUtils._getVideoSources(lines);
  9040. };
  9041. NativeSimulcastSender.prototype._restoreLocalVideoSources = function (lines) {
  9042. this.simulcastUtils._replaceVideoSources(lines, this._localVideoSourceCache);
  9043. };
  9044. NativeSimulcastSender.prototype._appendSimulcastGroup = function (lines) {
  9045. var videoSources, ssrcGroup, simSSRC, numOfSubs = 2, i, sb, msid;
  9046. this.logger.info('Appending simulcast group...');
  9047. // Get the primary SSRC information.
  9048. videoSources = this.simulcastUtils.parseMedia(lines, ['video'])[0];
  9049. // Start building the SIM SSRC group.
  9050. ssrcGroup = ['a=ssrc-group:SIM'];
  9051. // The video source buffer.
  9052. sb = [];
  9053. // Create the simulcast sub-streams.
  9054. for (i = 0; i < numOfSubs; i++) {
  9055. // TODO(gp) prevent SSRC collision.
  9056. simSSRC = this._generateRandomSSRC();
  9057. ssrcGroup.push(simSSRC);
  9058. if (videoSources.base) {
  9059. sb.splice.apply(sb, [sb.length, 0].concat(
  9060. [["a=ssrc:", simSSRC, " cname:", videoSources.base.cname].join(''),
  9061. ["a=ssrc:", simSSRC, " msid:", videoSources.base.msid].join('')]
  9062. ));
  9063. }
  9064. this.logger.info(['Generated substream ', i, ' with SSRC ', simSSRC, '.'].join(''));
  9065. }
  9066. // Add the group sim layers.
  9067. sb.splice(0, 0, ssrcGroup.join(' '))
  9068. this.simulcastUtils._replaceVideoSources(lines, sb);
  9069. };
  9070. // Does the actual patching.
  9071. NativeSimulcastSender.prototype._ensureSimulcastGroup = function (lines) {
  9072. this.logger.info('Ensuring simulcast group...');
  9073. if (this.simulcastUtils._indexOfArray('a=ssrc-group:SIM', lines) === this.simulcastUtils._emptyCompoundIndex) {
  9074. this._appendSimulcastGroup(lines);
  9075. this._cacheLocalVideoSources(lines);
  9076. } else {
  9077. // verify that the ssrcs participating in the SIM group are present
  9078. // in the SDP (needed for presence).
  9079. this._restoreLocalVideoSources(lines);
  9080. }
  9081. };
  9082. /**
  9083. * Produces a single stream with multiple tracks for local video sources.
  9084. *
  9085. * @param lines
  9086. * @private
  9087. */
  9088. NativeSimulcastSender.prototype._explodeSimulcastSenderSources = function (lines) {
  9089. var sb, msid, sid, tid, videoSources, self;
  9090. this.logger.info('Exploding local video sources...');
  9091. videoSources = this.simulcastUtils.parseMedia(lines, ['video'])[0];
  9092. self = this;
  9093. if (videoSources.groups && videoSources.groups.length !== 0) {
  9094. videoSources.groups.forEach(function (group) {
  9095. if (group.semantics === 'SIM') {
  9096. group.ssrcs.forEach(function (ssrc) {
  9097. // Get the msid for this ssrc..
  9098. if (self._localExplosionMap[ssrc]) {
  9099. // .. either from the explosion map..
  9100. msid = self._localExplosionMap[ssrc];
  9101. } else {
  9102. // .. or generate a new one (msid).
  9103. sid = videoSources.sources[ssrc].msid
  9104. .substring(0, videoSources.sources[ssrc].msid.indexOf(' '));
  9105. tid = self._generateGuid();
  9106. msid = [sid, tid].join(' ');
  9107. self._localExplosionMap[ssrc] = msid;
  9108. }
  9109. // Assign it to the source object.
  9110. videoSources.sources[ssrc].msid = msid;
  9111. // TODO(gp) Change the msid of associated sources.
  9112. });
  9113. }
  9114. });
  9115. }
  9116. sb = this.simulcastUtils._compileVideoSources(videoSources);
  9117. this.simulcastUtils._replaceVideoSources(lines, sb);
  9118. };
  9119. /**
  9120. * GUM for simulcast.
  9121. *
  9122. * @param constraints
  9123. * @param success
  9124. * @param err
  9125. */
  9126. NativeSimulcastSender.prototype.getUserMedia = function (constraints, success, err) {
  9127. // There's nothing special to do for native simulcast, so just do a normal GUM.
  9128. navigator.webkitGetUserMedia(constraints, function (hqStream) {
  9129. success(hqStream);
  9130. }, err);
  9131. };
  9132. /**
  9133. * Prepares the local description for public usage (i.e. to be signaled
  9134. * through Jingle to the focus).
  9135. *
  9136. * @param desc
  9137. * @returns {RTCSessionDescription}
  9138. */
  9139. NativeSimulcastSender.prototype.reverseTransformLocalDescription = function (desc) {
  9140. var sb;
  9141. if (!this.simulcastUtils.isValidDescription(desc) || this._isUsingScreenStream) {
  9142. return desc;
  9143. }
  9144. sb = desc.sdp.split('\r\n');
  9145. this._explodeSimulcastSenderSources(sb);
  9146. desc = new RTCSessionDescription({
  9147. type: desc.type,
  9148. sdp: sb.join('\r\n')
  9149. });
  9150. this.logger.fine(['Exploded local video sources', desc.sdp].join(' '));
  9151. return desc;
  9152. };
  9153. /**
  9154. * Ensures that the simulcast group is present in the answer, _if_ native
  9155. * simulcast is enabled,
  9156. *
  9157. * @param desc
  9158. * @returns {*}
  9159. */
  9160. NativeSimulcastSender.prototype.transformAnswer = function (desc) {
  9161. if (!this.simulcastUtils.isValidDescription(desc) || this._isUsingScreenStream) {
  9162. return desc;
  9163. }
  9164. var sb = desc.sdp.split('\r\n');
  9165. // Even if we have enabled native simulcasting previously
  9166. // (with a call to SLD with an appropriate SDP, for example),
  9167. // createAnswer seems to consistently generate incomplete SDP
  9168. // with missing SSRCS.
  9169. //
  9170. // So, subsequent calls to SLD will have missing SSRCS and presence
  9171. // won't have the complete list of SRCs.
  9172. this._ensureSimulcastGroup(sb);
  9173. desc = new RTCSessionDescription({
  9174. type: desc.type,
  9175. sdp: sb.join('\r\n')
  9176. });
  9177. this.logger.fine(['Transformed answer', desc.sdp].join(' '));
  9178. return desc;
  9179. };
  9180. /**
  9181. *
  9182. *
  9183. * @param desc
  9184. * @returns {*}
  9185. */
  9186. NativeSimulcastSender.prototype.transformLocalDescription = function (desc) {
  9187. return desc;
  9188. };
  9189. NativeSimulcastSender.prototype._setLocalVideoStreamEnabled = function (ssrc, enabled) {
  9190. // Nothing to do here, native simulcast does that auto-magically.
  9191. };
  9192. NativeSimulcastSender.prototype.constructor = NativeSimulcastSender;
  9193. function SimpleSimulcastSender() {
  9194. SimulcastSender.call(this);
  9195. }
  9196. SimpleSimulcastSender.prototype = Object.create(SimulcastSender.prototype);
  9197. SimpleSimulcastSender.prototype.localStream = null;
  9198. SimpleSimulcastSender.prototype._localMaps = {
  9199. msids: [],
  9200. msid2ssrc: {}
  9201. };
  9202. /**
  9203. * Groups local video sources together in the ssrc-group:SIM group.
  9204. *
  9205. * @param lines
  9206. * @private
  9207. */
  9208. SimpleSimulcastSender.prototype._groupLocalVideoSources = function (lines) {
  9209. var sb, videoSources, ssrcs = [], ssrc;
  9210. this.logger.info('Grouping local video sources...');
  9211. videoSources = this.simulcastUtils.parseMedia(lines, ['video'])[0];
  9212. for (ssrc in videoSources.sources) {
  9213. // jitsi-meet destroys/creates streams at various places causing
  9214. // the original local stream ids to change. The only thing that
  9215. // remains unchanged is the trackid.
  9216. this._localMaps.msid2ssrc[videoSources.sources[ssrc].msid.split(' ')[1]] = ssrc;
  9217. }
  9218. var self = this;
  9219. // TODO(gp) add only "free" sources.
  9220. this._localMaps.msids.forEach(function (msid) {
  9221. ssrcs.push(self._localMaps.msid2ssrc[msid]);
  9222. });
  9223. if (!videoSources.groups) {
  9224. videoSources.groups = [];
  9225. }
  9226. videoSources.groups.push({
  9227. 'semantics': 'SIM',
  9228. 'ssrcs': ssrcs
  9229. });
  9230. sb = this.simulcastUtils._compileVideoSources(videoSources);
  9231. this.simulcastUtils._replaceVideoSources(lines, sb);
  9232. };
  9233. /**
  9234. * GUM for simulcast.
  9235. *
  9236. * @param constraints
  9237. * @param success
  9238. * @param err
  9239. */
  9240. SimpleSimulcastSender.prototype.getUserMedia = function (constraints, success, err) {
  9241. // TODO(gp) what if we request a resolution not supported by the hardware?
  9242. // TODO(gp) make the lq stream configurable; although this wouldn't work with native simulcast
  9243. var lqConstraints = {
  9244. audio: false,
  9245. video: {
  9246. mandatory: {
  9247. maxWidth: 320,
  9248. maxHeight: 180,
  9249. maxFrameRate: 15
  9250. }
  9251. }
  9252. };
  9253. this.logger.info('HQ constraints: ', constraints);
  9254. this.logger.info('LQ constraints: ', lqConstraints);
  9255. // NOTE(gp) if we request the lq stream first webkitGetUserMedia
  9256. // fails randomly. Tested with Chrome 37. As fippo suggested, the
  9257. // reason appears to be that Chrome only acquires the cam once and
  9258. // then downscales the picture (https://code.google.com/p/chromium/issues/detail?id=346616#c11)
  9259. var self = this;
  9260. navigator.webkitGetUserMedia(constraints, function (hqStream) {
  9261. self.localStream = hqStream;
  9262. // reset local maps.
  9263. self._localMaps.msids = [];
  9264. self._localMaps.msid2ssrc = {};
  9265. // add hq trackid to local map
  9266. self._localMaps.msids.push(hqStream.getVideoTracks()[0].id);
  9267. navigator.webkitGetUserMedia(lqConstraints, function (lqStream) {
  9268. self.displayedLocalVideoStream = lqStream;
  9269. // NOTE(gp) The specification says Array.forEach() will visit
  9270. // the array elements in numeric order, and that it doesn't
  9271. // visit elements that don't exist.
  9272. // add lq trackid to local map
  9273. self._localMaps.msids.splice(0, 0, lqStream.getVideoTracks()[0].id);
  9274. self.localStream.addTrack(lqStream.getVideoTracks()[0]);
  9275. success(self.localStream);
  9276. }, err);
  9277. }, err);
  9278. };
  9279. /**
  9280. * Prepares the local description for public usage (i.e. to be signaled
  9281. * through Jingle to the focus).
  9282. *
  9283. * @param desc
  9284. * @returns {RTCSessionDescription}
  9285. */
  9286. SimpleSimulcastSender.prototype.reverseTransformLocalDescription = function (desc) {
  9287. var sb;
  9288. if (!this.simulcastUtils.isValidDescription(desc)) {
  9289. return desc;
  9290. }
  9291. sb = desc.sdp.split('\r\n');
  9292. this._groupLocalVideoSources(sb);
  9293. desc = new RTCSessionDescription({
  9294. type: desc.type,
  9295. sdp: sb.join('\r\n')
  9296. });
  9297. this.logger.fine('Grouped local video sources');
  9298. this.logger.fine(desc.sdp);
  9299. return desc;
  9300. };
  9301. /**
  9302. * Ensures that the simulcast group is present in the answer, _if_ native
  9303. * simulcast is enabled,
  9304. *
  9305. * @param desc
  9306. * @returns {*}
  9307. */
  9308. SimpleSimulcastSender.prototype.transformAnswer = function (desc) {
  9309. return desc;
  9310. };
  9311. /**
  9312. *
  9313. *
  9314. * @param desc
  9315. * @returns {*}
  9316. */
  9317. SimpleSimulcastSender.prototype.transformLocalDescription = function (desc) {
  9318. var sb = desc.sdp.split('\r\n');
  9319. this.simulcastUtils._removeSimulcastGroup(sb);
  9320. desc = new RTCSessionDescription({
  9321. type: desc.type,
  9322. sdp: sb.join('\r\n')
  9323. });
  9324. this.logger.fine('Transformed local description');
  9325. this.logger.fine(desc.sdp);
  9326. return desc;
  9327. };
  9328. SimpleSimulcastSender.prototype._setLocalVideoStreamEnabled = function (ssrc, enabled) {
  9329. var trackid;
  9330. var self = this;
  9331. this.logger.log(['Requested to', enabled ? 'enable' : 'disable', ssrc].join(' '));
  9332. if (Object.keys(this._localMaps.msid2ssrc).some(function (tid) {
  9333. // Search for the track id that corresponds to the ssrc
  9334. if (self._localMaps.msid2ssrc[tid] == ssrc) {
  9335. trackid = tid;
  9336. return true;
  9337. }
  9338. }) && self.localStream.getVideoTracks().some(function (track) {
  9339. // Start/stop the track that corresponds to the track id
  9340. if (track.id === trackid) {
  9341. track.enabled = enabled;
  9342. return true;
  9343. }
  9344. })) {
  9345. this.logger.log([trackid, enabled ? 'enabled' : 'disabled'].join(' '));
  9346. $(document).trigger(enabled
  9347. ? 'simulcastlayerstarted'
  9348. : 'simulcastlayerstopped');
  9349. } else {
  9350. this.logger.error("I don't have a local stream with SSRC " + ssrc);
  9351. }
  9352. };
  9353. SimpleSimulcastSender.prototype.constructor = SimpleSimulcastSender;
  9354. function NoSimulcastSender() {
  9355. SimulcastSender.call(this);
  9356. }
  9357. NoSimulcastSender.prototype = Object.create(SimulcastSender.prototype);
  9358. /**
  9359. * GUM for simulcast.
  9360. *
  9361. * @param constraints
  9362. * @param success
  9363. * @param err
  9364. */
  9365. NoSimulcastSender.prototype.getUserMedia = function (constraints, success, err) {
  9366. navigator.webkitGetUserMedia(constraints, function (hqStream) {
  9367. success(hqStream);
  9368. }, err);
  9369. };
  9370. /**
  9371. * Prepares the local description for public usage (i.e. to be signaled
  9372. * through Jingle to the focus).
  9373. *
  9374. * @param desc
  9375. * @returns {RTCSessionDescription}
  9376. */
  9377. NoSimulcastSender.prototype.reverseTransformLocalDescription = function (desc) {
  9378. return desc;
  9379. };
  9380. /**
  9381. * Ensures that the simulcast group is present in the answer, _if_ native
  9382. * simulcast is enabled,
  9383. *
  9384. * @param desc
  9385. * @returns {*}
  9386. */
  9387. NoSimulcastSender.prototype.transformAnswer = function (desc) {
  9388. return desc;
  9389. };
  9390. /**
  9391. *
  9392. *
  9393. * @param desc
  9394. * @returns {*}
  9395. */
  9396. NoSimulcastSender.prototype.transformLocalDescription = function (desc) {
  9397. return desc;
  9398. };
  9399. NoSimulcastSender.prototype._setLocalVideoStreamEnabled = function (ssrc, enabled) {
  9400. };
  9401. NoSimulcastSender.prototype.constructor = NoSimulcastSender;
  9402. module.exports = {
  9403. "native": NativeSimulcastSender,
  9404. "no": NoSimulcastSender
  9405. }
  9406. },{"./SimulcastLogger":41,"./SimulcastUtils":44}],44:[function(require,module,exports){
  9407. var SimulcastLogger = require("./SimulcastLogger");
  9408. /**
  9409. *
  9410. * @constructor
  9411. */
  9412. function SimulcastUtils() {
  9413. this.logger = new SimulcastLogger("SimulcastUtils", 1);
  9414. }
  9415. /**
  9416. *
  9417. * @type {{}}
  9418. * @private
  9419. */
  9420. SimulcastUtils.prototype._emptyCompoundIndex = {};
  9421. /**
  9422. *
  9423. * @param lines
  9424. * @param videoSources
  9425. * @private
  9426. */
  9427. SimulcastUtils.prototype._replaceVideoSources = function (lines, videoSources) {
  9428. var i, inVideo = false, index = -1, howMany = 0;
  9429. this.logger.info('Replacing video sources...');
  9430. for (i = 0; i < lines.length; i++) {
  9431. if (inVideo && lines[i].substring(0, 'm='.length) === 'm=') {
  9432. // Out of video.
  9433. break;
  9434. }
  9435. if (!inVideo && lines[i].substring(0, 'm=video '.length) === 'm=video ') {
  9436. // In video.
  9437. inVideo = true;
  9438. }
  9439. if (inVideo && (lines[i].substring(0, 'a=ssrc:'.length) === 'a=ssrc:'
  9440. || lines[i].substring(0, 'a=ssrc-group:'.length) === 'a=ssrc-group:')) {
  9441. if (index === -1) {
  9442. index = i;
  9443. }
  9444. howMany++;
  9445. }
  9446. }
  9447. // efficiency baby ;)
  9448. lines.splice.apply(lines,
  9449. [index, howMany].concat(videoSources));
  9450. };
  9451. SimulcastUtils.prototype.isValidDescription = function (desc)
  9452. {
  9453. return desc && desc != null
  9454. && desc.type && desc.type != ''
  9455. && desc.sdp && desc.sdp != '';
  9456. };
  9457. SimulcastUtils.prototype._getVideoSources = function (lines) {
  9458. var i, inVideo = false, sb = [];
  9459. this.logger.info('Getting video sources...');
  9460. for (i = 0; i < lines.length; i++) {
  9461. if (inVideo && lines[i].substring(0, 'm='.length) === 'm=') {
  9462. // Out of video.
  9463. break;
  9464. }
  9465. if (!inVideo && lines[i].substring(0, 'm=video '.length) === 'm=video ') {
  9466. // In video.
  9467. inVideo = true;
  9468. }
  9469. if (inVideo && lines[i].substring(0, 'a=ssrc:'.length) === 'a=ssrc:') {
  9470. // In SSRC.
  9471. sb.push(lines[i]);
  9472. }
  9473. if (inVideo && lines[i].substring(0, 'a=ssrc-group:'.length) === 'a=ssrc-group:') {
  9474. sb.push(lines[i]);
  9475. }
  9476. }
  9477. return sb;
  9478. };
  9479. SimulcastUtils.prototype.parseMedia = function (lines, mediatypes) {
  9480. var i, res = [], type, cur_media, idx, ssrcs, cur_ssrc, ssrc,
  9481. ssrc_attribute, group, semantics, skip = true;
  9482. this.logger.info('Parsing media sources...');
  9483. for (i = 0; i < lines.length; i++) {
  9484. if (lines[i].substring(0, 'm='.length) === 'm=') {
  9485. type = lines[i]
  9486. .substr('m='.length, lines[i].indexOf(' ') - 'm='.length);
  9487. skip = mediatypes !== undefined && mediatypes.indexOf(type) === -1;
  9488. if (!skip) {
  9489. cur_media = {
  9490. 'type': type,
  9491. 'sources': {},
  9492. 'groups': []
  9493. };
  9494. res.push(cur_media);
  9495. }
  9496. } else if (!skip && lines[i].substring(0, 'a=ssrc:'.length) === 'a=ssrc:') {
  9497. idx = lines[i].indexOf(' ');
  9498. ssrc = lines[i].substring('a=ssrc:'.length, idx);
  9499. if (cur_media.sources[ssrc] === undefined) {
  9500. cur_ssrc = {'ssrc': ssrc};
  9501. cur_media.sources[ssrc] = cur_ssrc;
  9502. }
  9503. ssrc_attribute = lines[i].substr(idx + 1).split(':', 2)[0];
  9504. cur_ssrc[ssrc_attribute] = lines[i].substr(idx + 1).split(':', 2)[1];
  9505. if (cur_media.base === undefined) {
  9506. cur_media.base = cur_ssrc;
  9507. }
  9508. } else if (!skip && lines[i].substring(0, 'a=ssrc-group:'.length) === 'a=ssrc-group:') {
  9509. idx = lines[i].indexOf(' ');
  9510. semantics = lines[i].substr(0, idx).substr('a=ssrc-group:'.length);
  9511. ssrcs = lines[i].substr(idx).trim().split(' ');
  9512. group = {
  9513. 'semantics': semantics,
  9514. 'ssrcs': ssrcs
  9515. };
  9516. cur_media.groups.push(group);
  9517. } else if (!skip && (lines[i].substring(0, 'a=sendrecv'.length) === 'a=sendrecv' ||
  9518. lines[i].substring(0, 'a=recvonly'.length) === 'a=recvonly' ||
  9519. lines[i].substring(0, 'a=sendonly'.length) === 'a=sendonly' ||
  9520. lines[i].substring(0, 'a=inactive'.length) === 'a=inactive')) {
  9521. cur_media.direction = lines[i].substring('a='.length);
  9522. }
  9523. }
  9524. return res;
  9525. };
  9526. /**
  9527. * The _indexOfArray() method returns the first a CompoundIndex at which a
  9528. * given element can be found in the array, or _emptyCompoundIndex if it is
  9529. * not present.
  9530. *
  9531. * Example:
  9532. *
  9533. * _indexOfArray('3', [ 'this is line 1', 'this is line 2', 'this is line 3' ])
  9534. *
  9535. * returns {row: 2, column: 14}
  9536. *
  9537. * @param needle
  9538. * @param haystack
  9539. * @param start
  9540. * @returns {}
  9541. * @private
  9542. */
  9543. SimulcastUtils.prototype._indexOfArray = function (needle, haystack, start) {
  9544. var length = haystack.length, idx, i;
  9545. if (!start) {
  9546. start = 0;
  9547. }
  9548. for (i = start; i < length; i++) {
  9549. idx = haystack[i].indexOf(needle);
  9550. if (idx !== -1) {
  9551. return {row: i, column: idx};
  9552. }
  9553. }
  9554. return this._emptyCompoundIndex;
  9555. };
  9556. SimulcastUtils.prototype._removeSimulcastGroup = function (lines) {
  9557. var i;
  9558. for (i = lines.length - 1; i >= 0; i--) {
  9559. if (lines[i].indexOf('a=ssrc-group:SIM') !== -1) {
  9560. lines.splice(i, 1);
  9561. }
  9562. }
  9563. };
  9564. SimulcastUtils.prototype._compileVideoSources = function (videoSources) {
  9565. var sb = [], ssrc, addedSSRCs = [];
  9566. this.logger.info('Compiling video sources...');
  9567. // Add the groups
  9568. if (videoSources.groups && videoSources.groups.length !== 0) {
  9569. videoSources.groups.forEach(function (group) {
  9570. if (group.ssrcs && group.ssrcs.length !== 0) {
  9571. sb.push([['a=ssrc-group:', group.semantics].join(''), group.ssrcs.join(' ')].join(' '));
  9572. // if (group.semantics !== 'SIM') {
  9573. group.ssrcs.forEach(function (ssrc) {
  9574. addedSSRCs.push(ssrc);
  9575. sb.splice.apply(sb, [sb.length, 0].concat([
  9576. ["a=ssrc:", ssrc, " cname:", videoSources.sources[ssrc].cname].join(''),
  9577. ["a=ssrc:", ssrc, " msid:", videoSources.sources[ssrc].msid].join('')]));
  9578. });
  9579. //}
  9580. }
  9581. });
  9582. }
  9583. // Then add any free sources.
  9584. if (videoSources.sources) {
  9585. for (ssrc in videoSources.sources) {
  9586. if (addedSSRCs.indexOf(ssrc) === -1) {
  9587. sb.splice.apply(sb, [sb.length, 0].concat([
  9588. ["a=ssrc:", ssrc, " cname:", videoSources.sources[ssrc].cname].join(''),
  9589. ["a=ssrc:", ssrc, " msid:", videoSources.sources[ssrc].msid].join('')]));
  9590. }
  9591. }
  9592. }
  9593. return sb;
  9594. };
  9595. module.exports = SimulcastUtils;
  9596. },{"./SimulcastLogger":41}],45:[function(require,module,exports){
  9597. /*jslint plusplus: true */
  9598. /*jslint nomen: true*/
  9599. var SimulcastSender = require("./SimulcastSender");
  9600. var NoSimulcastSender = SimulcastSender["no"];
  9601. var NativeSimulcastSender = SimulcastSender["native"];
  9602. var SimulcastReceiver = require("./SimulcastReceiver");
  9603. var SimulcastUtils = require("./SimulcastUtils");
  9604. var RTCEvents = require("../../service/RTC/RTCEvents");
  9605. /**
  9606. *
  9607. * @constructor
  9608. */
  9609. function SimulcastManager() {
  9610. // Create the simulcast utilities.
  9611. this.simulcastUtils = new SimulcastUtils();
  9612. // Create remote simulcast.
  9613. this.simulcastReceiver = new SimulcastReceiver();
  9614. // Initialize local simulcast.
  9615. // TODO(gp) move into SimulcastManager.prototype.getUserMedia and take into
  9616. // account constraints.
  9617. if (!config.enableSimulcast) {
  9618. this.simulcastSender = new NoSimulcastSender();
  9619. } else {
  9620. var isChromium = window.chrome,
  9621. vendorName = window.navigator.vendor;
  9622. if(isChromium !== null && isChromium !== undefined
  9623. /* skip opera */
  9624. && vendorName === "Google Inc."
  9625. /* skip Chromium as suggested by fippo */
  9626. && !window.navigator.appVersion.match(/Chromium\//) ) {
  9627. var ver = parseInt(window.navigator.appVersion.match(/Chrome\/(\d+)\./)[1], 10);
  9628. if (ver > 37) {
  9629. this.simulcastSender = new NativeSimulcastSender();
  9630. } else {
  9631. this.simulcastSender = new NoSimulcastSender();
  9632. }
  9633. } else {
  9634. this.simulcastSender = new NoSimulcastSender();
  9635. }
  9636. }
  9637. APP.RTC.addListener(RTCEvents.SIMULCAST_LAYER_CHANGED,
  9638. function (endpointSimulcastLayers) {
  9639. endpointSimulcastLayers.forEach(function (esl) {
  9640. var ssrc = esl.simulcastLayer.primarySSRC;
  9641. simulcast._setReceivingVideoStream(esl.endpoint, ssrc);
  9642. });
  9643. });
  9644. APP.RTC.addListener(RTCEvents.SIMULCAST_START, function (simulcastLayer) {
  9645. var ssrc = simulcastLayer.primarySSRC;
  9646. simulcast._setLocalVideoStreamEnabled(ssrc, true);
  9647. });
  9648. APP.RTC.addListener(RTCEvents.SIMULCAST_STOP, function (simulcastLayer) {
  9649. var ssrc = simulcastLayer.primarySSRC;
  9650. simulcast._setLocalVideoStreamEnabled(ssrc, false);
  9651. });
  9652. }
  9653. /**
  9654. * Restores the simulcast groups of the remote description. In
  9655. * transformRemoteDescription we remove those in order for the set remote
  9656. * description to succeed. The focus needs the signal the groups to new
  9657. * participants.
  9658. *
  9659. * @param desc
  9660. * @returns {*}
  9661. */
  9662. SimulcastManager.prototype.reverseTransformRemoteDescription = function (desc) {
  9663. return this.simulcastReceiver.reverseTransformRemoteDescription(desc);
  9664. };
  9665. /**
  9666. * Removes the ssrc-group:SIM from the remote description bacause Chrome
  9667. * either gets confused and thinks this is an FID group or, if an FID group
  9668. * is already present, it fails to set the remote description.
  9669. *
  9670. * @param desc
  9671. * @returns {*}
  9672. */
  9673. SimulcastManager.prototype.transformRemoteDescription = function (desc) {
  9674. return this.simulcastReceiver.transformRemoteDescription(desc);
  9675. };
  9676. /**
  9677. * Gets the fully qualified msid (stream.id + track.id) associated to the
  9678. * SSRC.
  9679. *
  9680. * @param ssrc
  9681. * @returns {*}
  9682. */
  9683. SimulcastManager.prototype.getRemoteVideoStreamIdBySSRC = function (ssrc) {
  9684. return this.simulcastReceiver.getRemoteVideoStreamIdBySSRC(ssrc);
  9685. };
  9686. /**
  9687. * Returns a stream with single video track, the one currently being
  9688. * received by this endpoint.
  9689. *
  9690. * @param stream the remote simulcast stream.
  9691. * @returns {webkitMediaStream}
  9692. */
  9693. SimulcastManager.prototype.getReceivingVideoStream = function (stream) {
  9694. return this.simulcastReceiver.getReceivingVideoStream(stream);
  9695. };
  9696. /**
  9697. *
  9698. *
  9699. * @param desc
  9700. * @returns {*}
  9701. */
  9702. SimulcastManager.prototype.transformLocalDescription = function (desc) {
  9703. return this.simulcastSender.transformLocalDescription(desc);
  9704. };
  9705. /**
  9706. *
  9707. * @returns {*}
  9708. */
  9709. SimulcastManager.prototype.getLocalVideoStream = function() {
  9710. return this.simulcastSender.getLocalVideoStream();
  9711. };
  9712. /**
  9713. * GUM for simulcast.
  9714. *
  9715. * @param constraints
  9716. * @param success
  9717. * @param err
  9718. */
  9719. SimulcastManager.prototype.getUserMedia = function (constraints, success, err) {
  9720. this.simulcastSender.getUserMedia(constraints, success, err);
  9721. };
  9722. /**
  9723. * Prepares the local description for public usage (i.e. to be signaled
  9724. * through Jingle to the focus).
  9725. *
  9726. * @param desc
  9727. * @returns {RTCSessionDescription}
  9728. */
  9729. SimulcastManager.prototype.reverseTransformLocalDescription = function (desc) {
  9730. return this.simulcastSender.reverseTransformLocalDescription(desc);
  9731. };
  9732. /**
  9733. * Ensures that the simulcast group is present in the answer, _if_ native
  9734. * simulcast is enabled,
  9735. *
  9736. * @param desc
  9737. * @returns {*}
  9738. */
  9739. SimulcastManager.prototype.transformAnswer = function (desc) {
  9740. return this.simulcastSender.transformAnswer(desc);
  9741. };
  9742. SimulcastManager.prototype.getReceivingSSRC = function (jid) {
  9743. return this.simulcastReceiver.getReceivingSSRC(jid);
  9744. };
  9745. SimulcastManager.prototype.getReceivingVideoStreamBySSRC = function (msid) {
  9746. return this.simulcastReceiver.getReceivingVideoStreamBySSRC(msid);
  9747. };
  9748. /**
  9749. *
  9750. * @param lines
  9751. * @param mediatypes
  9752. * @returns {*}
  9753. */
  9754. SimulcastManager.prototype.parseMedia = function(lines, mediatypes) {
  9755. var sb = lines.sdp.split('\r\n');
  9756. return this.simulcastUtils.parseMedia(sb, mediatypes);
  9757. };
  9758. SimulcastManager.prototype._setReceivingVideoStream = function(resource, ssrc) {
  9759. this.simulcastReceiver._setReceivingVideoStream(resource, ssrc);
  9760. };
  9761. SimulcastManager.prototype._setLocalVideoStreamEnabled = function(ssrc, enabled) {
  9762. this.simulcastSender._setLocalVideoStreamEnabled(ssrc, enabled);
  9763. };
  9764. SimulcastManager.prototype.resetSender = function() {
  9765. if (typeof this.simulcastSender.reset === 'function'){
  9766. this.simulcastSender.reset();
  9767. }
  9768. };
  9769. var simulcast = new SimulcastManager();
  9770. module.exports = simulcast;
  9771. },{"../../service/RTC/RTCEvents":92,"./SimulcastReceiver":42,"./SimulcastSender":43,"./SimulcastUtils":44}],46:[function(require,module,exports){
  9772. /**
  9773. * Provides statistics for the local stream.
  9774. */
  9775. /**
  9776. * Size of the webaudio analizer buffer.
  9777. * @type {number}
  9778. */
  9779. var WEBAUDIO_ANALIZER_FFT_SIZE = 2048;
  9780. /**
  9781. * Value of the webaudio analizer smoothing time parameter.
  9782. * @type {number}
  9783. */
  9784. var WEBAUDIO_ANALIZER_SMOOTING_TIME = 0.8;
  9785. /**
  9786. * Converts time domain data array to audio level.
  9787. * @param array the time domain data array.
  9788. * @returns {number} the audio level
  9789. */
  9790. function timeDomainDataToAudioLevel(samples) {
  9791. var maxVolume = 0;
  9792. var length = samples.length;
  9793. for (var i = 0; i < length; i++) {
  9794. if (maxVolume < samples[i])
  9795. maxVolume = samples[i];
  9796. }
  9797. return parseFloat(((maxVolume - 127) / 128).toFixed(3));
  9798. };
  9799. /**
  9800. * Animates audio level change
  9801. * @param newLevel the new audio level
  9802. * @param lastLevel the last audio level
  9803. * @returns {Number} the audio level to be set
  9804. */
  9805. function animateLevel(newLevel, lastLevel)
  9806. {
  9807. var value = 0;
  9808. var diff = lastLevel - newLevel;
  9809. if(diff > 0.2)
  9810. {
  9811. value = lastLevel - 0.2;
  9812. }
  9813. else if(diff < -0.4)
  9814. {
  9815. value = lastLevel + 0.4;
  9816. }
  9817. else
  9818. {
  9819. value = newLevel;
  9820. }
  9821. return parseFloat(value.toFixed(3));
  9822. }
  9823. /**
  9824. * <tt>LocalStatsCollector</tt> calculates statistics for the local stream.
  9825. *
  9826. * @param stream the local stream
  9827. * @param interval stats refresh interval given in ms.
  9828. * @param {function(LocalStatsCollector)} updateCallback the callback called on stats
  9829. * update.
  9830. * @constructor
  9831. */
  9832. function LocalStatsCollector(stream, interval, statisticsService, eventEmitter) {
  9833. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  9834. this.stream = stream;
  9835. this.intervalId = null;
  9836. this.intervalMilis = interval;
  9837. this.eventEmitter = eventEmitter;
  9838. this.audioLevel = 0;
  9839. this.statisticsService = statisticsService;
  9840. }
  9841. /**
  9842. * Starts the collecting the statistics.
  9843. */
  9844. LocalStatsCollector.prototype.start = function () {
  9845. if (config.disableAudioLevels || !window.AudioContext)
  9846. return;
  9847. var context = new AudioContext();
  9848. var analyser = context.createAnalyser();
  9849. analyser.smoothingTimeConstant = WEBAUDIO_ANALIZER_SMOOTING_TIME;
  9850. analyser.fftSize = WEBAUDIO_ANALIZER_FFT_SIZE;
  9851. var source = context.createMediaStreamSource(this.stream);
  9852. source.connect(analyser);
  9853. var self = this;
  9854. this.intervalId = setInterval(
  9855. function () {
  9856. var array = new Uint8Array(analyser.frequencyBinCount);
  9857. analyser.getByteTimeDomainData(array);
  9858. var audioLevel = timeDomainDataToAudioLevel(array);
  9859. if(audioLevel != self.audioLevel) {
  9860. self.audioLevel = animateLevel(audioLevel, self.audioLevel);
  9861. self.eventEmitter.emit(
  9862. "statistics.audioLevel",
  9863. self.statisticsService.LOCAL_JID,
  9864. self.audioLevel);
  9865. }
  9866. },
  9867. this.intervalMilis
  9868. );
  9869. };
  9870. /**
  9871. * Stops collecting the statistics.
  9872. */
  9873. LocalStatsCollector.prototype.stop = function () {
  9874. if (this.intervalId) {
  9875. clearInterval(this.intervalId);
  9876. this.intervalId = null;
  9877. }
  9878. };
  9879. module.exports = LocalStatsCollector;
  9880. },{}],47:[function(require,module,exports){
  9881. /* global ssrc2jid */
  9882. /* jshint -W117 */
  9883. var RTCBrowserType = require("../../service/RTC/RTCBrowserType");
  9884. /**
  9885. * Calculates packet lost percent using the number of lost packets and the
  9886. * number of all packet.
  9887. * @param lostPackets the number of lost packets
  9888. * @param totalPackets the number of all packets.
  9889. * @returns {number} packet loss percent
  9890. */
  9891. function calculatePacketLoss(lostPackets, totalPackets) {
  9892. if(!totalPackets || totalPackets <= 0 || !lostPackets || lostPackets <= 0)
  9893. return 0;
  9894. return Math.round((lostPackets/totalPackets)*100);
  9895. }
  9896. function getStatValue(item, name) {
  9897. if(!keyMap[APP.RTC.getBrowserType()][name])
  9898. throw "The property isn't supported!";
  9899. var key = keyMap[APP.RTC.getBrowserType()][name];
  9900. return APP.RTC.getBrowserType() == RTCBrowserType.RTC_BROWSER_CHROME? item.stat(key) : item[key];
  9901. }
  9902. /**
  9903. * Peer statistics data holder.
  9904. * @constructor
  9905. */
  9906. function PeerStats()
  9907. {
  9908. this.ssrc2Loss = {};
  9909. this.ssrc2AudioLevel = {};
  9910. this.ssrc2bitrate = {};
  9911. this.ssrc2resolution = {};
  9912. }
  9913. /**
  9914. * The bandwidth
  9915. * @type {{}}
  9916. */
  9917. PeerStats.bandwidth = {};
  9918. /**
  9919. * The bit rate
  9920. * @type {{}}
  9921. */
  9922. PeerStats.bitrate = {};
  9923. /**
  9924. * The packet loss rate
  9925. * @type {{}}
  9926. */
  9927. PeerStats.packetLoss = null;
  9928. /**
  9929. * Sets packets loss rate for given <tt>ssrc</tt> that blong to the peer
  9930. * represented by this instance.
  9931. * @param ssrc audio or video RTP stream SSRC.
  9932. * @param lossRate new packet loss rate value to be set.
  9933. */
  9934. PeerStats.prototype.setSsrcLoss = function (ssrc, lossRate)
  9935. {
  9936. this.ssrc2Loss[ssrc] = lossRate;
  9937. };
  9938. /**
  9939. * Sets resolution for given <tt>ssrc</tt> that belong to the peer
  9940. * represented by this instance.
  9941. * @param ssrc audio or video RTP stream SSRC.
  9942. * @param resolution new resolution value to be set.
  9943. */
  9944. PeerStats.prototype.setSsrcResolution = function (ssrc, resolution)
  9945. {
  9946. if(resolution === null && this.ssrc2resolution[ssrc])
  9947. {
  9948. delete this.ssrc2resolution[ssrc];
  9949. }
  9950. else if(resolution !== null)
  9951. this.ssrc2resolution[ssrc] = resolution;
  9952. };
  9953. /**
  9954. * Sets the bit rate for given <tt>ssrc</tt> that blong to the peer
  9955. * represented by this instance.
  9956. * @param ssrc audio or video RTP stream SSRC.
  9957. * @param bitrate new bitrate value to be set.
  9958. */
  9959. PeerStats.prototype.setSsrcBitrate = function (ssrc, bitrate)
  9960. {
  9961. if(this.ssrc2bitrate[ssrc])
  9962. {
  9963. this.ssrc2bitrate[ssrc].download += bitrate.download;
  9964. this.ssrc2bitrate[ssrc].upload += bitrate.upload;
  9965. }
  9966. else {
  9967. this.ssrc2bitrate[ssrc] = bitrate;
  9968. }
  9969. };
  9970. /**
  9971. * Sets new audio level(input or output) for given <tt>ssrc</tt> that identifies
  9972. * the stream which belongs to the peer represented by this instance.
  9973. * @param ssrc RTP stream SSRC for which current audio level value will be
  9974. * updated.
  9975. * @param audioLevel the new audio level value to be set. Value is truncated to
  9976. * fit the range from 0 to 1.
  9977. */
  9978. PeerStats.prototype.setSsrcAudioLevel = function (ssrc, audioLevel)
  9979. {
  9980. // Range limit 0 - 1
  9981. this.ssrc2AudioLevel[ssrc] = formatAudioLevel(audioLevel);
  9982. };
  9983. function formatAudioLevel(audioLevel) {
  9984. return Math.min(Math.max(audioLevel, 0), 1);
  9985. }
  9986. /**
  9987. * Array with the transport information.
  9988. * @type {Array}
  9989. */
  9990. PeerStats.transport = [];
  9991. /**
  9992. * <tt>StatsCollector</tt> registers for stats updates of given
  9993. * <tt>peerconnection</tt> in given <tt>interval</tt>. On each update particular
  9994. * stats are extracted and put in {@link PeerStats} objects. Once the processing
  9995. * is done <tt>audioLevelsUpdateCallback</tt> is called with <tt>this</tt>
  9996. * instance as an event source.
  9997. *
  9998. * @param peerconnection webRTC peer connection object.
  9999. * @param interval stats refresh interval given in ms.
  10000. * @param {function(StatsCollector)} audioLevelsUpdateCallback the callback
  10001. * called on stats update.
  10002. * @constructor
  10003. */
  10004. function StatsCollector(peerconnection, audioLevelsInterval, statsInterval, eventEmitter)
  10005. {
  10006. this.peerconnection = peerconnection;
  10007. this.baselineAudioLevelsReport = null;
  10008. this.currentAudioLevelsReport = null;
  10009. this.currentStatsReport = null;
  10010. this.baselineStatsReport = null;
  10011. this.audioLevelsIntervalId = null;
  10012. this.eventEmitter = eventEmitter;
  10013. /**
  10014. * Gather PeerConnection stats once every this many milliseconds.
  10015. */
  10016. this.GATHER_INTERVAL = 15000;
  10017. /**
  10018. * Log stats via the focus once every this many milliseconds.
  10019. */
  10020. this.LOG_INTERVAL = 60000;
  10021. /**
  10022. * Gather stats and store them in this.statsToBeLogged.
  10023. */
  10024. this.gatherStatsIntervalId = null;
  10025. /**
  10026. * Send the stats already saved in this.statsToBeLogged to be logged via
  10027. * the focus.
  10028. */
  10029. this.logStatsIntervalId = null;
  10030. /**
  10031. * Stores the statistics which will be send to the focus to be logged.
  10032. */
  10033. this.statsToBeLogged =
  10034. {
  10035. timestamps: [],
  10036. stats: {}
  10037. };
  10038. // Updates stats interval
  10039. this.audioLevelsIntervalMilis = audioLevelsInterval;
  10040. this.statsIntervalId = null;
  10041. this.statsIntervalMilis = statsInterval;
  10042. // Map of jids to PeerStats
  10043. this.jid2stats = {};
  10044. }
  10045. module.exports = StatsCollector;
  10046. /**
  10047. * Stops stats updates.
  10048. */
  10049. StatsCollector.prototype.stop = function () {
  10050. if (this.audioLevelsIntervalId) {
  10051. clearInterval(this.audioLevelsIntervalId);
  10052. this.audioLevelsIntervalId = null;
  10053. }
  10054. if (this.statsIntervalId)
  10055. {
  10056. clearInterval(this.statsIntervalId);
  10057. this.statsIntervalId = null;
  10058. }
  10059. if(this.logStatsIntervalId)
  10060. {
  10061. clearInterval(this.logStatsIntervalId);
  10062. this.logStatsIntervalId = null;
  10063. }
  10064. if(this.gatherStatsIntervalId)
  10065. {
  10066. clearInterval(this.gatherStatsIntervalId);
  10067. this.gatherStatsIntervalId = null;
  10068. }
  10069. };
  10070. /**
  10071. * Callback passed to <tt>getStats</tt> method.
  10072. * @param error an error that occurred on <tt>getStats</tt> call.
  10073. */
  10074. StatsCollector.prototype.errorCallback = function (error)
  10075. {
  10076. console.error("Get stats error", error);
  10077. this.stop();
  10078. };
  10079. /**
  10080. * Starts stats updates.
  10081. */
  10082. StatsCollector.prototype.start = function ()
  10083. {
  10084. var self = this;
  10085. if(!config.disableAudioLevels) {
  10086. this.audioLevelsIntervalId = setInterval(
  10087. function () {
  10088. // Interval updates
  10089. self.peerconnection.getStats(
  10090. function (report) {
  10091. var results = null;
  10092. if (!report || !report.result ||
  10093. typeof report.result != 'function') {
  10094. results = report;
  10095. }
  10096. else {
  10097. results = report.result();
  10098. }
  10099. //console.error("Got interval report", results);
  10100. self.currentAudioLevelsReport = results;
  10101. self.processAudioLevelReport();
  10102. self.baselineAudioLevelsReport =
  10103. self.currentAudioLevelsReport;
  10104. },
  10105. self.errorCallback
  10106. );
  10107. },
  10108. self.audioLevelsIntervalMilis
  10109. );
  10110. }
  10111. if(!config.disableStats) {
  10112. this.statsIntervalId = setInterval(
  10113. function () {
  10114. // Interval updates
  10115. self.peerconnection.getStats(
  10116. function (report) {
  10117. var results = null;
  10118. if (!report || !report.result ||
  10119. typeof report.result != 'function') {
  10120. //firefox
  10121. results = report;
  10122. }
  10123. else {
  10124. //chrome
  10125. results = report.result();
  10126. }
  10127. //console.error("Got interval report", results);
  10128. self.currentStatsReport = results;
  10129. try {
  10130. self.processStatsReport();
  10131. }
  10132. catch (e) {
  10133. console.error("Unsupported key:" + e, e);
  10134. }
  10135. self.baselineStatsReport = self.currentStatsReport;
  10136. },
  10137. self.errorCallback
  10138. );
  10139. },
  10140. self.statsIntervalMilis
  10141. );
  10142. }
  10143. if (config.logStats) {
  10144. this.gatherStatsIntervalId = setInterval(
  10145. function () {
  10146. self.peerconnection.getStats(
  10147. function (report) {
  10148. self.addStatsToBeLogged(report.result());
  10149. },
  10150. function () {
  10151. }
  10152. );
  10153. },
  10154. this.GATHER_INTERVAL
  10155. );
  10156. this.logStatsIntervalId = setInterval(
  10157. function() { self.logStats(); },
  10158. this.LOG_INTERVAL);
  10159. }
  10160. };
  10161. /**
  10162. * Checks whether a certain record should be included in the logged statistics.
  10163. */
  10164. function acceptStat(reportId, reportType, statName) {
  10165. if (reportType == "googCandidatePair" && statName == "googChannelId")
  10166. return false;
  10167. if (reportType == "ssrc") {
  10168. if (statName == "googTrackId" ||
  10169. statName == "transportId" ||
  10170. statName == "ssrc")
  10171. return false;
  10172. }
  10173. return true;
  10174. }
  10175. /**
  10176. * Checks whether a certain record should be included in the logged statistics.
  10177. */
  10178. function acceptReport(id, type) {
  10179. if (id.substring(0, 15) == "googCertificate" ||
  10180. id.substring(0, 9) == "googTrack" ||
  10181. id.substring(0, 20) == "googLibjingleSession")
  10182. return false;
  10183. if (type == "googComponent")
  10184. return false;
  10185. return true;
  10186. }
  10187. /**
  10188. * Converts the stats to the format used for logging, and saves the data in
  10189. * this.statsToBeLogged.
  10190. * @param reports Reports as given by webkitRTCPerConnection.getStats.
  10191. */
  10192. StatsCollector.prototype.addStatsToBeLogged = function (reports) {
  10193. var self = this;
  10194. var num_records = this.statsToBeLogged.timestamps.length;
  10195. this.statsToBeLogged.timestamps.push(new Date().getTime());
  10196. reports.map(function (report) {
  10197. if (!acceptReport(report.id, report.type))
  10198. return;
  10199. var stat = self.statsToBeLogged.stats[report.id];
  10200. if (!stat) {
  10201. stat = self.statsToBeLogged.stats[report.id] = {};
  10202. }
  10203. stat.type = report.type;
  10204. report.names().map(function (name) {
  10205. if (!acceptStat(report.id, report.type, name))
  10206. return;
  10207. var values = stat[name];
  10208. if (!values) {
  10209. values = stat[name] = [];
  10210. }
  10211. while (values.length < num_records) {
  10212. values.push(null);
  10213. }
  10214. values.push(report.stat(name));
  10215. });
  10216. });
  10217. };
  10218. StatsCollector.prototype.logStats = function () {
  10219. if(!APP.xmpp.sendLogs(this.statsToBeLogged))
  10220. return;
  10221. // Reset the stats
  10222. this.statsToBeLogged.stats = {};
  10223. this.statsToBeLogged.timestamps = [];
  10224. };
  10225. var keyMap = {};
  10226. keyMap[RTCBrowserType.RTC_BROWSER_FIREFOX] = {
  10227. "ssrc": "ssrc",
  10228. "packetsReceived": "packetsReceived",
  10229. "packetsLost": "packetsLost",
  10230. "packetsSent": "packetsSent",
  10231. "bytesReceived": "bytesReceived",
  10232. "bytesSent": "bytesSent"
  10233. };
  10234. keyMap[RTCBrowserType.RTC_BROWSER_CHROME] = {
  10235. "receiveBandwidth": "googAvailableReceiveBandwidth",
  10236. "sendBandwidth": "googAvailableSendBandwidth",
  10237. "remoteAddress": "googRemoteAddress",
  10238. "transportType": "googTransportType",
  10239. "localAddress": "googLocalAddress",
  10240. "activeConnection": "googActiveConnection",
  10241. "ssrc": "ssrc",
  10242. "packetsReceived": "packetsReceived",
  10243. "packetsSent": "packetsSent",
  10244. "packetsLost": "packetsLost",
  10245. "bytesReceived": "bytesReceived",
  10246. "bytesSent": "bytesSent",
  10247. "googFrameHeightReceived": "googFrameHeightReceived",
  10248. "googFrameWidthReceived": "googFrameWidthReceived",
  10249. "googFrameHeightSent": "googFrameHeightSent",
  10250. "googFrameWidthSent": "googFrameWidthSent",
  10251. "audioInputLevel": "audioInputLevel",
  10252. "audioOutputLevel": "audioOutputLevel"
  10253. };
  10254. /**
  10255. * Stats processing logic.
  10256. */
  10257. StatsCollector.prototype.processStatsReport = function () {
  10258. if (!this.baselineStatsReport) {
  10259. return;
  10260. }
  10261. for (var idx in this.currentStatsReport) {
  10262. var now = this.currentStatsReport[idx];
  10263. try {
  10264. if (getStatValue(now, 'receiveBandwidth') ||
  10265. getStatValue(now, 'sendBandwidth')) {
  10266. PeerStats.bandwidth = {
  10267. "download": Math.round(
  10268. (getStatValue(now, 'receiveBandwidth')) / 1000),
  10269. "upload": Math.round(
  10270. (getStatValue(now, 'sendBandwidth')) / 1000)
  10271. };
  10272. }
  10273. }
  10274. catch(e){/*not supported*/}
  10275. if(now.type == 'googCandidatePair')
  10276. {
  10277. var ip, type, localIP, active;
  10278. try {
  10279. ip = getStatValue(now, 'remoteAddress');
  10280. type = getStatValue(now, "transportType");
  10281. localIP = getStatValue(now, "localAddress");
  10282. active = getStatValue(now, "activeConnection");
  10283. }
  10284. catch(e){/*not supported*/}
  10285. if(!ip || !type || !localIP || active != "true")
  10286. continue;
  10287. var addressSaved = false;
  10288. for(var i = 0; i < PeerStats.transport.length; i++)
  10289. {
  10290. if(PeerStats.transport[i].ip == ip &&
  10291. PeerStats.transport[i].type == type &&
  10292. PeerStats.transport[i].localip == localIP)
  10293. {
  10294. addressSaved = true;
  10295. }
  10296. }
  10297. if(addressSaved)
  10298. continue;
  10299. PeerStats.transport.push({localip: localIP, ip: ip, type: type});
  10300. continue;
  10301. }
  10302. if(now.type == "candidatepair")
  10303. {
  10304. if(now.state == "succeeded")
  10305. continue;
  10306. var local = this.currentStatsReport[now.localCandidateId];
  10307. var remote = this.currentStatsReport[now.remoteCandidateId];
  10308. PeerStats.transport.push({localip: local.ipAddress + ":" + local.portNumber,
  10309. ip: remote.ipAddress + ":" + remote.portNumber, type: local.transport});
  10310. }
  10311. if (now.type != 'ssrc' && now.type != "outboundrtp" &&
  10312. now.type != "inboundrtp") {
  10313. continue;
  10314. }
  10315. var before = this.baselineStatsReport[idx];
  10316. if (!before) {
  10317. console.warn(getStatValue(now, 'ssrc') + ' not enough data');
  10318. continue;
  10319. }
  10320. var ssrc = getStatValue(now, 'ssrc');
  10321. if(!ssrc)
  10322. continue;
  10323. var jid = APP.xmpp.getJidFromSSRC(ssrc);
  10324. if (!jid && (Date.now() - now.timestamp) < 3000) {
  10325. console.warn("No jid for ssrc: " + ssrc);
  10326. continue;
  10327. }
  10328. var jidStats = this.jid2stats[jid];
  10329. if (!jidStats) {
  10330. jidStats = new PeerStats();
  10331. this.jid2stats[jid] = jidStats;
  10332. }
  10333. var isDownloadStream = true;
  10334. var key = 'packetsReceived';
  10335. if (!getStatValue(now, key))
  10336. {
  10337. isDownloadStream = false;
  10338. key = 'packetsSent';
  10339. if (!getStatValue(now, key))
  10340. {
  10341. console.warn("No packetsReceived nor packetSent stat found");
  10342. continue;
  10343. }
  10344. }
  10345. var packetsNow = getStatValue(now, key);
  10346. if(!packetsNow || packetsNow < 0)
  10347. packetsNow = 0;
  10348. var packetsBefore = getStatValue(before, key);
  10349. if(!packetsBefore || packetsBefore < 0)
  10350. packetsBefore = 0;
  10351. var packetRate = packetsNow - packetsBefore;
  10352. if(!packetRate || packetRate < 0)
  10353. packetRate = 0;
  10354. var currentLoss = getStatValue(now, 'packetsLost');
  10355. if(!currentLoss || currentLoss < 0)
  10356. currentLoss = 0;
  10357. var previousLoss = getStatValue(before, 'packetsLost');
  10358. if(!previousLoss || previousLoss < 0)
  10359. previousLoss = 0;
  10360. var lossRate = currentLoss - previousLoss;
  10361. if(!lossRate || lossRate < 0)
  10362. lossRate = 0;
  10363. var packetsTotal = (packetRate + lossRate);
  10364. jidStats.setSsrcLoss(ssrc,
  10365. {"packetsTotal": packetsTotal,
  10366. "packetsLost": lossRate,
  10367. "isDownloadStream": isDownloadStream});
  10368. var bytesReceived = 0, bytesSent = 0;
  10369. if(getStatValue(now, "bytesReceived"))
  10370. {
  10371. bytesReceived = getStatValue(now, "bytesReceived") -
  10372. getStatValue(before, "bytesReceived");
  10373. }
  10374. if(getStatValue(now, "bytesSent"))
  10375. {
  10376. bytesSent = getStatValue(now, "bytesSent") -
  10377. getStatValue(before, "bytesSent");
  10378. }
  10379. var time = Math.round((now.timestamp - before.timestamp) / 1000);
  10380. if(bytesReceived <= 0 || time <= 0)
  10381. {
  10382. bytesReceived = 0;
  10383. }
  10384. else
  10385. {
  10386. bytesReceived = Math.round(((bytesReceived * 8) / time) / 1000);
  10387. }
  10388. if(bytesSent <= 0 || time <= 0)
  10389. {
  10390. bytesSent = 0;
  10391. }
  10392. else
  10393. {
  10394. bytesSent = Math.round(((bytesSent * 8) / time) / 1000);
  10395. }
  10396. jidStats.setSsrcBitrate(ssrc, {
  10397. "download": bytesReceived,
  10398. "upload": bytesSent});
  10399. var resolution = {height: null, width: null};
  10400. try {
  10401. if (getStatValue(now, "googFrameHeightReceived") &&
  10402. getStatValue(now, "googFrameWidthReceived")) {
  10403. resolution.height = getStatValue(now, "googFrameHeightReceived");
  10404. resolution.width = getStatValue(now, "googFrameWidthReceived");
  10405. }
  10406. else if (getStatValue(now, "googFrameHeightSent") &&
  10407. getStatValue(now, "googFrameWidthSent")) {
  10408. resolution.height = getStatValue(now, "googFrameHeightSent");
  10409. resolution.width = getStatValue(now, "googFrameWidthSent");
  10410. }
  10411. }
  10412. catch(e){/*not supported*/}
  10413. if(resolution.height && resolution.width)
  10414. {
  10415. jidStats.setSsrcResolution(ssrc, resolution);
  10416. }
  10417. else
  10418. {
  10419. jidStats.setSsrcResolution(ssrc, null);
  10420. }
  10421. }
  10422. var self = this;
  10423. // Jid stats
  10424. var totalPackets = {download: 0, upload: 0};
  10425. var lostPackets = {download: 0, upload: 0};
  10426. var bitrateDownload = 0;
  10427. var bitrateUpload = 0;
  10428. var resolutions = {};
  10429. Object.keys(this.jid2stats).forEach(
  10430. function (jid)
  10431. {
  10432. Object.keys(self.jid2stats[jid].ssrc2Loss).forEach(
  10433. function (ssrc)
  10434. {
  10435. var type = "upload";
  10436. if(self.jid2stats[jid].ssrc2Loss[ssrc].isDownloadStream)
  10437. type = "download";
  10438. totalPackets[type] +=
  10439. self.jid2stats[jid].ssrc2Loss[ssrc].packetsTotal;
  10440. lostPackets[type] +=
  10441. self.jid2stats[jid].ssrc2Loss[ssrc].packetsLost;
  10442. }
  10443. );
  10444. Object.keys(self.jid2stats[jid].ssrc2bitrate).forEach(
  10445. function (ssrc) {
  10446. bitrateDownload +=
  10447. self.jid2stats[jid].ssrc2bitrate[ssrc].download;
  10448. bitrateUpload +=
  10449. self.jid2stats[jid].ssrc2bitrate[ssrc].upload;
  10450. delete self.jid2stats[jid].ssrc2bitrate[ssrc];
  10451. }
  10452. );
  10453. resolutions[jid] = self.jid2stats[jid].ssrc2resolution;
  10454. }
  10455. );
  10456. PeerStats.bitrate = {"upload": bitrateUpload, "download": bitrateDownload};
  10457. PeerStats.packetLoss = {
  10458. total:
  10459. calculatePacketLoss(lostPackets.download + lostPackets.upload,
  10460. totalPackets.download + totalPackets.upload),
  10461. download:
  10462. calculatePacketLoss(lostPackets.download, totalPackets.download),
  10463. upload:
  10464. calculatePacketLoss(lostPackets.upload, totalPackets.upload)
  10465. };
  10466. this.eventEmitter.emit("statistics.connectionstats",
  10467. {
  10468. "bitrate": PeerStats.bitrate,
  10469. "packetLoss": PeerStats.packetLoss,
  10470. "bandwidth": PeerStats.bandwidth,
  10471. "resolution": resolutions,
  10472. "transport": PeerStats.transport
  10473. });
  10474. PeerStats.transport = [];
  10475. };
  10476. /**
  10477. * Stats processing logic.
  10478. */
  10479. StatsCollector.prototype.processAudioLevelReport = function ()
  10480. {
  10481. if (!this.baselineAudioLevelsReport)
  10482. {
  10483. return;
  10484. }
  10485. for (var idx in this.currentAudioLevelsReport)
  10486. {
  10487. var now = this.currentAudioLevelsReport[idx];
  10488. if (now.type != 'ssrc')
  10489. {
  10490. continue;
  10491. }
  10492. var before = this.baselineAudioLevelsReport[idx];
  10493. if (!before)
  10494. {
  10495. console.warn(getStatValue(now, 'ssrc') + ' not enough data');
  10496. continue;
  10497. }
  10498. var ssrc = getStatValue(now, 'ssrc');
  10499. var jid = APP.xmpp.getJidFromSSRC(ssrc);
  10500. if (!jid && (Date.now() - now.timestamp) < 3000)
  10501. {
  10502. console.warn("No jid for ssrc: " + ssrc);
  10503. continue;
  10504. }
  10505. var jidStats = this.jid2stats[jid];
  10506. if (!jidStats)
  10507. {
  10508. jidStats = new PeerStats();
  10509. this.jid2stats[jid] = jidStats;
  10510. }
  10511. // Audio level
  10512. var audioLevel = null;
  10513. try {
  10514. audioLevel = getStatValue(now, 'audioInputLevel');
  10515. if (!audioLevel)
  10516. audioLevel = getStatValue(now, 'audioOutputLevel');
  10517. }
  10518. catch(e) {/*not supported*/
  10519. console.warn("Audio Levels are not available in the statistics.");
  10520. clearInterval(this.audioLevelsIntervalId);
  10521. return;
  10522. }
  10523. if (audioLevel)
  10524. {
  10525. // TODO: can't find specs about what this value really is,
  10526. // but it seems to vary between 0 and around 32k.
  10527. audioLevel = audioLevel / 32767;
  10528. jidStats.setSsrcAudioLevel(ssrc, audioLevel);
  10529. if(jid != APP.xmpp.myJid())
  10530. this.eventEmitter.emit("statistics.audioLevel", jid, audioLevel);
  10531. }
  10532. }
  10533. };
  10534. },{"../../service/RTC/RTCBrowserType":91}],48:[function(require,module,exports){
  10535. /**
  10536. * Created by hristo on 8/4/14.
  10537. */
  10538. var LocalStats = require("./LocalStatsCollector.js");
  10539. var RTPStats = require("./RTPStatsCollector.js");
  10540. var EventEmitter = require("events");
  10541. var StreamEventTypes = require("../../service/RTC/StreamEventTypes.js");
  10542. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  10543. var eventEmitter = new EventEmitter();
  10544. var localStats = null;
  10545. var rtpStats = null;
  10546. function stopLocal()
  10547. {
  10548. if(localStats)
  10549. {
  10550. localStats.stop();
  10551. localStats = null;
  10552. }
  10553. }
  10554. function stopRemote()
  10555. {
  10556. if(rtpStats)
  10557. {
  10558. rtpStats.stop();
  10559. eventEmitter.emit("statistics.stop");
  10560. rtpStats = null;
  10561. }
  10562. }
  10563. function startRemoteStats (peerconnection) {
  10564. if(rtpStats)
  10565. {
  10566. rtpStats.stop();
  10567. rtpStats = null;
  10568. }
  10569. rtpStats = new RTPStats(peerconnection, 200, 2000, eventEmitter);
  10570. rtpStats.start();
  10571. }
  10572. function onStreamCreated(stream)
  10573. {
  10574. if(stream.getOriginalStream().getAudioTracks().length === 0)
  10575. return;
  10576. localStats = new LocalStats(stream.getOriginalStream(), 200, statistics,
  10577. eventEmitter);
  10578. localStats.start();
  10579. }
  10580. function onDisposeConference(onUnload) {
  10581. stopRemote();
  10582. if(onUnload) {
  10583. stopLocal();
  10584. eventEmitter.removeAllListeners();
  10585. }
  10586. }
  10587. var statistics =
  10588. {
  10589. /**
  10590. * Indicates that this audio level is for local jid.
  10591. * @type {string}
  10592. */
  10593. LOCAL_JID: 'local',
  10594. addAudioLevelListener: function(listener)
  10595. {
  10596. eventEmitter.on("statistics.audioLevel", listener);
  10597. },
  10598. removeAudioLevelListener: function(listener)
  10599. {
  10600. eventEmitter.removeListener("statistics.audioLevel", listener);
  10601. },
  10602. addConnectionStatsListener: function(listener)
  10603. {
  10604. eventEmitter.on("statistics.connectionstats", listener);
  10605. },
  10606. removeConnectionStatsListener: function(listener)
  10607. {
  10608. eventEmitter.removeListener("statistics.connectionstats", listener);
  10609. },
  10610. addRemoteStatsStopListener: function(listener)
  10611. {
  10612. eventEmitter.on("statistics.stop", listener);
  10613. },
  10614. removeRemoteStatsStopListener: function(listener)
  10615. {
  10616. eventEmitter.removeListener("statistics.stop", listener);
  10617. },
  10618. stop: function () {
  10619. stopLocal();
  10620. stopRemote();
  10621. if(eventEmitter)
  10622. {
  10623. eventEmitter.removeAllListeners();
  10624. }
  10625. },
  10626. stopRemoteStatistics: function()
  10627. {
  10628. stopRemote();
  10629. },
  10630. start: function () {
  10631. APP.RTC.addStreamListener(onStreamCreated,
  10632. StreamEventTypes.EVENT_TYPE_LOCAL_CREATED);
  10633. APP.xmpp.addListener(XMPPEvents.DISPOSE_CONFERENCE, onDisposeConference);
  10634. APP.xmpp.addListener(XMPPEvents.CALL_INCOMING, function (event) {
  10635. startRemoteStats(event.peerconnection);
  10636. });
  10637. }
  10638. };
  10639. module.exports = statistics;
  10640. },{"../../service/RTC/StreamEventTypes.js":94,"../../service/xmpp/XMPPEvents":101,"./LocalStatsCollector.js":46,"./RTPStatsCollector.js":47,"events":102}],49:[function(require,module,exports){
  10641. var i18n = require("i18next-client");
  10642. var languages = require("../../service/translation/languages");
  10643. var Settings = require("../settings/Settings");
  10644. var DEFAULT_LANG = languages.EN;
  10645. i18n.addPostProcessor("resolveAppName", function(value, key, options) {
  10646. return value.replace("__app__", interfaceConfig.APP_NAME);
  10647. });
  10648. var defaultOptions = {
  10649. detectLngQS: "lang",
  10650. useCookie: false,
  10651. fallbackLng: DEFAULT_LANG,
  10652. load: "unspecific",
  10653. resGetPath: 'lang/__ns__-__lng__.json',
  10654. ns: {
  10655. namespaces: ['main', 'languages'],
  10656. defaultNs: 'main'
  10657. },
  10658. lngWhitelist : languages.getLanguages(),
  10659. fallbackOnNull: true,
  10660. fallbackOnEmpty: true,
  10661. useDataAttrOptions: true,
  10662. defaultValueFromContent: false,
  10663. app: interfaceConfig.APP_NAME,
  10664. getAsync: false,
  10665. defaultValueFromContent: false,
  10666. customLoad: function(lng, ns, options, done) {
  10667. var resPath = "lang/__ns__-__lng__.json";
  10668. if(lng === languages.EN)
  10669. resPath = "lang/__ns__.json";
  10670. var url = i18n.functions.applyReplacement(resPath, { lng: lng, ns: ns });
  10671. i18n.functions.ajax({
  10672. url: url,
  10673. success: function(data, status, xhr) {
  10674. i18n.functions.log('loaded: ' + url);
  10675. done(null, data);
  10676. },
  10677. error : function(xhr, status, error) {
  10678. if ((status && status == 200) ||
  10679. (xhr && xhr.status && xhr.status == 200)) {
  10680. // file loaded but invalid json, stop waste time !
  10681. i18n.functions.error('There is a typo in: ' + url);
  10682. } else if ((status && status == 404) ||
  10683. (xhr && xhr.status && xhr.status == 404)) {
  10684. i18n.functions.log('Does not exist: ' + url);
  10685. } else {
  10686. var theStatus = status ? status :
  10687. ((xhr && xhr.status) ? xhr.status : null);
  10688. i18n.functions.log(theStatus + ' when loading ' + url);
  10689. }
  10690. done(error, {});
  10691. },
  10692. dataType: "json",
  10693. async : options.getAsync
  10694. });
  10695. }
  10696. // options for caching
  10697. // useLocalStorage: true,
  10698. // localStorageExpirationTime: 86400000 // in ms, default 1 week
  10699. };
  10700. function initCompleted(t)
  10701. {
  10702. $("[data-i18n]").i18n();
  10703. }
  10704. function checkForParameter() {
  10705. var query = window.location.search.substring(1);
  10706. var vars = query.split("&");
  10707. for (var i=0;i<vars.length;i++) {
  10708. var pair = vars[i].split("=");
  10709. if(pair[0] == "lang")
  10710. {
  10711. return pair[1];
  10712. }
  10713. }
  10714. return null;
  10715. }
  10716. module.exports = {
  10717. init: function (lang) {
  10718. var options = defaultOptions;
  10719. if(!lang)
  10720. {
  10721. lang = checkForParameter();
  10722. if(!lang)
  10723. {
  10724. var settings = Settings.getSettings();
  10725. if(settings)
  10726. lang = settings.language;
  10727. }
  10728. }
  10729. if(lang) {
  10730. options.lng = lang;
  10731. }
  10732. i18n.init(options, initCompleted);
  10733. },
  10734. translateString: function (key, options) {
  10735. return i18n.t(key, options);
  10736. },
  10737. setLanguage: function (lang) {
  10738. if(!lang)
  10739. lang = DEFAULT_LANG;
  10740. i18n.setLng(lang, defaultOptions, initCompleted);
  10741. },
  10742. getCurrentLanguage: function () {
  10743. return i18n.lng();
  10744. },
  10745. translateElement: function (selector) {
  10746. selector.i18n();
  10747. },
  10748. generateTranslatonHTML: function (key, options) {
  10749. var str = "<span data-i18n=\"" + key + "\"";
  10750. if(options)
  10751. {
  10752. str += " data-i18n-options=\"" + JSON.stringify(options) + "\"";
  10753. }
  10754. str += ">";
  10755. str += this.translateString(key, options);
  10756. str += "</span>";
  10757. return str;
  10758. }
  10759. };
  10760. },{"../../service/translation/languages":100,"../settings/Settings":40,"i18next-client":65}],50:[function(require,module,exports){
  10761. /* jshint -W117 */
  10762. var TraceablePeerConnection = require("./TraceablePeerConnection");
  10763. var SDPDiffer = require("./SDPDiffer");
  10764. var SDPUtil = require("./SDPUtil");
  10765. var SDP = require("./SDP");
  10766. var RTCBrowserType = require("../../service/RTC/RTCBrowserType");
  10767. var async = require("async");
  10768. // Jingle stuff
  10769. function JingleSession(me, sid, connection, service) {
  10770. this.me = me;
  10771. this.sid = sid;
  10772. this.connection = connection;
  10773. this.initiator = null;
  10774. this.responder = null;
  10775. this.isInitiator = null;
  10776. this.peerjid = null;
  10777. this.state = null;
  10778. this.localSDP = null;
  10779. this.remoteSDP = null;
  10780. this.relayedStreams = [];
  10781. this.startTime = null;
  10782. this.stopTime = null;
  10783. this.media_constraints = null;
  10784. this.pc_constraints = null;
  10785. this.ice_config = {};
  10786. this.drip_container = [];
  10787. this.service = service;
  10788. this.usetrickle = true;
  10789. this.usepranswer = false; // early transport warmup -- mind you, this might fail. depends on webrtc issue 1718
  10790. this.usedrip = false; // dripping is sending trickle candidates not one-by-one
  10791. this.hadstuncandidate = false;
  10792. this.hadturncandidate = false;
  10793. this.lasticecandidate = false;
  10794. this.statsinterval = null;
  10795. this.reason = null;
  10796. this.addssrc = [];
  10797. this.removessrc = [];
  10798. this.pendingop = null;
  10799. this.switchstreams = false;
  10800. this.wait = true;
  10801. this.localStreamsSSRC = null;
  10802. /**
  10803. * The indicator which determines whether the (local) video has been muted
  10804. * in response to a user command in contrast to an automatic decision made
  10805. * by the application logic.
  10806. */
  10807. this.videoMuteByUser = false;
  10808. this.modifySourcesQueue = async.queue(this._modifySources.bind(this), 1);
  10809. }
  10810. //TODO: this array must be removed when firefox implement multistream support
  10811. JingleSession.notReceivedSSRCs = [];
  10812. JingleSession.prototype.initiate = function (peerjid, isInitiator) {
  10813. var self = this;
  10814. if (this.state !== null) {
  10815. console.error('attempt to initiate on session ' + this.sid +
  10816. 'in state ' + this.state);
  10817. return;
  10818. }
  10819. this.isInitiator = isInitiator;
  10820. this.state = 'pending';
  10821. this.initiator = isInitiator ? this.me : peerjid;
  10822. this.responder = !isInitiator ? this.me : peerjid;
  10823. this.peerjid = peerjid;
  10824. this.hadstuncandidate = false;
  10825. this.hadturncandidate = false;
  10826. this.lasticecandidate = false;
  10827. this.peerconnection
  10828. = new TraceablePeerConnection(
  10829. this.connection.jingle.ice_config,
  10830. this.connection.jingle.pc_constraints );
  10831. this.peerconnection.onicecandidate = function (event) {
  10832. self.sendIceCandidate(event.candidate);
  10833. };
  10834. this.peerconnection.onaddstream = function (event) {
  10835. console.log("REMOTE STREAM ADDED: " + event.stream + " - " + event.stream.id);
  10836. self.remoteStreamAdded(event);
  10837. };
  10838. this.peerconnection.onremovestream = function (event) {
  10839. // Remove the stream from remoteStreams
  10840. // FIXME: remotestreamremoved.jingle not defined anywhere(unused)
  10841. $(document).trigger('remotestreamremoved.jingle', [event, self.sid]);
  10842. };
  10843. this.peerconnection.onsignalingstatechange = function (event) {
  10844. if (!(self && self.peerconnection)) return;
  10845. };
  10846. this.peerconnection.oniceconnectionstatechange = function (event) {
  10847. if (!(self && self.peerconnection)) return;
  10848. switch (self.peerconnection.iceConnectionState) {
  10849. case 'connected':
  10850. this.startTime = new Date();
  10851. break;
  10852. case 'disconnected':
  10853. this.stopTime = new Date();
  10854. break;
  10855. }
  10856. onIceConnectionStateChange(self.sid, self);
  10857. };
  10858. // add any local and relayed stream
  10859. APP.RTC.localStreams.forEach(function(stream) {
  10860. self.peerconnection.addStream(stream.getOriginalStream());
  10861. });
  10862. this.relayedStreams.forEach(function(stream) {
  10863. self.peerconnection.addStream(stream);
  10864. });
  10865. };
  10866. function onIceConnectionStateChange(sid, session) {
  10867. switch (session.peerconnection.iceConnectionState) {
  10868. case 'checking':
  10869. session.timeChecking = (new Date()).getTime();
  10870. session.firstconnect = true;
  10871. break;
  10872. case 'completed': // on caller side
  10873. case 'connected':
  10874. if (session.firstconnect) {
  10875. session.firstconnect = false;
  10876. var metadata = {};
  10877. metadata.setupTime
  10878. = (new Date()).getTime() - session.timeChecking;
  10879. session.peerconnection.getStats(function (res) {
  10880. if(res && res.result) {
  10881. res.result().forEach(function (report) {
  10882. if (report.type == 'googCandidatePair' &&
  10883. report.stat('googActiveConnection') == 'true') {
  10884. metadata.localCandidateType
  10885. = report.stat('googLocalCandidateType');
  10886. metadata.remoteCandidateType
  10887. = report.stat('googRemoteCandidateType');
  10888. // log pair as well so we can get nice pie
  10889. // charts
  10890. metadata.candidatePair
  10891. = report.stat('googLocalCandidateType') +
  10892. ';' +
  10893. report.stat('googRemoteCandidateType');
  10894. if (report.stat('googRemoteAddress').indexOf('[') === 0)
  10895. {
  10896. metadata.ipv6 = true;
  10897. }
  10898. }
  10899. });
  10900. }
  10901. });
  10902. }
  10903. break;
  10904. }
  10905. }
  10906. JingleSession.prototype.accept = function () {
  10907. var self = this;
  10908. this.state = 'active';
  10909. var pranswer = this.peerconnection.localDescription;
  10910. if (!pranswer || pranswer.type != 'pranswer') {
  10911. return;
  10912. }
  10913. console.log('going from pranswer to answer');
  10914. if (this.usetrickle) {
  10915. // remove candidates already sent from session-accept
  10916. var lines = SDPUtil.find_lines(pranswer.sdp, 'a=candidate:');
  10917. for (var i = 0; i < lines.length; i++) {
  10918. pranswer.sdp = pranswer.sdp.replace(lines[i] + '\r\n', '');
  10919. }
  10920. }
  10921. while (SDPUtil.find_line(pranswer.sdp, 'a=inactive')) {
  10922. // FIXME: change any inactive to sendrecv or whatever they were originally
  10923. pranswer.sdp = pranswer.sdp.replace('a=inactive', 'a=sendrecv');
  10924. }
  10925. pranswer = APP.simulcast.reverseTransformLocalDescription(pranswer);
  10926. var prsdp = new SDP(pranswer.sdp);
  10927. var accept = $iq({to: this.peerjid,
  10928. type: 'set'})
  10929. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  10930. action: 'session-accept',
  10931. initiator: this.initiator,
  10932. responder: this.responder,
  10933. sid: this.sid });
  10934. prsdp.toJingle(accept, this.initiator == this.me ? 'initiator' : 'responder', this.localStreamsSSRC);
  10935. var sdp = this.peerconnection.localDescription.sdp;
  10936. while (SDPUtil.find_line(sdp, 'a=inactive')) {
  10937. // FIXME: change any inactive to sendrecv or whatever they were originally
  10938. sdp = sdp.replace('a=inactive', 'a=sendrecv');
  10939. }
  10940. var self = this;
  10941. this.peerconnection.setLocalDescription(new RTCSessionDescription({type: 'answer', sdp: sdp}),
  10942. function () {
  10943. //console.log('setLocalDescription success');
  10944. self.setLocalDescription();
  10945. self.connection.sendIQ(accept,
  10946. function () {
  10947. var ack = {};
  10948. ack.source = 'answer';
  10949. $(document).trigger('ack.jingle', [self.sid, ack]);
  10950. },
  10951. function (stanza) {
  10952. var error = ($(stanza).find('error').length) ? {
  10953. code: $(stanza).find('error').attr('code'),
  10954. reason: $(stanza).find('error :first')[0].tagName
  10955. }:{};
  10956. error.source = 'answer';
  10957. JingleSession.onJingleError(self.sid, error);
  10958. },
  10959. 10000);
  10960. },
  10961. function (e) {
  10962. console.error('setLocalDescription failed', e);
  10963. }
  10964. );
  10965. };
  10966. JingleSession.prototype.terminate = function (reason) {
  10967. this.state = 'ended';
  10968. this.reason = reason;
  10969. this.peerconnection.close();
  10970. if (this.statsinterval !== null) {
  10971. window.clearInterval(this.statsinterval);
  10972. this.statsinterval = null;
  10973. }
  10974. };
  10975. JingleSession.prototype.active = function () {
  10976. return this.state == 'active';
  10977. };
  10978. JingleSession.prototype.sendIceCandidate = function (candidate) {
  10979. var self = this;
  10980. if (candidate && !this.lasticecandidate) {
  10981. var ice = SDPUtil.iceparams(this.localSDP.media[candidate.sdpMLineIndex], this.localSDP.session);
  10982. var jcand = SDPUtil.candidateToJingle(candidate.candidate);
  10983. if (!(ice && jcand)) {
  10984. console.error('failed to get ice && jcand');
  10985. return;
  10986. }
  10987. ice.xmlns = 'urn:xmpp:jingle:transports:ice-udp:1';
  10988. if (jcand.type === 'srflx') {
  10989. this.hadstuncandidate = true;
  10990. } else if (jcand.type === 'relay') {
  10991. this.hadturncandidate = true;
  10992. }
  10993. if (this.usetrickle) {
  10994. if (this.usedrip) {
  10995. if (this.drip_container.length === 0) {
  10996. // start 20ms callout
  10997. window.setTimeout(function () {
  10998. if (self.drip_container.length === 0) return;
  10999. self.sendIceCandidates(self.drip_container);
  11000. self.drip_container = [];
  11001. }, 20);
  11002. }
  11003. this.drip_container.push(candidate);
  11004. return;
  11005. } else {
  11006. self.sendIceCandidate([candidate]);
  11007. }
  11008. }
  11009. } else {
  11010. //console.log('sendIceCandidate: last candidate.');
  11011. if (!this.usetrickle) {
  11012. //console.log('should send full offer now...');
  11013. var init = $iq({to: this.peerjid,
  11014. type: 'set'})
  11015. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  11016. action: this.peerconnection.localDescription.type == 'offer' ? 'session-initiate' : 'session-accept',
  11017. initiator: this.initiator,
  11018. sid: this.sid});
  11019. this.localSDP = new SDP(this.peerconnection.localDescription.sdp);
  11020. var self = this;
  11021. var sendJingle = function (ssrc) {
  11022. if(!ssrc)
  11023. ssrc = {};
  11024. self.localSDP.toJingle(init, self.initiator == self.me ? 'initiator' : 'responder', ssrc);
  11025. self.connection.sendIQ(init,
  11026. function () {
  11027. //console.log('session initiate ack');
  11028. var ack = {};
  11029. ack.source = 'offer';
  11030. $(document).trigger('ack.jingle', [self.sid, ack]);
  11031. },
  11032. function (stanza) {
  11033. self.state = 'error';
  11034. self.peerconnection.close();
  11035. var error = ($(stanza).find('error').length) ? {
  11036. code: $(stanza).find('error').attr('code'),
  11037. reason: $(stanza).find('error :first')[0].tagName,
  11038. }:{};
  11039. error.source = 'offer';
  11040. JingleSession.onJingleError(self.sid, error);
  11041. },
  11042. 10000);
  11043. }
  11044. sendJingle();
  11045. }
  11046. this.lasticecandidate = true;
  11047. console.log('Have we encountered any srflx candidates? ' + this.hadstuncandidate);
  11048. console.log('Have we encountered any relay candidates? ' + this.hadturncandidate);
  11049. if (!(this.hadstuncandidate || this.hadturncandidate) && this.peerconnection.signalingState != 'closed') {
  11050. $(document).trigger('nostuncandidates.jingle', [this.sid]);
  11051. }
  11052. }
  11053. };
  11054. JingleSession.prototype.sendIceCandidates = function (candidates) {
  11055. console.log('sendIceCandidates', candidates);
  11056. var cand = $iq({to: this.peerjid, type: 'set'})
  11057. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  11058. action: 'transport-info',
  11059. initiator: this.initiator,
  11060. sid: this.sid});
  11061. for (var mid = 0; mid < this.localSDP.media.length; mid++) {
  11062. var cands = candidates.filter(function (el) { return el.sdpMLineIndex == mid; });
  11063. var mline = SDPUtil.parse_mline(this.localSDP.media[mid].split('\r\n')[0]);
  11064. if (cands.length > 0) {
  11065. var ice = SDPUtil.iceparams(this.localSDP.media[mid], this.localSDP.session);
  11066. ice.xmlns = 'urn:xmpp:jingle:transports:ice-udp:1';
  11067. cand.c('content', {creator: this.initiator == this.me ? 'initiator' : 'responder',
  11068. name: (cands[0].sdpMid? cands[0].sdpMid : mline.media)
  11069. }).c('transport', ice);
  11070. for (var i = 0; i < cands.length; i++) {
  11071. cand.c('candidate', SDPUtil.candidateToJingle(cands[i].candidate)).up();
  11072. }
  11073. // add fingerprint
  11074. if (SDPUtil.find_line(this.localSDP.media[mid], 'a=fingerprint:', this.localSDP.session)) {
  11075. var tmp = SDPUtil.parse_fingerprint(SDPUtil.find_line(this.localSDP.media[mid], 'a=fingerprint:', this.localSDP.session));
  11076. tmp.required = true;
  11077. cand.c(
  11078. 'fingerprint',
  11079. {xmlns: 'urn:xmpp:jingle:apps:dtls:0'})
  11080. .t(tmp.fingerprint);
  11081. delete tmp.fingerprint;
  11082. cand.attrs(tmp);
  11083. cand.up();
  11084. }
  11085. cand.up(); // transport
  11086. cand.up(); // content
  11087. }
  11088. }
  11089. // might merge last-candidate notification into this, but it is called alot later. See webrtc issue #2340
  11090. //console.log('was this the last candidate', this.lasticecandidate);
  11091. this.connection.sendIQ(cand,
  11092. function () {
  11093. var ack = {};
  11094. ack.source = 'transportinfo';
  11095. $(document).trigger('ack.jingle', [this.sid, ack]);
  11096. },
  11097. function (stanza) {
  11098. var error = ($(stanza).find('error').length) ? {
  11099. code: $(stanza).find('error').attr('code'),
  11100. reason: $(stanza).find('error :first')[0].tagName,
  11101. }:{};
  11102. error.source = 'transportinfo';
  11103. JingleSession.onJingleError(this.sid, error);
  11104. },
  11105. 10000);
  11106. };
  11107. JingleSession.prototype.sendOffer = function () {
  11108. //console.log('sendOffer...');
  11109. var self = this;
  11110. this.peerconnection.createOffer(function (sdp) {
  11111. self.createdOffer(sdp);
  11112. },
  11113. function (e) {
  11114. console.error('createOffer failed', e);
  11115. },
  11116. this.media_constraints
  11117. );
  11118. };
  11119. JingleSession.prototype.createdOffer = function (sdp) {
  11120. //console.log('createdOffer', sdp);
  11121. var self = this;
  11122. this.localSDP = new SDP(sdp.sdp);
  11123. //this.localSDP.mangle();
  11124. var sendJingle = function () {
  11125. var init = $iq({to: this.peerjid,
  11126. type: 'set'})
  11127. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  11128. action: 'session-initiate',
  11129. initiator: this.initiator,
  11130. sid: this.sid});
  11131. self.localSDP.toJingle(init, this.initiator == this.me ? 'initiator' : 'responder', this.localStreamsSSRC);
  11132. self.connection.sendIQ(init,
  11133. function () {
  11134. var ack = {};
  11135. ack.source = 'offer';
  11136. $(document).trigger('ack.jingle', [self.sid, ack]);
  11137. },
  11138. function (stanza) {
  11139. self.state = 'error';
  11140. self.peerconnection.close();
  11141. var error = ($(stanza).find('error').length) ? {
  11142. code: $(stanza).find('error').attr('code'),
  11143. reason: $(stanza).find('error :first')[0].tagName,
  11144. }:{};
  11145. error.source = 'offer';
  11146. JingleSession.onJingleError(self.sid, error);
  11147. },
  11148. 10000);
  11149. }
  11150. sdp.sdp = this.localSDP.raw;
  11151. this.peerconnection.setLocalDescription(sdp,
  11152. function () {
  11153. if(self.usetrickle)
  11154. {
  11155. sendJingle();
  11156. }
  11157. self.setLocalDescription();
  11158. //console.log('setLocalDescription success');
  11159. },
  11160. function (e) {
  11161. console.error('setLocalDescription failed', e);
  11162. }
  11163. );
  11164. var cands = SDPUtil.find_lines(this.localSDP.raw, 'a=candidate:');
  11165. for (var i = 0; i < cands.length; i++) {
  11166. var cand = SDPUtil.parse_icecandidate(cands[i]);
  11167. if (cand.type == 'srflx') {
  11168. this.hadstuncandidate = true;
  11169. } else if (cand.type == 'relay') {
  11170. this.hadturncandidate = true;
  11171. }
  11172. }
  11173. };
  11174. JingleSession.prototype.setRemoteDescription = function (elem, desctype) {
  11175. //console.log('setting remote description... ', desctype);
  11176. this.remoteSDP = new SDP('');
  11177. this.remoteSDP.fromJingle(elem);
  11178. if (this.peerconnection.remoteDescription !== null) {
  11179. console.log('setRemoteDescription when remote description is not null, should be pranswer', this.peerconnection.remoteDescription);
  11180. if (this.peerconnection.remoteDescription.type == 'pranswer') {
  11181. var pranswer = new SDP(this.peerconnection.remoteDescription.sdp);
  11182. for (var i = 0; i < pranswer.media.length; i++) {
  11183. // make sure we have ice ufrag and pwd
  11184. if (!SDPUtil.find_line(this.remoteSDP.media[i], 'a=ice-ufrag:', this.remoteSDP.session)) {
  11185. if (SDPUtil.find_line(pranswer.media[i], 'a=ice-ufrag:', pranswer.session)) {
  11186. this.remoteSDP.media[i] += SDPUtil.find_line(pranswer.media[i], 'a=ice-ufrag:', pranswer.session) + '\r\n';
  11187. } else {
  11188. console.warn('no ice ufrag?');
  11189. }
  11190. if (SDPUtil.find_line(pranswer.media[i], 'a=ice-pwd:', pranswer.session)) {
  11191. this.remoteSDP.media[i] += SDPUtil.find_line(pranswer.media[i], 'a=ice-pwd:', pranswer.session) + '\r\n';
  11192. } else {
  11193. console.warn('no ice pwd?');
  11194. }
  11195. }
  11196. // copy over candidates
  11197. var lines = SDPUtil.find_lines(pranswer.media[i], 'a=candidate:');
  11198. for (var j = 0; j < lines.length; j++) {
  11199. this.remoteSDP.media[i] += lines[j] + '\r\n';
  11200. }
  11201. }
  11202. this.remoteSDP.raw = this.remoteSDP.session + this.remoteSDP.media.join('');
  11203. }
  11204. }
  11205. var remotedesc = new RTCSessionDescription({type: desctype, sdp: this.remoteSDP.raw});
  11206. this.peerconnection.setRemoteDescription(remotedesc,
  11207. function () {
  11208. //console.log('setRemoteDescription success');
  11209. },
  11210. function (e) {
  11211. console.error('setRemoteDescription error', e);
  11212. JingleSession.onJingleFatalError(self, e);
  11213. }
  11214. );
  11215. };
  11216. JingleSession.prototype.addIceCandidate = function (elem) {
  11217. var self = this;
  11218. if (this.peerconnection.signalingState == 'closed') {
  11219. return;
  11220. }
  11221. if (!this.peerconnection.remoteDescription && this.peerconnection.signalingState == 'have-local-offer') {
  11222. console.log('trickle ice candidate arriving before session accept...');
  11223. // create a PRANSWER for setRemoteDescription
  11224. if (!this.remoteSDP) {
  11225. var cobbled = 'v=0\r\n' +
  11226. 'o=- ' + '1923518516' + ' 2 IN IP4 0.0.0.0\r\n' +// FIXME
  11227. 's=-\r\n' +
  11228. 't=0 0\r\n';
  11229. // first, take some things from the local description
  11230. for (var i = 0; i < this.localSDP.media.length; i++) {
  11231. cobbled += SDPUtil.find_line(this.localSDP.media[i], 'm=') + '\r\n';
  11232. cobbled += SDPUtil.find_lines(this.localSDP.media[i], 'a=rtpmap:').join('\r\n') + '\r\n';
  11233. if (SDPUtil.find_line(this.localSDP.media[i], 'a=mid:')) {
  11234. cobbled += SDPUtil.find_line(this.localSDP.media[i], 'a=mid:') + '\r\n';
  11235. }
  11236. cobbled += 'a=inactive\r\n';
  11237. }
  11238. this.remoteSDP = new SDP(cobbled);
  11239. }
  11240. // then add things like ice and dtls from remote candidate
  11241. elem.each(function () {
  11242. for (var i = 0; i < self.remoteSDP.media.length; i++) {
  11243. if (SDPUtil.find_line(self.remoteSDP.media[i], 'a=mid:' + $(this).attr('name')) ||
  11244. self.remoteSDP.media[i].indexOf('m=' + $(this).attr('name')) === 0) {
  11245. if (!SDPUtil.find_line(self.remoteSDP.media[i], 'a=ice-ufrag:')) {
  11246. var tmp = $(this).find('transport');
  11247. self.remoteSDP.media[i] += 'a=ice-ufrag:' + tmp.attr('ufrag') + '\r\n';
  11248. self.remoteSDP.media[i] += 'a=ice-pwd:' + tmp.attr('pwd') + '\r\n';
  11249. tmp = $(this).find('transport>fingerprint');
  11250. if (tmp.length) {
  11251. self.remoteSDP.media[i] += 'a=fingerprint:' + tmp.attr('hash') + ' ' + tmp.text() + '\r\n';
  11252. } else {
  11253. console.log('no dtls fingerprint (webrtc issue #1718?)');
  11254. self.remoteSDP.media[i] += 'a=crypto:1 AES_CM_128_HMAC_SHA1_80 inline:BAADBAADBAADBAADBAADBAADBAADBAADBAADBAAD\r\n';
  11255. }
  11256. break;
  11257. }
  11258. }
  11259. }
  11260. });
  11261. this.remoteSDP.raw = this.remoteSDP.session + this.remoteSDP.media.join('');
  11262. // we need a complete SDP with ice-ufrag/ice-pwd in all parts
  11263. // this makes the assumption that the PRANSWER is constructed such that the ice-ufrag is in all mediaparts
  11264. // but it could be in the session part as well. since the code above constructs this sdp this can't happen however
  11265. var iscomplete = this.remoteSDP.media.filter(function (mediapart) {
  11266. return SDPUtil.find_line(mediapart, 'a=ice-ufrag:');
  11267. }).length == this.remoteSDP.media.length;
  11268. if (iscomplete) {
  11269. console.log('setting pranswer');
  11270. try {
  11271. this.peerconnection.setRemoteDescription(new RTCSessionDescription({type: 'pranswer', sdp: this.remoteSDP.raw }),
  11272. function() {
  11273. },
  11274. function(e) {
  11275. console.log('setRemoteDescription pranswer failed', e.toString());
  11276. });
  11277. } catch (e) {
  11278. console.error('setting pranswer failed', e);
  11279. }
  11280. } else {
  11281. //console.log('not yet setting pranswer');
  11282. }
  11283. }
  11284. // operate on each content element
  11285. elem.each(function () {
  11286. // would love to deactivate this, but firefox still requires it
  11287. var idx = -1;
  11288. var i;
  11289. for (i = 0; i < self.remoteSDP.media.length; i++) {
  11290. if (SDPUtil.find_line(self.remoteSDP.media[i], 'a=mid:' + $(this).attr('name')) ||
  11291. self.remoteSDP.media[i].indexOf('m=' + $(this).attr('name')) === 0) {
  11292. idx = i;
  11293. break;
  11294. }
  11295. }
  11296. if (idx == -1) { // fall back to localdescription
  11297. for (i = 0; i < self.localSDP.media.length; i++) {
  11298. if (SDPUtil.find_line(self.localSDP.media[i], 'a=mid:' + $(this).attr('name')) ||
  11299. self.localSDP.media[i].indexOf('m=' + $(this).attr('name')) === 0) {
  11300. idx = i;
  11301. break;
  11302. }
  11303. }
  11304. }
  11305. var name = $(this).attr('name');
  11306. // TODO: check ice-pwd and ice-ufrag?
  11307. $(this).find('transport>candidate').each(function () {
  11308. var line, candidate;
  11309. line = SDPUtil.candidateFromJingle(this);
  11310. candidate = new RTCIceCandidate({sdpMLineIndex: idx,
  11311. sdpMid: name,
  11312. candidate: line});
  11313. try {
  11314. self.peerconnection.addIceCandidate(candidate);
  11315. } catch (e) {
  11316. console.error('addIceCandidate failed', e.toString(), line);
  11317. }
  11318. });
  11319. });
  11320. };
  11321. JingleSession.prototype.sendAnswer = function (provisional) {
  11322. //console.log('createAnswer', provisional);
  11323. var self = this;
  11324. this.peerconnection.createAnswer(
  11325. function (sdp) {
  11326. self.createdAnswer(sdp, provisional);
  11327. },
  11328. function (e) {
  11329. console.error('createAnswer failed', e);
  11330. },
  11331. this.media_constraints
  11332. );
  11333. };
  11334. JingleSession.prototype.createdAnswer = function (sdp, provisional) {
  11335. //console.log('createAnswer callback');
  11336. var self = this;
  11337. this.localSDP = new SDP(sdp.sdp);
  11338. //this.localSDP.mangle();
  11339. this.usepranswer = provisional === true;
  11340. if (this.usetrickle) {
  11341. if (this.usepranswer) {
  11342. sdp.type = 'pranswer';
  11343. for (var i = 0; i < this.localSDP.media.length; i++) {
  11344. this.localSDP.media[i] = this.localSDP.media[i].replace('a=sendrecv\r\n', 'a=inactive\r\n');
  11345. }
  11346. this.localSDP.raw = this.localSDP.session + '\r\n' + this.localSDP.media.join('');
  11347. }
  11348. }
  11349. var self = this;
  11350. var sendJingle = function (ssrcs) {
  11351. var accept = $iq({to: self.peerjid,
  11352. type: 'set'})
  11353. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  11354. action: 'session-accept',
  11355. initiator: self.initiator,
  11356. responder: self.responder,
  11357. sid: self.sid });
  11358. var publicLocalDesc = APP.simulcast.reverseTransformLocalDescription(sdp);
  11359. var publicLocalSDP = new SDP(publicLocalDesc.sdp);
  11360. publicLocalSDP.toJingle(accept, self.initiator == self.me ? 'initiator' : 'responder', ssrcs);
  11361. self.connection.sendIQ(accept,
  11362. function () {
  11363. var ack = {};
  11364. ack.source = 'answer';
  11365. $(document).trigger('ack.jingle', [self.sid, ack]);
  11366. },
  11367. function (stanza) {
  11368. var error = ($(stanza).find('error').length) ? {
  11369. code: $(stanza).find('error').attr('code'),
  11370. reason: $(stanza).find('error :first')[0].tagName,
  11371. }:{};
  11372. error.source = 'answer';
  11373. JingleSession.onJingleError(self.sid, error);
  11374. },
  11375. 10000);
  11376. }
  11377. sdp.sdp = this.localSDP.raw;
  11378. this.peerconnection.setLocalDescription(sdp,
  11379. function () {
  11380. //console.log('setLocalDescription success');
  11381. if (self.usetrickle && !self.usepranswer) {
  11382. sendJingle();
  11383. }
  11384. self.setLocalDescription();
  11385. },
  11386. function (e) {
  11387. console.error('setLocalDescription failed', e);
  11388. }
  11389. );
  11390. var cands = SDPUtil.find_lines(this.localSDP.raw, 'a=candidate:');
  11391. for (var j = 0; j < cands.length; j++) {
  11392. var cand = SDPUtil.parse_icecandidate(cands[j]);
  11393. if (cand.type == 'srflx') {
  11394. this.hadstuncandidate = true;
  11395. } else if (cand.type == 'relay') {
  11396. this.hadturncandidate = true;
  11397. }
  11398. }
  11399. };
  11400. JingleSession.prototype.sendTerminate = function (reason, text) {
  11401. var self = this,
  11402. term = $iq({to: this.peerjid,
  11403. type: 'set'})
  11404. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  11405. action: 'session-terminate',
  11406. initiator: this.initiator,
  11407. sid: this.sid})
  11408. .c('reason')
  11409. .c(reason || 'success');
  11410. if (text) {
  11411. term.up().c('text').t(text);
  11412. }
  11413. this.connection.sendIQ(term,
  11414. function () {
  11415. self.peerconnection.close();
  11416. self.peerconnection = null;
  11417. self.terminate();
  11418. var ack = {};
  11419. ack.source = 'terminate';
  11420. $(document).trigger('ack.jingle', [self.sid, ack]);
  11421. },
  11422. function (stanza) {
  11423. var error = ($(stanza).find('error').length) ? {
  11424. code: $(stanza).find('error').attr('code'),
  11425. reason: $(stanza).find('error :first')[0].tagName,
  11426. }:{};
  11427. $(document).trigger('ack.jingle', [self.sid, error]);
  11428. },
  11429. 10000);
  11430. if (this.statsinterval !== null) {
  11431. window.clearInterval(this.statsinterval);
  11432. this.statsinterval = null;
  11433. }
  11434. };
  11435. JingleSession.prototype.addSource = function (elem, fromJid) {
  11436. var self = this;
  11437. // FIXME: dirty waiting
  11438. if (!this.peerconnection.localDescription)
  11439. {
  11440. console.warn("addSource - localDescription not ready yet")
  11441. setTimeout(function()
  11442. {
  11443. self.addSource(elem, fromJid);
  11444. },
  11445. 200
  11446. );
  11447. return;
  11448. }
  11449. console.log('addssrc', new Date().getTime());
  11450. console.log('ice', this.peerconnection.iceConnectionState);
  11451. var sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  11452. var mySdp = new SDP(this.peerconnection.localDescription.sdp);
  11453. $(elem).each(function (idx, content) {
  11454. var name = $(content).attr('name');
  11455. var lines = '';
  11456. $(content).find('ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]').each(function() {
  11457. var semantics = this.getAttribute('semantics');
  11458. var ssrcs = $(this).find('>source').map(function () {
  11459. return this.getAttribute('ssrc');
  11460. }).get();
  11461. if (ssrcs.length != 0) {
  11462. lines += 'a=ssrc-group:' + semantics + ' ' + ssrcs.join(' ') + '\r\n';
  11463. }
  11464. });
  11465. var tmp = $(content).find('source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]'); // can handle both >source and >description>source
  11466. tmp.each(function () {
  11467. var ssrc = $(this).attr('ssrc');
  11468. if(mySdp.containsSSRC(ssrc)){
  11469. /**
  11470. * This happens when multiple participants change their streams at the same time and
  11471. * ColibriFocus.modifySources have to wait for stable state. In the meantime multiple
  11472. * addssrc are scheduled for update IQ. See
  11473. */
  11474. console.warn("Got add stream request for my own ssrc: "+ssrc);
  11475. return;
  11476. }
  11477. $(this).find('>parameter').each(function () {
  11478. lines += 'a=ssrc:' + ssrc + ' ' + $(this).attr('name');
  11479. if ($(this).attr('value') && $(this).attr('value').length)
  11480. lines += ':' + $(this).attr('value');
  11481. lines += '\r\n';
  11482. });
  11483. });
  11484. sdp.media.forEach(function(media, idx) {
  11485. if (!SDPUtil.find_line(media, 'a=mid:' + name))
  11486. return;
  11487. sdp.media[idx] += lines;
  11488. if (!self.addssrc[idx]) self.addssrc[idx] = '';
  11489. self.addssrc[idx] += lines;
  11490. });
  11491. sdp.raw = sdp.session + sdp.media.join('');
  11492. });
  11493. this.modifySourcesQueue.push();
  11494. };
  11495. JingleSession.prototype.removeSource = function (elem, fromJid) {
  11496. var self = this;
  11497. // FIXME: dirty waiting
  11498. if (!this.peerconnection.localDescription)
  11499. {
  11500. console.warn("removeSource - localDescription not ready yet")
  11501. setTimeout(function()
  11502. {
  11503. self.removeSource(elem, fromJid);
  11504. },
  11505. 200
  11506. );
  11507. return;
  11508. }
  11509. console.log('removessrc', new Date().getTime());
  11510. console.log('ice', this.peerconnection.iceConnectionState);
  11511. var sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  11512. var mySdp = new SDP(this.peerconnection.localDescription.sdp);
  11513. $(elem).each(function (idx, content) {
  11514. var name = $(content).attr('name');
  11515. var lines = '';
  11516. $(content).find('ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]').each(function() {
  11517. var semantics = this.getAttribute('semantics');
  11518. var ssrcs = $(this).find('>source').map(function () {
  11519. return this.getAttribute('ssrc');
  11520. }).get();
  11521. if (ssrcs.length != 0) {
  11522. lines += 'a=ssrc-group:' + semantics + ' ' + ssrcs.join(' ') + '\r\n';
  11523. }
  11524. });
  11525. var tmp = $(content).find('source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]'); // can handle both >source and >description>source
  11526. tmp.each(function () {
  11527. var ssrc = $(this).attr('ssrc');
  11528. // This should never happen, but can be useful for bug detection
  11529. if(mySdp.containsSSRC(ssrc)){
  11530. console.error("Got remove stream request for my own ssrc: "+ssrc);
  11531. return;
  11532. }
  11533. $(this).find('>parameter').each(function () {
  11534. lines += 'a=ssrc:' + ssrc + ' ' + $(this).attr('name');
  11535. if ($(this).attr('value') && $(this).attr('value').length)
  11536. lines += ':' + $(this).attr('value');
  11537. lines += '\r\n';
  11538. });
  11539. });
  11540. sdp.media.forEach(function(media, idx) {
  11541. if (!SDPUtil.find_line(media, 'a=mid:' + name))
  11542. return;
  11543. sdp.media[idx] += lines;
  11544. if (!self.removessrc[idx]) self.removessrc[idx] = '';
  11545. self.removessrc[idx] += lines;
  11546. });
  11547. sdp.raw = sdp.session + sdp.media.join('');
  11548. });
  11549. this.modifySourcesQueue.push();
  11550. };
  11551. JingleSession.prototype._modifySources = function (successCallback, queueCallback) {
  11552. var self = this;
  11553. if (this.peerconnection.signalingState == 'closed') return;
  11554. if (!(this.addssrc.length || this.removessrc.length || this.pendingop !== null || this.switchstreams)){
  11555. // There is nothing to do since scheduled job might have been executed by another succeeding call
  11556. this.setLocalDescription();
  11557. if(successCallback){
  11558. successCallback();
  11559. }
  11560. queueCallback();
  11561. return;
  11562. }
  11563. // Reset switch streams flag
  11564. this.switchstreams = false;
  11565. var sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  11566. // add sources
  11567. this.addssrc.forEach(function(lines, idx) {
  11568. sdp.media[idx] += lines;
  11569. });
  11570. this.addssrc = [];
  11571. // remove sources
  11572. this.removessrc.forEach(function(lines, idx) {
  11573. lines = lines.split('\r\n');
  11574. lines.pop(); // remove empty last element;
  11575. lines.forEach(function(line) {
  11576. sdp.media[idx] = sdp.media[idx].replace(line + '\r\n', '');
  11577. });
  11578. });
  11579. this.removessrc = [];
  11580. // FIXME:
  11581. // this was a hack for the situation when only one peer exists
  11582. // in the conference.
  11583. // check if still required and remove
  11584. if (sdp.media[0])
  11585. sdp.media[0] = sdp.media[0].replace('a=recvonly', 'a=sendrecv');
  11586. if (sdp.media[1])
  11587. sdp.media[1] = sdp.media[1].replace('a=recvonly', 'a=sendrecv');
  11588. sdp.raw = sdp.session + sdp.media.join('');
  11589. this.peerconnection.setRemoteDescription(new RTCSessionDescription({type: 'offer', sdp: sdp.raw}),
  11590. function() {
  11591. if(self.signalingState == 'closed') {
  11592. console.error("createAnswer attempt on closed state");
  11593. queueCallback("createAnswer attempt on closed state");
  11594. return;
  11595. }
  11596. self.peerconnection.createAnswer(
  11597. function(modifiedAnswer) {
  11598. // change video direction, see https://github.com/jitsi/jitmeet/issues/41
  11599. if (self.pendingop !== null) {
  11600. var sdp = new SDP(modifiedAnswer.sdp);
  11601. if (sdp.media.length > 1) {
  11602. switch(self.pendingop) {
  11603. case 'mute':
  11604. sdp.media[1] = sdp.media[1].replace('a=sendrecv', 'a=recvonly');
  11605. break;
  11606. case 'unmute':
  11607. sdp.media[1] = sdp.media[1].replace('a=recvonly', 'a=sendrecv');
  11608. break;
  11609. }
  11610. sdp.raw = sdp.session + sdp.media.join('');
  11611. modifiedAnswer.sdp = sdp.raw;
  11612. }
  11613. self.pendingop = null;
  11614. }
  11615. // FIXME: pushing down an answer while ice connection state
  11616. // is still checking is bad...
  11617. //console.log(self.peerconnection.iceConnectionState);
  11618. // trying to work around another chrome bug
  11619. //modifiedAnswer.sdp = modifiedAnswer.sdp.replace(/a=setup:active/g, 'a=setup:actpass');
  11620. self.peerconnection.setLocalDescription(modifiedAnswer,
  11621. function() {
  11622. //console.log('modified setLocalDescription ok');
  11623. self.setLocalDescription();
  11624. if(successCallback){
  11625. successCallback();
  11626. }
  11627. queueCallback();
  11628. },
  11629. function(error) {
  11630. console.error('modified setLocalDescription failed', error);
  11631. queueCallback(error);
  11632. }
  11633. );
  11634. },
  11635. function(error) {
  11636. console.error('modified answer failed', error);
  11637. queueCallback(error);
  11638. }
  11639. );
  11640. },
  11641. function(error) {
  11642. console.error('modify failed', error);
  11643. queueCallback(error);
  11644. }
  11645. );
  11646. };
  11647. /**
  11648. * Switches video streams.
  11649. * @param new_stream new stream that will be used as video of this session.
  11650. * @param oldStream old video stream of this session.
  11651. * @param success_callback callback executed after successful stream switch.
  11652. */
  11653. JingleSession.prototype.switchStreams = function (new_stream, oldStream, success_callback) {
  11654. var self = this;
  11655. // Remember SDP to figure out added/removed SSRCs
  11656. var oldSdp = null;
  11657. if(self.peerconnection) {
  11658. if(self.peerconnection.localDescription) {
  11659. oldSdp = new SDP(self.peerconnection.localDescription.sdp);
  11660. }
  11661. self.peerconnection.removeStream(oldStream, true);
  11662. if(new_stream)
  11663. self.peerconnection.addStream(new_stream);
  11664. }
  11665. APP.RTC.switchVideoStreams(new_stream, oldStream);
  11666. // Conference is not active
  11667. if(!oldSdp || !self.peerconnection) {
  11668. success_callback();
  11669. return;
  11670. }
  11671. self.switchstreams = true;
  11672. self.modifySourcesQueue.push(function() {
  11673. console.log('modify sources done');
  11674. success_callback();
  11675. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  11676. console.log("SDPs", oldSdp, newSdp);
  11677. self.notifyMySSRCUpdate(oldSdp, newSdp);
  11678. });
  11679. };
  11680. /**
  11681. * Figures out added/removed ssrcs and send update IQs.
  11682. * @param old_sdp SDP object for old description.
  11683. * @param new_sdp SDP object for new description.
  11684. */
  11685. JingleSession.prototype.notifyMySSRCUpdate = function (old_sdp, new_sdp) {
  11686. if (!(this.peerconnection.signalingState == 'stable' &&
  11687. this.peerconnection.iceConnectionState == 'connected')){
  11688. console.log("Too early to send updates");
  11689. return;
  11690. }
  11691. // send source-remove IQ.
  11692. sdpDiffer = new SDPDiffer(new_sdp, old_sdp);
  11693. var remove = $iq({to: this.peerjid, type: 'set'})
  11694. .c('jingle', {
  11695. xmlns: 'urn:xmpp:jingle:1',
  11696. action: 'source-remove',
  11697. initiator: this.initiator,
  11698. sid: this.sid
  11699. }
  11700. );
  11701. var removed = sdpDiffer.toJingle(remove);
  11702. if (removed) {
  11703. this.connection.sendIQ(remove,
  11704. function (res) {
  11705. console.info('got remove result', res);
  11706. },
  11707. function (err) {
  11708. console.error('got remove error', err);
  11709. }
  11710. );
  11711. } else {
  11712. console.log('removal not necessary');
  11713. }
  11714. // send source-add IQ.
  11715. var sdpDiffer = new SDPDiffer(old_sdp, new_sdp);
  11716. var add = $iq({to: this.peerjid, type: 'set'})
  11717. .c('jingle', {
  11718. xmlns: 'urn:xmpp:jingle:1',
  11719. action: 'source-add',
  11720. initiator: this.initiator,
  11721. sid: this.sid
  11722. }
  11723. );
  11724. var added = sdpDiffer.toJingle(add);
  11725. if (added) {
  11726. this.connection.sendIQ(add,
  11727. function (res) {
  11728. console.info('got add result', res);
  11729. },
  11730. function (err) {
  11731. console.error('got add error', err);
  11732. }
  11733. );
  11734. } else {
  11735. console.log('addition not necessary');
  11736. }
  11737. };
  11738. /**
  11739. * Mutes/unmutes the (local) video i.e. enables/disables all video tracks.
  11740. *
  11741. * @param mute <tt>true</tt> to mute the (local) video i.e. to disable all video
  11742. * tracks; otherwise, <tt>false</tt>
  11743. * @param callback a function to be invoked with <tt>mute</tt> after all video
  11744. * tracks have been enabled/disabled. The function may, optionally, return
  11745. * another function which is to be invoked after the whole mute/unmute operation
  11746. * has completed successfully.
  11747. * @param options an object which specifies optional arguments such as the
  11748. * <tt>boolean</tt> key <tt>byUser</tt> with default value <tt>true</tt> which
  11749. * specifies whether the method was initiated in response to a user command (in
  11750. * contrast to an automatic decision made by the application logic)
  11751. */
  11752. JingleSession.prototype.setVideoMute = function (mute, callback, options) {
  11753. var byUser;
  11754. if (options) {
  11755. byUser = options.byUser;
  11756. if (typeof byUser === 'undefined') {
  11757. byUser = true;
  11758. }
  11759. } else {
  11760. byUser = true;
  11761. }
  11762. // The user's command to mute the (local) video takes precedence over any
  11763. // automatic decision made by the application logic.
  11764. if (byUser) {
  11765. this.videoMuteByUser = mute;
  11766. } else if (this.videoMuteByUser) {
  11767. return;
  11768. }
  11769. this.hardMuteVideo(mute);
  11770. this.modifySourcesQueue.push(callback(mute));
  11771. };
  11772. JingleSession.prototype.hardMuteVideo = function (muted) {
  11773. this.pendingop = muted ? 'mute' : 'unmute';
  11774. };
  11775. JingleSession.prototype.sendMute = function (muted, content) {
  11776. var info = $iq({to: this.peerjid,
  11777. type: 'set'})
  11778. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  11779. action: 'session-info',
  11780. initiator: this.initiator,
  11781. sid: this.sid });
  11782. info.c(muted ? 'mute' : 'unmute', {xmlns: 'urn:xmpp:jingle:apps:rtp:info:1'});
  11783. info.attrs({'creator': this.me == this.initiator ? 'creator' : 'responder'});
  11784. if (content) {
  11785. info.attrs({'name': content});
  11786. }
  11787. this.connection.send(info);
  11788. };
  11789. JingleSession.prototype.sendRinging = function () {
  11790. var info = $iq({to: this.peerjid,
  11791. type: 'set'})
  11792. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  11793. action: 'session-info',
  11794. initiator: this.initiator,
  11795. sid: this.sid });
  11796. info.c('ringing', {xmlns: 'urn:xmpp:jingle:apps:rtp:info:1'});
  11797. this.connection.send(info);
  11798. };
  11799. JingleSession.prototype.getStats = function (interval) {
  11800. var self = this;
  11801. var recv = {audio: 0, video: 0};
  11802. var lost = {audio: 0, video: 0};
  11803. var lastrecv = {audio: 0, video: 0};
  11804. var lastlost = {audio: 0, video: 0};
  11805. var loss = {audio: 0, video: 0};
  11806. var delta = {audio: 0, video: 0};
  11807. this.statsinterval = window.setInterval(function () {
  11808. if (self && self.peerconnection && self.peerconnection.getStats) {
  11809. self.peerconnection.getStats(function (stats) {
  11810. var results = stats.result();
  11811. // TODO: there are so much statistics you can get from this..
  11812. for (var i = 0; i < results.length; ++i) {
  11813. if (results[i].type == 'ssrc') {
  11814. var packetsrecv = results[i].stat('packetsReceived');
  11815. var packetslost = results[i].stat('packetsLost');
  11816. if (packetsrecv && packetslost) {
  11817. packetsrecv = parseInt(packetsrecv, 10);
  11818. packetslost = parseInt(packetslost, 10);
  11819. if (results[i].stat('googFrameRateReceived')) {
  11820. lastlost.video = lost.video;
  11821. lastrecv.video = recv.video;
  11822. recv.video = packetsrecv;
  11823. lost.video = packetslost;
  11824. } else {
  11825. lastlost.audio = lost.audio;
  11826. lastrecv.audio = recv.audio;
  11827. recv.audio = packetsrecv;
  11828. lost.audio = packetslost;
  11829. }
  11830. }
  11831. }
  11832. }
  11833. delta.audio = recv.audio - lastrecv.audio;
  11834. delta.video = recv.video - lastrecv.video;
  11835. loss.audio = (delta.audio > 0) ? Math.ceil(100 * (lost.audio - lastlost.audio) / delta.audio) : 0;
  11836. loss.video = (delta.video > 0) ? Math.ceil(100 * (lost.video - lastlost.video) / delta.video) : 0;
  11837. $(document).trigger('packetloss.jingle', [self.sid, loss]);
  11838. });
  11839. }
  11840. }, interval || 3000);
  11841. return this.statsinterval;
  11842. };
  11843. JingleSession.onJingleError = function (session, error)
  11844. {
  11845. console.error("Jingle error", error);
  11846. }
  11847. JingleSession.onJingleFatalError = function (session, error)
  11848. {
  11849. this.service.sessionTerminated = true;
  11850. this.connection.emuc.doLeave();
  11851. APP.UI.messageHandler.showError("dialog.sorry",
  11852. "dialog.internalError");
  11853. }
  11854. JingleSession.prototype.setLocalDescription = function () {
  11855. // put our ssrcs into presence so other clients can identify our stream
  11856. var newssrcs = [];
  11857. var media = APP.simulcast.parseMedia(this.peerconnection.localDescription);
  11858. media.forEach(function (media) {
  11859. if(Object.keys(media.sources).length > 0) {
  11860. // TODO(gp) maybe exclude FID streams?
  11861. Object.keys(media.sources).forEach(function (ssrc) {
  11862. newssrcs.push({
  11863. 'ssrc': ssrc,
  11864. 'type': media.type,
  11865. 'direction': media.direction
  11866. });
  11867. });
  11868. }
  11869. else if(this.localStreamsSSRC && this.localStreamsSSRC[media.type])
  11870. {
  11871. newssrcs.push({
  11872. 'ssrc': this.localStreamsSSRC[media.type],
  11873. 'type': media.type,
  11874. 'direction': media.direction
  11875. });
  11876. }
  11877. });
  11878. console.log('new ssrcs', newssrcs);
  11879. // Have to clear presence map to get rid of removed streams
  11880. this.connection.emuc.clearPresenceMedia();
  11881. if (newssrcs.length > 0) {
  11882. for (var i = 1; i <= newssrcs.length; i ++) {
  11883. // Change video type to screen
  11884. if (newssrcs[i-1].type === 'video' && APP.desktopsharing.isUsingScreenStream()) {
  11885. newssrcs[i-1].type = 'screen';
  11886. }
  11887. this.connection.emuc.addMediaToPresence(i,
  11888. newssrcs[i-1].type, newssrcs[i-1].ssrc, newssrcs[i-1].direction);
  11889. }
  11890. this.connection.emuc.sendPresence();
  11891. }
  11892. }
  11893. // an attempt to work around https://github.com/jitsi/jitmeet/issues/32
  11894. function sendKeyframe(pc) {
  11895. console.log('sendkeyframe', pc.iceConnectionState);
  11896. if (pc.iceConnectionState !== 'connected') return; // safe...
  11897. pc.setRemoteDescription(
  11898. pc.remoteDescription,
  11899. function () {
  11900. pc.createAnswer(
  11901. function (modifiedAnswer) {
  11902. pc.setLocalDescription(
  11903. modifiedAnswer,
  11904. function () {
  11905. // noop
  11906. },
  11907. function (error) {
  11908. console.log('triggerKeyframe setLocalDescription failed', error);
  11909. APP.UI.messageHandler.showError();
  11910. }
  11911. );
  11912. },
  11913. function (error) {
  11914. console.log('triggerKeyframe createAnswer failed', error);
  11915. APP.UI.messageHandler.showError();
  11916. }
  11917. );
  11918. },
  11919. function (error) {
  11920. console.log('triggerKeyframe setRemoteDescription failed', error);
  11921. APP.UI.messageHandler.showError();
  11922. }
  11923. );
  11924. }
  11925. JingleSession.prototype.remoteStreamAdded = function (data, times) {
  11926. var self = this;
  11927. var thessrc;
  11928. var ssrc2jid = this.connection.emuc.ssrc2jid;
  11929. // look up an associated JID for a stream id
  11930. if (data.stream.id && data.stream.id.indexOf('mixedmslabel') === -1) {
  11931. // look only at a=ssrc: and _not_ at a=ssrc-group: lines
  11932. var ssrclines
  11933. = SDPUtil.find_lines(this.peerconnection.remoteDescription.sdp, 'a=ssrc:');
  11934. ssrclines = ssrclines.filter(function (line) {
  11935. // NOTE(gp) previously we filtered on the mslabel, but that property
  11936. // is not always present.
  11937. // return line.indexOf('mslabel:' + data.stream.label) !== -1;
  11938. return ((line.indexOf('msid:' + data.stream.id) !== -1));
  11939. });
  11940. if (ssrclines.length) {
  11941. thessrc = ssrclines[0].substring(7).split(' ')[0];
  11942. // We signal our streams (through Jingle to the focus) before we set
  11943. // our presence (through which peers associate remote streams to
  11944. // jids). So, it might arrive that a remote stream is added but
  11945. // ssrc2jid is not yet updated and thus data.peerjid cannot be
  11946. // successfully set. Here we wait for up to a second for the
  11947. // presence to arrive.
  11948. if (!ssrc2jid[thessrc]) {
  11949. if (typeof times === 'undefined')
  11950. {
  11951. times = 0;
  11952. }
  11953. if (times > 10)
  11954. {
  11955. console.warning('Waiting for jid timed out', thessrc);
  11956. }
  11957. else
  11958. {
  11959. setTimeout(function(d) {
  11960. return function() {
  11961. self.remoteStreamAdded(d, times++);
  11962. }
  11963. }(data), 250);
  11964. }
  11965. return;
  11966. }
  11967. // ok to overwrite the one from focus? might save work in colibri.js
  11968. console.log('associated jid', ssrc2jid[thessrc], data.peerjid);
  11969. if (ssrc2jid[thessrc]) {
  11970. data.peerjid = ssrc2jid[thessrc];
  11971. }
  11972. }
  11973. }
  11974. APP.RTC.createRemoteStream(data, this.sid, thessrc);
  11975. var isVideo = data.stream.getVideoTracks().length > 0;
  11976. // an attempt to work around https://github.com/jitsi/jitmeet/issues/32
  11977. if (isVideo &&
  11978. data.peerjid && this.peerjid === data.peerjid &&
  11979. data.stream.getVideoTracks().length === 0 &&
  11980. APP.RTC.localVideo.getTracks().length > 0) {
  11981. window.setTimeout(function () {
  11982. sendKeyframe(self.peerconnection);
  11983. }, 3000);
  11984. }
  11985. }
  11986. module.exports = JingleSession;
  11987. },{"../../service/RTC/RTCBrowserType":91,"./SDP":51,"./SDPDiffer":52,"./SDPUtil":53,"./TraceablePeerConnection":54,"async":64}],51:[function(require,module,exports){
  11988. /* jshint -W117 */
  11989. var SDPUtil = require("./SDPUtil");
  11990. // SDP STUFF
  11991. function SDP(sdp) {
  11992. this.media = sdp.split('\r\nm=');
  11993. for (var i = 1; i < this.media.length; i++) {
  11994. this.media[i] = 'm=' + this.media[i];
  11995. if (i != this.media.length - 1) {
  11996. this.media[i] += '\r\n';
  11997. }
  11998. }
  11999. this.session = this.media.shift() + '\r\n';
  12000. this.raw = this.session + this.media.join('');
  12001. }
  12002. /**
  12003. * Returns map of MediaChannel mapped per channel idx.
  12004. */
  12005. SDP.prototype.getMediaSsrcMap = function() {
  12006. var self = this;
  12007. var media_ssrcs = {};
  12008. var tmp;
  12009. for (var mediaindex = 0; mediaindex < self.media.length; mediaindex++) {
  12010. tmp = SDPUtil.find_lines(self.media[mediaindex], 'a=ssrc:');
  12011. var mid = SDPUtil.parse_mid(SDPUtil.find_line(self.media[mediaindex], 'a=mid:'));
  12012. var media = {
  12013. mediaindex: mediaindex,
  12014. mid: mid,
  12015. ssrcs: {},
  12016. ssrcGroups: []
  12017. };
  12018. media_ssrcs[mediaindex] = media;
  12019. tmp.forEach(function (line) {
  12020. var linessrc = line.substring(7).split(' ')[0];
  12021. // allocate new ChannelSsrc
  12022. if(!media.ssrcs[linessrc]) {
  12023. media.ssrcs[linessrc] = {
  12024. ssrc: linessrc,
  12025. lines: []
  12026. };
  12027. }
  12028. media.ssrcs[linessrc].lines.push(line);
  12029. });
  12030. tmp = SDPUtil.find_lines(self.media[mediaindex], 'a=ssrc-group:');
  12031. tmp.forEach(function(line){
  12032. var semantics = line.substr(0, idx).substr(13);
  12033. var ssrcs = line.substr(14 + semantics.length).split(' ');
  12034. if (ssrcs.length != 0) {
  12035. media.ssrcGroups.push({
  12036. semantics: semantics,
  12037. ssrcs: ssrcs
  12038. });
  12039. }
  12040. });
  12041. }
  12042. return media_ssrcs;
  12043. };
  12044. /**
  12045. * Returns <tt>true</tt> if this SDP contains given SSRC.
  12046. * @param ssrc the ssrc to check.
  12047. * @returns {boolean} <tt>true</tt> if this SDP contains given SSRC.
  12048. */
  12049. SDP.prototype.containsSSRC = function(ssrc) {
  12050. var medias = this.getMediaSsrcMap();
  12051. var contains = false;
  12052. Object.keys(medias).forEach(function(mediaindex){
  12053. var media = medias[mediaindex];
  12054. //console.log("Check", channel, ssrc);
  12055. if(Object.keys(media.ssrcs).indexOf(ssrc) != -1){
  12056. contains = true;
  12057. }
  12058. });
  12059. return contains;
  12060. };
  12061. // remove iSAC and CN from SDP
  12062. SDP.prototype.mangle = function () {
  12063. var i, j, mline, lines, rtpmap, newdesc;
  12064. for (i = 0; i < this.media.length; i++) {
  12065. lines = this.media[i].split('\r\n');
  12066. lines.pop(); // remove empty last element
  12067. mline = SDPUtil.parse_mline(lines.shift());
  12068. if (mline.media != 'audio')
  12069. continue;
  12070. newdesc = '';
  12071. mline.fmt.length = 0;
  12072. for (j = 0; j < lines.length; j++) {
  12073. if (lines[j].substr(0, 9) == 'a=rtpmap:') {
  12074. rtpmap = SDPUtil.parse_rtpmap(lines[j]);
  12075. if (rtpmap.name == 'CN' || rtpmap.name == 'ISAC')
  12076. continue;
  12077. mline.fmt.push(rtpmap.id);
  12078. newdesc += lines[j] + '\r\n';
  12079. } else {
  12080. newdesc += lines[j] + '\r\n';
  12081. }
  12082. }
  12083. this.media[i] = SDPUtil.build_mline(mline) + '\r\n';
  12084. this.media[i] += newdesc;
  12085. }
  12086. this.raw = this.session + this.media.join('');
  12087. };
  12088. // remove lines matching prefix from session section
  12089. SDP.prototype.removeSessionLines = function(prefix) {
  12090. var self = this;
  12091. var lines = SDPUtil.find_lines(this.session, prefix);
  12092. lines.forEach(function(line) {
  12093. self.session = self.session.replace(line + '\r\n', '');
  12094. });
  12095. this.raw = this.session + this.media.join('');
  12096. return lines;
  12097. }
  12098. // remove lines matching prefix from a media section specified by mediaindex
  12099. // TODO: non-numeric mediaindex could match mid
  12100. SDP.prototype.removeMediaLines = function(mediaindex, prefix) {
  12101. var self = this;
  12102. var lines = SDPUtil.find_lines(this.media[mediaindex], prefix);
  12103. lines.forEach(function(line) {
  12104. self.media[mediaindex] = self.media[mediaindex].replace(line + '\r\n', '');
  12105. });
  12106. this.raw = this.session + this.media.join('');
  12107. return lines;
  12108. }
  12109. // add content's to a jingle element
  12110. SDP.prototype.toJingle = function (elem, thecreator, ssrcs) {
  12111. // console.log("SSRC" + ssrcs["audio"] + " - " + ssrcs["video"]);
  12112. var i, j, k, mline, ssrc, rtpmap, tmp, line, lines;
  12113. var self = this;
  12114. // new bundle plan
  12115. if (SDPUtil.find_line(this.session, 'a=group:')) {
  12116. lines = SDPUtil.find_lines(this.session, 'a=group:');
  12117. for (i = 0; i < lines.length; i++) {
  12118. tmp = lines[i].split(' ');
  12119. var semantics = tmp.shift().substr(8);
  12120. elem.c('group', {xmlns: 'urn:xmpp:jingle:apps:grouping:0', semantics:semantics});
  12121. for (j = 0; j < tmp.length; j++) {
  12122. elem.c('content', {name: tmp[j]}).up();
  12123. }
  12124. elem.up();
  12125. }
  12126. }
  12127. for (i = 0; i < this.media.length; i++) {
  12128. mline = SDPUtil.parse_mline(this.media[i].split('\r\n')[0]);
  12129. if (!(mline.media === 'audio' ||
  12130. mline.media === 'video' ||
  12131. mline.media === 'application'))
  12132. {
  12133. continue;
  12134. }
  12135. if (SDPUtil.find_line(this.media[i], 'a=ssrc:')) {
  12136. ssrc = SDPUtil.find_line(this.media[i], 'a=ssrc:').substring(7).split(' ')[0]; // take the first
  12137. } else {
  12138. if(ssrcs && ssrcs[mline.media])
  12139. {
  12140. ssrc = ssrcs[mline.media];
  12141. }
  12142. else
  12143. ssrc = false;
  12144. }
  12145. elem.c('content', {creator: thecreator, name: mline.media});
  12146. if (SDPUtil.find_line(this.media[i], 'a=mid:')) {
  12147. // prefer identifier from a=mid if present
  12148. var mid = SDPUtil.parse_mid(SDPUtil.find_line(this.media[i], 'a=mid:'));
  12149. elem.attrs({ name: mid });
  12150. }
  12151. if (SDPUtil.find_line(this.media[i], 'a=rtpmap:').length)
  12152. {
  12153. elem.c('description',
  12154. {xmlns: 'urn:xmpp:jingle:apps:rtp:1',
  12155. media: mline.media });
  12156. if (ssrc) {
  12157. elem.attrs({ssrc: ssrc});
  12158. }
  12159. for (j = 0; j < mline.fmt.length; j++) {
  12160. rtpmap = SDPUtil.find_line(this.media[i], 'a=rtpmap:' + mline.fmt[j]);
  12161. elem.c('payload-type', SDPUtil.parse_rtpmap(rtpmap));
  12162. // put any 'a=fmtp:' + mline.fmt[j] lines into <param name=foo value=bar/>
  12163. if (SDPUtil.find_line(this.media[i], 'a=fmtp:' + mline.fmt[j])) {
  12164. tmp = SDPUtil.parse_fmtp(SDPUtil.find_line(this.media[i], 'a=fmtp:' + mline.fmt[j]));
  12165. for (k = 0; k < tmp.length; k++) {
  12166. elem.c('parameter', tmp[k]).up();
  12167. }
  12168. }
  12169. this.RtcpFbToJingle(i, elem, mline.fmt[j]); // XEP-0293 -- map a=rtcp-fb
  12170. elem.up();
  12171. }
  12172. if (SDPUtil.find_line(this.media[i], 'a=crypto:', this.session)) {
  12173. elem.c('encryption', {required: 1});
  12174. var crypto = SDPUtil.find_lines(this.media[i], 'a=crypto:', this.session);
  12175. crypto.forEach(function(line) {
  12176. elem.c('crypto', SDPUtil.parse_crypto(line)).up();
  12177. });
  12178. elem.up(); // end of encryption
  12179. }
  12180. if (ssrc) {
  12181. // new style mapping
  12182. elem.c('source', { ssrc: ssrc, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  12183. // FIXME: group by ssrc and support multiple different ssrcs
  12184. var ssrclines = SDPUtil.find_lines(this.media[i], 'a=ssrc:');
  12185. if(ssrclines.length > 0) {
  12186. ssrclines.forEach(function (line) {
  12187. idx = line.indexOf(' ');
  12188. var linessrc = line.substr(0, idx).substr(7);
  12189. if (linessrc != ssrc) {
  12190. elem.up();
  12191. ssrc = linessrc;
  12192. elem.c('source', { ssrc: ssrc, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  12193. }
  12194. var kv = line.substr(idx + 1);
  12195. elem.c('parameter');
  12196. if (kv.indexOf(':') == -1) {
  12197. elem.attrs({ name: kv });
  12198. } else {
  12199. elem.attrs({ name: kv.split(':', 2)[0] });
  12200. elem.attrs({ value: kv.split(':', 2)[1] });
  12201. }
  12202. elem.up();
  12203. });
  12204. elem.up();
  12205. }
  12206. else
  12207. {
  12208. elem.up();
  12209. elem.c('source', { ssrc: ssrc, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  12210. elem.c('parameter');
  12211. elem.attrs({name: "cname", value:Math.random().toString(36).substring(7)});
  12212. elem.up();
  12213. var msid = null;
  12214. if(mline.media == "audio")
  12215. {
  12216. msid = APP.RTC.localAudio.getId();
  12217. }
  12218. else
  12219. {
  12220. msid = APP.RTC.localVideo.getId();
  12221. }
  12222. if(msid != null)
  12223. {
  12224. msid = msid.replace(/[\{,\}]/g,"");
  12225. elem.c('parameter');
  12226. elem.attrs({name: "msid", value:msid});
  12227. elem.up();
  12228. elem.c('parameter');
  12229. elem.attrs({name: "mslabel", value:msid});
  12230. elem.up();
  12231. elem.c('parameter');
  12232. elem.attrs({name: "label", value:msid});
  12233. elem.up();
  12234. elem.up();
  12235. }
  12236. }
  12237. // XEP-0339 handle ssrc-group attributes
  12238. var ssrc_group_lines = SDPUtil.find_lines(this.media[i], 'a=ssrc-group:');
  12239. ssrc_group_lines.forEach(function(line) {
  12240. idx = line.indexOf(' ');
  12241. var semantics = line.substr(0, idx).substr(13);
  12242. var ssrcs = line.substr(14 + semantics.length).split(' ');
  12243. if (ssrcs.length != 0) {
  12244. elem.c('ssrc-group', { semantics: semantics, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  12245. ssrcs.forEach(function(ssrc) {
  12246. elem.c('source', { ssrc: ssrc })
  12247. .up();
  12248. });
  12249. elem.up();
  12250. }
  12251. });
  12252. }
  12253. if (SDPUtil.find_line(this.media[i], 'a=rtcp-mux')) {
  12254. elem.c('rtcp-mux').up();
  12255. }
  12256. // XEP-0293 -- map a=rtcp-fb:*
  12257. this.RtcpFbToJingle(i, elem, '*');
  12258. // XEP-0294
  12259. if (SDPUtil.find_line(this.media[i], 'a=extmap:')) {
  12260. lines = SDPUtil.find_lines(this.media[i], 'a=extmap:');
  12261. for (j = 0; j < lines.length; j++) {
  12262. tmp = SDPUtil.parse_extmap(lines[j]);
  12263. elem.c('rtp-hdrext', { xmlns: 'urn:xmpp:jingle:apps:rtp:rtp-hdrext:0',
  12264. uri: tmp.uri,
  12265. id: tmp.value });
  12266. if (tmp.hasOwnProperty('direction')) {
  12267. switch (tmp.direction) {
  12268. case 'sendonly':
  12269. elem.attrs({senders: 'responder'});
  12270. break;
  12271. case 'recvonly':
  12272. elem.attrs({senders: 'initiator'});
  12273. break;
  12274. case 'sendrecv':
  12275. elem.attrs({senders: 'both'});
  12276. break;
  12277. case 'inactive':
  12278. elem.attrs({senders: 'none'});
  12279. break;
  12280. }
  12281. }
  12282. // TODO: handle params
  12283. elem.up();
  12284. }
  12285. }
  12286. elem.up(); // end of description
  12287. }
  12288. // map ice-ufrag/pwd, dtls fingerprint, candidates
  12289. this.TransportToJingle(i, elem);
  12290. if (SDPUtil.find_line(this.media[i], 'a=sendrecv', this.session)) {
  12291. elem.attrs({senders: 'both'});
  12292. } else if (SDPUtil.find_line(this.media[i], 'a=sendonly', this.session)) {
  12293. elem.attrs({senders: 'initiator'});
  12294. } else if (SDPUtil.find_line(this.media[i], 'a=recvonly', this.session)) {
  12295. elem.attrs({senders: 'responder'});
  12296. } else if (SDPUtil.find_line(this.media[i], 'a=inactive', this.session)) {
  12297. elem.attrs({senders: 'none'});
  12298. }
  12299. if (mline.port == '0') {
  12300. // estos hack to reject an m-line
  12301. elem.attrs({senders: 'rejected'});
  12302. }
  12303. elem.up(); // end of content
  12304. }
  12305. elem.up();
  12306. return elem;
  12307. };
  12308. SDP.prototype.TransportToJingle = function (mediaindex, elem) {
  12309. var i = mediaindex;
  12310. var tmp;
  12311. var self = this;
  12312. elem.c('transport');
  12313. // XEP-0343 DTLS/SCTP
  12314. if (SDPUtil.find_line(this.media[mediaindex], 'a=sctpmap:').length)
  12315. {
  12316. var sctpmap = SDPUtil.find_line(
  12317. this.media[i], 'a=sctpmap:', self.session);
  12318. if (sctpmap)
  12319. {
  12320. var sctpAttrs = SDPUtil.parse_sctpmap(sctpmap);
  12321. elem.c('sctpmap',
  12322. {
  12323. xmlns: 'urn:xmpp:jingle:transports:dtls-sctp:1',
  12324. number: sctpAttrs[0], /* SCTP port */
  12325. protocol: sctpAttrs[1], /* protocol */
  12326. });
  12327. // Optional stream count attribute
  12328. if (sctpAttrs.length > 2)
  12329. elem.attrs({ streams: sctpAttrs[2]});
  12330. elem.up();
  12331. }
  12332. }
  12333. // XEP-0320
  12334. var fingerprints = SDPUtil.find_lines(this.media[mediaindex], 'a=fingerprint:', this.session);
  12335. fingerprints.forEach(function(line) {
  12336. tmp = SDPUtil.parse_fingerprint(line);
  12337. tmp.xmlns = 'urn:xmpp:jingle:apps:dtls:0';
  12338. elem.c('fingerprint').t(tmp.fingerprint);
  12339. delete tmp.fingerprint;
  12340. line = SDPUtil.find_line(self.media[mediaindex], 'a=setup:', self.session);
  12341. if (line) {
  12342. tmp.setup = line.substr(8);
  12343. }
  12344. elem.attrs(tmp);
  12345. elem.up(); // end of fingerprint
  12346. });
  12347. tmp = SDPUtil.iceparams(this.media[mediaindex], this.session);
  12348. if (tmp) {
  12349. tmp.xmlns = 'urn:xmpp:jingle:transports:ice-udp:1';
  12350. elem.attrs(tmp);
  12351. // XEP-0176
  12352. if (SDPUtil.find_line(this.media[mediaindex], 'a=candidate:', this.session)) { // add any a=candidate lines
  12353. var lines = SDPUtil.find_lines(this.media[mediaindex], 'a=candidate:', this.session);
  12354. lines.forEach(function (line) {
  12355. elem.c('candidate', SDPUtil.candidateToJingle(line)).up();
  12356. });
  12357. }
  12358. }
  12359. elem.up(); // end of transport
  12360. }
  12361. SDP.prototype.RtcpFbToJingle = function (mediaindex, elem, payloadtype) { // XEP-0293
  12362. var lines = SDPUtil.find_lines(this.media[mediaindex], 'a=rtcp-fb:' + payloadtype);
  12363. lines.forEach(function (line) {
  12364. var tmp = SDPUtil.parse_rtcpfb(line);
  12365. if (tmp.type == 'trr-int') {
  12366. elem.c('rtcp-fb-trr-int', {xmlns: 'urn:xmpp:jingle:apps:rtp:rtcp-fb:0', value: tmp.params[0]});
  12367. elem.up();
  12368. } else {
  12369. elem.c('rtcp-fb', {xmlns: 'urn:xmpp:jingle:apps:rtp:rtcp-fb:0', type: tmp.type});
  12370. if (tmp.params.length > 0) {
  12371. elem.attrs({'subtype': tmp.params[0]});
  12372. }
  12373. elem.up();
  12374. }
  12375. });
  12376. };
  12377. SDP.prototype.RtcpFbFromJingle = function (elem, payloadtype) { // XEP-0293
  12378. var media = '';
  12379. var tmp = elem.find('>rtcp-fb-trr-int[xmlns="urn:xmpp:jingle:apps:rtp:rtcp-fb:0"]');
  12380. if (tmp.length) {
  12381. media += 'a=rtcp-fb:' + '*' + ' ' + 'trr-int' + ' ';
  12382. if (tmp.attr('value')) {
  12383. media += tmp.attr('value');
  12384. } else {
  12385. media += '0';
  12386. }
  12387. media += '\r\n';
  12388. }
  12389. tmp = elem.find('>rtcp-fb[xmlns="urn:xmpp:jingle:apps:rtp:rtcp-fb:0"]');
  12390. tmp.each(function () {
  12391. media += 'a=rtcp-fb:' + payloadtype + ' ' + $(this).attr('type');
  12392. if ($(this).attr('subtype')) {
  12393. media += ' ' + $(this).attr('subtype');
  12394. }
  12395. media += '\r\n';
  12396. });
  12397. return media;
  12398. };
  12399. // construct an SDP from a jingle stanza
  12400. SDP.prototype.fromJingle = function (jingle) {
  12401. var self = this;
  12402. this.raw = 'v=0\r\n' +
  12403. 'o=- ' + '1923518516' + ' 2 IN IP4 0.0.0.0\r\n' +// FIXME
  12404. 's=-\r\n' +
  12405. 't=0 0\r\n';
  12406. // http://tools.ietf.org/html/draft-ietf-mmusic-sdp-bundle-negotiation-04#section-8
  12407. if ($(jingle).find('>group[xmlns="urn:xmpp:jingle:apps:grouping:0"]').length) {
  12408. $(jingle).find('>group[xmlns="urn:xmpp:jingle:apps:grouping:0"]').each(function (idx, group) {
  12409. var contents = $(group).find('>content').map(function (idx, content) {
  12410. return content.getAttribute('name');
  12411. }).get();
  12412. if (contents.length > 0) {
  12413. self.raw += 'a=group:' + (group.getAttribute('semantics') || group.getAttribute('type')) + ' ' + contents.join(' ') + '\r\n';
  12414. }
  12415. });
  12416. }
  12417. this.session = this.raw;
  12418. jingle.find('>content').each(function () {
  12419. var m = self.jingle2media($(this));
  12420. self.media.push(m);
  12421. });
  12422. // reconstruct msid-semantic -- apparently not necessary
  12423. /*
  12424. var msid = SDPUtil.parse_ssrc(this.raw);
  12425. if (msid.hasOwnProperty('mslabel')) {
  12426. this.session += "a=msid-semantic: WMS " + msid.mslabel + "\r\n";
  12427. }
  12428. */
  12429. this.raw = this.session + this.media.join('');
  12430. };
  12431. // translate a jingle content element into an an SDP media part
  12432. SDP.prototype.jingle2media = function (content) {
  12433. var media = '',
  12434. desc = content.find('description'),
  12435. ssrc = desc.attr('ssrc'),
  12436. self = this,
  12437. tmp;
  12438. var sctp = content.find(
  12439. '>transport>sctpmap[xmlns="urn:xmpp:jingle:transports:dtls-sctp:1"]');
  12440. tmp = { media: desc.attr('media') };
  12441. tmp.port = '1';
  12442. if (content.attr('senders') == 'rejected') {
  12443. // estos hack to reject an m-line.
  12444. tmp.port = '0';
  12445. }
  12446. if (content.find('>transport>fingerprint').length || desc.find('encryption').length) {
  12447. if (sctp.length)
  12448. tmp.proto = 'DTLS/SCTP';
  12449. else
  12450. tmp.proto = 'RTP/SAVPF';
  12451. } else {
  12452. tmp.proto = 'RTP/AVPF';
  12453. }
  12454. if (!sctp.length)
  12455. {
  12456. tmp.fmt = desc.find('payload-type').map(
  12457. function () { return this.getAttribute('id'); }).get();
  12458. media += SDPUtil.build_mline(tmp) + '\r\n';
  12459. }
  12460. else
  12461. {
  12462. media += 'm=application 1 DTLS/SCTP ' + sctp.attr('number') + '\r\n';
  12463. media += 'a=sctpmap:' + sctp.attr('number') +
  12464. ' ' + sctp.attr('protocol');
  12465. var streamCount = sctp.attr('streams');
  12466. if (streamCount)
  12467. media += ' ' + streamCount + '\r\n';
  12468. else
  12469. media += '\r\n';
  12470. }
  12471. media += 'c=IN IP4 0.0.0.0\r\n';
  12472. if (!sctp.length)
  12473. media += 'a=rtcp:1 IN IP4 0.0.0.0\r\n';
  12474. tmp = content.find('>transport[xmlns="urn:xmpp:jingle:transports:ice-udp:1"]');
  12475. if (tmp.length) {
  12476. if (tmp.attr('ufrag')) {
  12477. media += SDPUtil.build_iceufrag(tmp.attr('ufrag')) + '\r\n';
  12478. }
  12479. if (tmp.attr('pwd')) {
  12480. media += SDPUtil.build_icepwd(tmp.attr('pwd')) + '\r\n';
  12481. }
  12482. tmp.find('>fingerprint').each(function () {
  12483. // FIXME: check namespace at some point
  12484. media += 'a=fingerprint:' + this.getAttribute('hash');
  12485. media += ' ' + $(this).text();
  12486. media += '\r\n';
  12487. if (this.getAttribute('setup')) {
  12488. media += 'a=setup:' + this.getAttribute('setup') + '\r\n';
  12489. }
  12490. });
  12491. }
  12492. switch (content.attr('senders')) {
  12493. case 'initiator':
  12494. media += 'a=sendonly\r\n';
  12495. break;
  12496. case 'responder':
  12497. media += 'a=recvonly\r\n';
  12498. break;
  12499. case 'none':
  12500. media += 'a=inactive\r\n';
  12501. break;
  12502. case 'both':
  12503. media += 'a=sendrecv\r\n';
  12504. break;
  12505. }
  12506. media += 'a=mid:' + content.attr('name') + '\r\n';
  12507. // <description><rtcp-mux/></description>
  12508. // see http://code.google.com/p/libjingle/issues/detail?id=309 -- no spec though
  12509. // and http://mail.jabber.org/pipermail/jingle/2011-December/001761.html
  12510. if (desc.find('rtcp-mux').length) {
  12511. media += 'a=rtcp-mux\r\n';
  12512. }
  12513. if (desc.find('encryption').length) {
  12514. desc.find('encryption>crypto').each(function () {
  12515. media += 'a=crypto:' + this.getAttribute('tag');
  12516. media += ' ' + this.getAttribute('crypto-suite');
  12517. media += ' ' + this.getAttribute('key-params');
  12518. if (this.getAttribute('session-params')) {
  12519. media += ' ' + this.getAttribute('session-params');
  12520. }
  12521. media += '\r\n';
  12522. });
  12523. }
  12524. desc.find('payload-type').each(function () {
  12525. media += SDPUtil.build_rtpmap(this) + '\r\n';
  12526. if ($(this).find('>parameter').length) {
  12527. media += 'a=fmtp:' + this.getAttribute('id') + ' ';
  12528. media += $(this).find('parameter').map(function () { return (this.getAttribute('name') ? (this.getAttribute('name') + '=') : '') + this.getAttribute('value'); }).get().join('; ');
  12529. media += '\r\n';
  12530. }
  12531. // xep-0293
  12532. media += self.RtcpFbFromJingle($(this), this.getAttribute('id'));
  12533. });
  12534. // xep-0293
  12535. media += self.RtcpFbFromJingle(desc, '*');
  12536. // xep-0294
  12537. tmp = desc.find('>rtp-hdrext[xmlns="urn:xmpp:jingle:apps:rtp:rtp-hdrext:0"]');
  12538. tmp.each(function () {
  12539. media += 'a=extmap:' + this.getAttribute('id') + ' ' + this.getAttribute('uri') + '\r\n';
  12540. });
  12541. content.find('>transport[xmlns="urn:xmpp:jingle:transports:ice-udp:1"]>candidate').each(function () {
  12542. media += SDPUtil.candidateFromJingle(this);
  12543. });
  12544. // XEP-0339 handle ssrc-group attributes
  12545. tmp = content.find('description>ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]').each(function() {
  12546. var semantics = this.getAttribute('semantics');
  12547. var ssrcs = $(this).find('>source').map(function() {
  12548. return this.getAttribute('ssrc');
  12549. }).get();
  12550. if (ssrcs.length != 0) {
  12551. media += 'a=ssrc-group:' + semantics + ' ' + ssrcs.join(' ') + '\r\n';
  12552. }
  12553. });
  12554. tmp = content.find('description>source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]');
  12555. tmp.each(function () {
  12556. var ssrc = this.getAttribute('ssrc');
  12557. $(this).find('>parameter').each(function () {
  12558. media += 'a=ssrc:' + ssrc + ' ' + this.getAttribute('name');
  12559. if (this.getAttribute('value') && this.getAttribute('value').length)
  12560. media += ':' + this.getAttribute('value');
  12561. media += '\r\n';
  12562. });
  12563. });
  12564. return media;
  12565. };
  12566. module.exports = SDP;
  12567. },{"./SDPUtil":53}],52:[function(require,module,exports){
  12568. function SDPDiffer(mySDP, otherSDP) {
  12569. this.mySDP = mySDP;
  12570. this.otherSDP = otherSDP;
  12571. }
  12572. /**
  12573. * Returns map of MediaChannel that contains only media not contained in <tt>otherSdp</tt>. Mapped by channel idx.
  12574. * @param otherSdp the other SDP to check ssrc with.
  12575. */
  12576. SDPDiffer.prototype.getNewMedia = function() {
  12577. // this could be useful in Array.prototype.
  12578. function arrayEquals(array) {
  12579. // if the other array is a falsy value, return
  12580. if (!array)
  12581. return false;
  12582. // compare lengths - can save a lot of time
  12583. if (this.length != array.length)
  12584. return false;
  12585. for (var i = 0, l=this.length; i < l; i++) {
  12586. // Check if we have nested arrays
  12587. if (this[i] instanceof Array && array[i] instanceof Array) {
  12588. // recurse into the nested arrays
  12589. if (!this[i].equals(array[i]))
  12590. return false;
  12591. }
  12592. else if (this[i] != array[i]) {
  12593. // Warning - two different object instances will never be equal: {x:20} != {x:20}
  12594. return false;
  12595. }
  12596. }
  12597. return true;
  12598. }
  12599. var myMedias = this.mySDP.getMediaSsrcMap();
  12600. var othersMedias = this.otherSDP.getMediaSsrcMap();
  12601. var newMedia = {};
  12602. Object.keys(othersMedias).forEach(function(othersMediaIdx) {
  12603. var myMedia = myMedias[othersMediaIdx];
  12604. var othersMedia = othersMedias[othersMediaIdx];
  12605. if(!myMedia && othersMedia) {
  12606. // Add whole channel
  12607. newMedia[othersMediaIdx] = othersMedia;
  12608. return;
  12609. }
  12610. // Look for new ssrcs accross the channel
  12611. Object.keys(othersMedia.ssrcs).forEach(function(ssrc) {
  12612. if(Object.keys(myMedia.ssrcs).indexOf(ssrc) === -1) {
  12613. // Allocate channel if we've found ssrc that doesn't exist in our channel
  12614. if(!newMedia[othersMediaIdx]){
  12615. newMedia[othersMediaIdx] = {
  12616. mediaindex: othersMedia.mediaindex,
  12617. mid: othersMedia.mid,
  12618. ssrcs: {},
  12619. ssrcGroups: []
  12620. };
  12621. }
  12622. newMedia[othersMediaIdx].ssrcs[ssrc] = othersMedia.ssrcs[ssrc];
  12623. }
  12624. });
  12625. // Look for new ssrc groups across the channels
  12626. othersMedia.ssrcGroups.forEach(function(otherSsrcGroup){
  12627. // try to match the other ssrc-group with an ssrc-group of ours
  12628. var matched = false;
  12629. for (var i = 0; i < myMedia.ssrcGroups.length; i++) {
  12630. var mySsrcGroup = myMedia.ssrcGroups[i];
  12631. if (otherSsrcGroup.semantics == mySsrcGroup.semantics
  12632. && arrayEquals.apply(otherSsrcGroup.ssrcs, [mySsrcGroup.ssrcs])) {
  12633. matched = true;
  12634. break;
  12635. }
  12636. }
  12637. if (!matched) {
  12638. // Allocate channel if we've found an ssrc-group that doesn't
  12639. // exist in our channel
  12640. if(!newMedia[othersMediaIdx]){
  12641. newMedia[othersMediaIdx] = {
  12642. mediaindex: othersMedia.mediaindex,
  12643. mid: othersMedia.mid,
  12644. ssrcs: {},
  12645. ssrcGroups: []
  12646. };
  12647. }
  12648. newMedia[othersMediaIdx].ssrcGroups.push(otherSsrcGroup);
  12649. }
  12650. });
  12651. });
  12652. return newMedia;
  12653. };
  12654. /**
  12655. * Sends SSRC update IQ.
  12656. * @param sdpMediaSsrcs SSRCs map obtained from SDP.getNewMedia. Cntains SSRCs to add/remove.
  12657. * @param sid session identifier that will be put into the IQ.
  12658. * @param initiator initiator identifier.
  12659. * @param toJid destination Jid
  12660. * @param isAdd indicates if this is remove or add operation.
  12661. */
  12662. SDPDiffer.prototype.toJingle = function(modify) {
  12663. var sdpMediaSsrcs = this.getNewMedia();
  12664. var self = this;
  12665. // FIXME: only announce video ssrcs since we mix audio and dont need
  12666. // the audio ssrcs therefore
  12667. var modified = false;
  12668. Object.keys(sdpMediaSsrcs).forEach(function(mediaindex){
  12669. modified = true;
  12670. var media = sdpMediaSsrcs[mediaindex];
  12671. modify.c('content', {name: media.mid});
  12672. modify.c('description', {xmlns:'urn:xmpp:jingle:apps:rtp:1', media: media.mid});
  12673. // FIXME: not completly sure this operates on blocks and / or handles different ssrcs correctly
  12674. // generate sources from lines
  12675. Object.keys(media.ssrcs).forEach(function(ssrcNum) {
  12676. var mediaSsrc = media.ssrcs[ssrcNum];
  12677. modify.c('source', { xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  12678. modify.attrs({ssrc: mediaSsrc.ssrc});
  12679. // iterate over ssrc lines
  12680. mediaSsrc.lines.forEach(function (line) {
  12681. var idx = line.indexOf(' ');
  12682. var kv = line.substr(idx + 1);
  12683. modify.c('parameter');
  12684. if (kv.indexOf(':') == -1) {
  12685. modify.attrs({ name: kv });
  12686. } else {
  12687. modify.attrs({ name: kv.split(':', 2)[0] });
  12688. modify.attrs({ value: kv.split(':', 2)[1] });
  12689. }
  12690. modify.up(); // end of parameter
  12691. });
  12692. modify.up(); // end of source
  12693. });
  12694. // generate source groups from lines
  12695. media.ssrcGroups.forEach(function(ssrcGroup) {
  12696. if (ssrcGroup.ssrcs.length != 0) {
  12697. modify.c('ssrc-group', {
  12698. semantics: ssrcGroup.semantics,
  12699. xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0'
  12700. });
  12701. ssrcGroup.ssrcs.forEach(function (ssrc) {
  12702. modify.c('source', { ssrc: ssrc })
  12703. .up(); // end of source
  12704. });
  12705. modify.up(); // end of ssrc-group
  12706. }
  12707. });
  12708. modify.up(); // end of description
  12709. modify.up(); // end of content
  12710. });
  12711. return modified;
  12712. };
  12713. module.exports = SDPDiffer;
  12714. },{}],53:[function(require,module,exports){
  12715. SDPUtil = {
  12716. iceparams: function (mediadesc, sessiondesc) {
  12717. var data = null;
  12718. if (SDPUtil.find_line(mediadesc, 'a=ice-ufrag:', sessiondesc) &&
  12719. SDPUtil.find_line(mediadesc, 'a=ice-pwd:', sessiondesc)) {
  12720. data = {
  12721. ufrag: SDPUtil.parse_iceufrag(SDPUtil.find_line(mediadesc, 'a=ice-ufrag:', sessiondesc)),
  12722. pwd: SDPUtil.parse_icepwd(SDPUtil.find_line(mediadesc, 'a=ice-pwd:', sessiondesc))
  12723. };
  12724. }
  12725. return data;
  12726. },
  12727. parse_iceufrag: function (line) {
  12728. return line.substring(12);
  12729. },
  12730. build_iceufrag: function (frag) {
  12731. return 'a=ice-ufrag:' + frag;
  12732. },
  12733. parse_icepwd: function (line) {
  12734. return line.substring(10);
  12735. },
  12736. build_icepwd: function (pwd) {
  12737. return 'a=ice-pwd:' + pwd;
  12738. },
  12739. parse_mid: function (line) {
  12740. return line.substring(6);
  12741. },
  12742. parse_mline: function (line) {
  12743. var parts = line.substring(2).split(' '),
  12744. data = {};
  12745. data.media = parts.shift();
  12746. data.port = parts.shift();
  12747. data.proto = parts.shift();
  12748. if (parts[parts.length - 1] === '') { // trailing whitespace
  12749. parts.pop();
  12750. }
  12751. data.fmt = parts;
  12752. return data;
  12753. },
  12754. build_mline: function (mline) {
  12755. return 'm=' + mline.media + ' ' + mline.port + ' ' + mline.proto + ' ' + mline.fmt.join(' ');
  12756. },
  12757. parse_rtpmap: function (line) {
  12758. var parts = line.substring(9).split(' '),
  12759. data = {};
  12760. data.id = parts.shift();
  12761. parts = parts[0].split('/');
  12762. data.name = parts.shift();
  12763. data.clockrate = parts.shift();
  12764. data.channels = parts.length ? parts.shift() : '1';
  12765. return data;
  12766. },
  12767. /**
  12768. * Parses SDP line "a=sctpmap:..." and extracts SCTP port from it.
  12769. * @param line eg. "a=sctpmap:5000 webrtc-datachannel"
  12770. * @returns [SCTP port number, protocol, streams]
  12771. */
  12772. parse_sctpmap: function (line)
  12773. {
  12774. var parts = line.substring(10).split(' ');
  12775. var sctpPort = parts[0];
  12776. var protocol = parts[1];
  12777. // Stream count is optional
  12778. var streamCount = parts.length > 2 ? parts[2] : null;
  12779. return [sctpPort, protocol, streamCount];// SCTP port
  12780. },
  12781. build_rtpmap: function (el) {
  12782. var line = 'a=rtpmap:' + el.getAttribute('id') + ' ' + el.getAttribute('name') + '/' + el.getAttribute('clockrate');
  12783. if (el.getAttribute('channels') && el.getAttribute('channels') != '1') {
  12784. line += '/' + el.getAttribute('channels');
  12785. }
  12786. return line;
  12787. },
  12788. parse_crypto: function (line) {
  12789. var parts = line.substring(9).split(' '),
  12790. data = {};
  12791. data.tag = parts.shift();
  12792. data['crypto-suite'] = parts.shift();
  12793. data['key-params'] = parts.shift();
  12794. if (parts.length) {
  12795. data['session-params'] = parts.join(' ');
  12796. }
  12797. return data;
  12798. },
  12799. parse_fingerprint: function (line) { // RFC 4572
  12800. var parts = line.substring(14).split(' '),
  12801. data = {};
  12802. data.hash = parts.shift();
  12803. data.fingerprint = parts.shift();
  12804. // TODO assert that fingerprint satisfies 2UHEX *(":" 2UHEX) ?
  12805. return data;
  12806. },
  12807. parse_fmtp: function (line) {
  12808. var parts = line.split(' '),
  12809. i, key, value,
  12810. data = [];
  12811. parts.shift();
  12812. parts = parts.join(' ').split(';');
  12813. for (i = 0; i < parts.length; i++) {
  12814. key = parts[i].split('=')[0];
  12815. while (key.length && key[0] == ' ') {
  12816. key = key.substring(1);
  12817. }
  12818. value = parts[i].split('=')[1];
  12819. if (key && value) {
  12820. data.push({name: key, value: value});
  12821. } else if (key) {
  12822. // rfc 4733 (DTMF) style stuff
  12823. data.push({name: '', value: key});
  12824. }
  12825. }
  12826. return data;
  12827. },
  12828. parse_icecandidate: function (line) {
  12829. var candidate = {},
  12830. elems = line.split(' ');
  12831. candidate.foundation = elems[0].substring(12);
  12832. candidate.component = elems[1];
  12833. candidate.protocol = elems[2].toLowerCase();
  12834. candidate.priority = elems[3];
  12835. candidate.ip = elems[4];
  12836. candidate.port = elems[5];
  12837. // elems[6] => "typ"
  12838. candidate.type = elems[7];
  12839. candidate.generation = 0; // default value, may be overwritten below
  12840. for (var i = 8; i < elems.length; i += 2) {
  12841. switch (elems[i]) {
  12842. case 'raddr':
  12843. candidate['rel-addr'] = elems[i + 1];
  12844. break;
  12845. case 'rport':
  12846. candidate['rel-port'] = elems[i + 1];
  12847. break;
  12848. case 'generation':
  12849. candidate.generation = elems[i + 1];
  12850. break;
  12851. case 'tcptype':
  12852. candidate.tcptype = elems[i + 1];
  12853. break;
  12854. default: // TODO
  12855. console.log('parse_icecandidate not translating "' + elems[i] + '" = "' + elems[i + 1] + '"');
  12856. }
  12857. }
  12858. candidate.network = '1';
  12859. candidate.id = Math.random().toString(36).substr(2, 10); // not applicable to SDP -- FIXME: should be unique, not just random
  12860. return candidate;
  12861. },
  12862. build_icecandidate: function (cand) {
  12863. var line = ['a=candidate:' + cand.foundation, cand.component, cand.protocol, cand.priority, cand.ip, cand.port, 'typ', cand.type].join(' ');
  12864. line += ' ';
  12865. switch (cand.type) {
  12866. case 'srflx':
  12867. case 'prflx':
  12868. case 'relay':
  12869. if (cand.hasOwnAttribute('rel-addr') && cand.hasOwnAttribute('rel-port')) {
  12870. line += 'raddr';
  12871. line += ' ';
  12872. line += cand['rel-addr'];
  12873. line += ' ';
  12874. line += 'rport';
  12875. line += ' ';
  12876. line += cand['rel-port'];
  12877. line += ' ';
  12878. }
  12879. break;
  12880. }
  12881. if (cand.hasOwnAttribute('tcptype')) {
  12882. line += 'tcptype';
  12883. line += ' ';
  12884. line += cand.tcptype;
  12885. line += ' ';
  12886. }
  12887. line += 'generation';
  12888. line += ' ';
  12889. line += cand.hasOwnAttribute('generation') ? cand.generation : '0';
  12890. return line;
  12891. },
  12892. parse_ssrc: function (desc) {
  12893. // proprietary mapping of a=ssrc lines
  12894. // TODO: see "Jingle RTP Source Description" by Juberti and P. Thatcher on google docs
  12895. // and parse according to that
  12896. var lines = desc.split('\r\n'),
  12897. data = {};
  12898. for (var i = 0; i < lines.length; i++) {
  12899. if (lines[i].substring(0, 7) == 'a=ssrc:') {
  12900. var idx = lines[i].indexOf(' ');
  12901. data[lines[i].substr(idx + 1).split(':', 2)[0]] = lines[i].substr(idx + 1).split(':', 2)[1];
  12902. }
  12903. }
  12904. return data;
  12905. },
  12906. parse_rtcpfb: function (line) {
  12907. var parts = line.substr(10).split(' ');
  12908. var data = {};
  12909. data.pt = parts.shift();
  12910. data.type = parts.shift();
  12911. data.params = parts;
  12912. return data;
  12913. },
  12914. parse_extmap: function (line) {
  12915. var parts = line.substr(9).split(' ');
  12916. var data = {};
  12917. data.value = parts.shift();
  12918. if (data.value.indexOf('/') != -1) {
  12919. data.direction = data.value.substr(data.value.indexOf('/') + 1);
  12920. data.value = data.value.substr(0, data.value.indexOf('/'));
  12921. } else {
  12922. data.direction = 'both';
  12923. }
  12924. data.uri = parts.shift();
  12925. data.params = parts;
  12926. return data;
  12927. },
  12928. find_line: function (haystack, needle, sessionpart) {
  12929. var lines = haystack.split('\r\n');
  12930. for (var i = 0; i < lines.length; i++) {
  12931. if (lines[i].substring(0, needle.length) == needle) {
  12932. return lines[i];
  12933. }
  12934. }
  12935. if (!sessionpart) {
  12936. return false;
  12937. }
  12938. // search session part
  12939. lines = sessionpart.split('\r\n');
  12940. for (var j = 0; j < lines.length; j++) {
  12941. if (lines[j].substring(0, needle.length) == needle) {
  12942. return lines[j];
  12943. }
  12944. }
  12945. return false;
  12946. },
  12947. find_lines: function (haystack, needle, sessionpart) {
  12948. var lines = haystack.split('\r\n'),
  12949. needles = [];
  12950. for (var i = 0; i < lines.length; i++) {
  12951. if (lines[i].substring(0, needle.length) == needle)
  12952. needles.push(lines[i]);
  12953. }
  12954. if (needles.length || !sessionpart) {
  12955. return needles;
  12956. }
  12957. // search session part
  12958. lines = sessionpart.split('\r\n');
  12959. for (var j = 0; j < lines.length; j++) {
  12960. if (lines[j].substring(0, needle.length) == needle) {
  12961. needles.push(lines[j]);
  12962. }
  12963. }
  12964. return needles;
  12965. },
  12966. candidateToJingle: function (line) {
  12967. // a=candidate:2979166662 1 udp 2113937151 192.168.2.100 57698 typ host generation 0
  12968. // <candidate component=... foundation=... generation=... id=... ip=... network=... port=... priority=... protocol=... type=.../>
  12969. if (line.indexOf('candidate:') === 0) {
  12970. line = 'a=' + line;
  12971. } else if (line.substring(0, 12) != 'a=candidate:') {
  12972. console.log('parseCandidate called with a line that is not a candidate line');
  12973. console.log(line);
  12974. return null;
  12975. }
  12976. if (line.substring(line.length - 2) == '\r\n') // chomp it
  12977. line = line.substring(0, line.length - 2);
  12978. var candidate = {},
  12979. elems = line.split(' '),
  12980. i;
  12981. if (elems[6] != 'typ') {
  12982. console.log('did not find typ in the right place');
  12983. console.log(line);
  12984. return null;
  12985. }
  12986. candidate.foundation = elems[0].substring(12);
  12987. candidate.component = elems[1];
  12988. candidate.protocol = elems[2].toLowerCase();
  12989. candidate.priority = elems[3];
  12990. candidate.ip = elems[4];
  12991. candidate.port = elems[5];
  12992. // elems[6] => "typ"
  12993. candidate.type = elems[7];
  12994. candidate.generation = '0'; // default, may be overwritten below
  12995. for (i = 8; i < elems.length; i += 2) {
  12996. switch (elems[i]) {
  12997. case 'raddr':
  12998. candidate['rel-addr'] = elems[i + 1];
  12999. break;
  13000. case 'rport':
  13001. candidate['rel-port'] = elems[i + 1];
  13002. break;
  13003. case 'generation':
  13004. candidate.generation = elems[i + 1];
  13005. break;
  13006. case 'tcptype':
  13007. candidate.tcptype = elems[i + 1];
  13008. break;
  13009. default: // TODO
  13010. console.log('not translating "' + elems[i] + '" = "' + elems[i + 1] + '"');
  13011. }
  13012. }
  13013. candidate.network = '1';
  13014. candidate.id = Math.random().toString(36).substr(2, 10); // not applicable to SDP -- FIXME: should be unique, not just random
  13015. return candidate;
  13016. },
  13017. candidateFromJingle: function (cand) {
  13018. var line = 'a=candidate:';
  13019. line += cand.getAttribute('foundation');
  13020. line += ' ';
  13021. line += cand.getAttribute('component');
  13022. line += ' ';
  13023. line += cand.getAttribute('protocol'); //.toUpperCase(); // chrome M23 doesn't like this
  13024. line += ' ';
  13025. line += cand.getAttribute('priority');
  13026. line += ' ';
  13027. line += cand.getAttribute('ip');
  13028. line += ' ';
  13029. line += cand.getAttribute('port');
  13030. line += ' ';
  13031. line += 'typ';
  13032. line += ' ' + cand.getAttribute('type');
  13033. line += ' ';
  13034. switch (cand.getAttribute('type')) {
  13035. case 'srflx':
  13036. case 'prflx':
  13037. case 'relay':
  13038. if (cand.getAttribute('rel-addr') && cand.getAttribute('rel-port')) {
  13039. line += 'raddr';
  13040. line += ' ';
  13041. line += cand.getAttribute('rel-addr');
  13042. line += ' ';
  13043. line += 'rport';
  13044. line += ' ';
  13045. line += cand.getAttribute('rel-port');
  13046. line += ' ';
  13047. }
  13048. break;
  13049. }
  13050. if (cand.getAttribute('protocol').toLowerCase() == 'tcp') {
  13051. line += 'tcptype';
  13052. line += ' ';
  13053. line += cand.getAttribute('tcptype');
  13054. line += ' ';
  13055. }
  13056. line += 'generation';
  13057. line += ' ';
  13058. line += cand.getAttribute('generation') || '0';
  13059. return line + '\r\n';
  13060. }
  13061. };
  13062. module.exports = SDPUtil;
  13063. },{}],54:[function(require,module,exports){
  13064. function TraceablePeerConnection(ice_config, constraints) {
  13065. var self = this;
  13066. var RTCPeerconnection = navigator.mozGetUserMedia ? mozRTCPeerConnection : webkitRTCPeerConnection;
  13067. this.peerconnection = new RTCPeerconnection(ice_config, constraints);
  13068. this.updateLog = [];
  13069. this.stats = {};
  13070. this.statsinterval = null;
  13071. this.maxstats = 0; // limit to 300 values, i.e. 5 minutes; set to 0 to disable
  13072. var Interop = require('sdp-interop').Interop;
  13073. this.interop = new Interop();
  13074. // override as desired
  13075. this.trace = function (what, info) {
  13076. //console.warn('WTRACE', what, info);
  13077. self.updateLog.push({
  13078. time: new Date(),
  13079. type: what,
  13080. value: info || ""
  13081. });
  13082. };
  13083. this.onicecandidate = null;
  13084. this.peerconnection.onicecandidate = function (event) {
  13085. self.trace('onicecandidate', JSON.stringify(event.candidate, null, ' '));
  13086. if (self.onicecandidate !== null) {
  13087. self.onicecandidate(event);
  13088. }
  13089. };
  13090. this.onaddstream = null;
  13091. this.peerconnection.onaddstream = function (event) {
  13092. self.trace('onaddstream', event.stream.id);
  13093. if (self.onaddstream !== null) {
  13094. self.onaddstream(event);
  13095. }
  13096. };
  13097. this.onremovestream = null;
  13098. this.peerconnection.onremovestream = function (event) {
  13099. self.trace('onremovestream', event.stream.id);
  13100. if (self.onremovestream !== null) {
  13101. self.onremovestream(event);
  13102. }
  13103. };
  13104. this.onsignalingstatechange = null;
  13105. this.peerconnection.onsignalingstatechange = function (event) {
  13106. self.trace('onsignalingstatechange', self.signalingState);
  13107. if (self.onsignalingstatechange !== null) {
  13108. self.onsignalingstatechange(event);
  13109. }
  13110. };
  13111. this.oniceconnectionstatechange = null;
  13112. this.peerconnection.oniceconnectionstatechange = function (event) {
  13113. self.trace('oniceconnectionstatechange', self.iceConnectionState);
  13114. if (self.oniceconnectionstatechange !== null) {
  13115. self.oniceconnectionstatechange(event);
  13116. }
  13117. };
  13118. this.onnegotiationneeded = null;
  13119. this.peerconnection.onnegotiationneeded = function (event) {
  13120. self.trace('onnegotiationneeded');
  13121. if (self.onnegotiationneeded !== null) {
  13122. self.onnegotiationneeded(event);
  13123. }
  13124. };
  13125. self.ondatachannel = null;
  13126. this.peerconnection.ondatachannel = function (event) {
  13127. self.trace('ondatachannel', event);
  13128. if (self.ondatachannel !== null) {
  13129. self.ondatachannel(event);
  13130. }
  13131. };
  13132. if (!navigator.mozGetUserMedia && this.maxstats) {
  13133. this.statsinterval = window.setInterval(function() {
  13134. self.peerconnection.getStats(function(stats) {
  13135. var results = stats.result();
  13136. for (var i = 0; i < results.length; ++i) {
  13137. //console.log(results[i].type, results[i].id, results[i].names())
  13138. var now = new Date();
  13139. results[i].names().forEach(function (name) {
  13140. var id = results[i].id + '-' + name;
  13141. if (!self.stats[id]) {
  13142. self.stats[id] = {
  13143. startTime: now,
  13144. endTime: now,
  13145. values: [],
  13146. times: []
  13147. };
  13148. }
  13149. self.stats[id].values.push(results[i].stat(name));
  13150. self.stats[id].times.push(now.getTime());
  13151. if (self.stats[id].values.length > self.maxstats) {
  13152. self.stats[id].values.shift();
  13153. self.stats[id].times.shift();
  13154. }
  13155. self.stats[id].endTime = now;
  13156. });
  13157. }
  13158. });
  13159. }, 1000);
  13160. }
  13161. };
  13162. dumpSDP = function(description) {
  13163. if (typeof description === 'undefined' || description == null) {
  13164. return '';
  13165. }
  13166. return 'type: ' + description.type + '\r\n' + description.sdp;
  13167. };
  13168. if (TraceablePeerConnection.prototype.__defineGetter__ !== undefined) {
  13169. TraceablePeerConnection.prototype.__defineGetter__('signalingState', function() { return this.peerconnection.signalingState; });
  13170. TraceablePeerConnection.prototype.__defineGetter__('iceConnectionState', function() { return this.peerconnection.iceConnectionState; });
  13171. TraceablePeerConnection.prototype.__defineGetter__('localDescription', function() {
  13172. this.trace('getLocalDescription::preTransform (Plan A)', dumpSDP(this.peerconnection.localDescription));
  13173. // if we're running on FF, transform to Plan B first.
  13174. var desc = this.peerconnection.localDescription;
  13175. if (navigator.mozGetUserMedia) {
  13176. desc = this.interop.toPlanB(desc);
  13177. } else {
  13178. desc = APP.simulcast.reverseTransformLocalDescription(this.peerconnection.localDescription);
  13179. }
  13180. this.trace('getLocalDescription::postTransform (Plan B)', dumpSDP(desc));
  13181. return desc;
  13182. });
  13183. TraceablePeerConnection.prototype.__defineGetter__('remoteDescription', function() {
  13184. this.trace('getRemoteDescription::preTransform (Plan A)', dumpSDP(this.peerconnection.remoteDescription));
  13185. // if we're running on FF, transform to Plan B first.
  13186. var desc = this.peerconnection.remoteDescription;
  13187. if (navigator.mozGetUserMedia) {
  13188. desc = this.interop.toPlanB(desc);
  13189. } else {
  13190. desc = APP.simulcast.reverseTransformRemoteDescription(this.peerconnection.remoteDescription);
  13191. }
  13192. this.trace('getRemoteDescription::postTransform (Plan B)', dumpSDP(desc));
  13193. return desc;
  13194. });
  13195. }
  13196. TraceablePeerConnection.prototype.addStream = function (stream) {
  13197. this.trace('addStream', stream.id);
  13198. APP.simulcast.resetSender();
  13199. try
  13200. {
  13201. this.peerconnection.addStream(stream);
  13202. }
  13203. catch (e)
  13204. {
  13205. console.error(e);
  13206. return;
  13207. }
  13208. };
  13209. TraceablePeerConnection.prototype.removeStream = function (stream, stopStreams) {
  13210. this.trace('removeStream', stream.id);
  13211. APP.simulcast.resetSender();
  13212. if(stopStreams) {
  13213. stream.getAudioTracks().forEach(function (track) {
  13214. track.stop();
  13215. });
  13216. stream.getVideoTracks().forEach(function (track) {
  13217. track.stop();
  13218. });
  13219. }
  13220. try {
  13221. // FF doesn't support this yet.
  13222. this.peerconnection.removeStream(stream);
  13223. } catch (e) {
  13224. console.error(e);
  13225. }
  13226. };
  13227. TraceablePeerConnection.prototype.createDataChannel = function (label, opts) {
  13228. this.trace('createDataChannel', label, opts);
  13229. return this.peerconnection.createDataChannel(label, opts);
  13230. };
  13231. TraceablePeerConnection.prototype.setLocalDescription = function (description, successCallback, failureCallback) {
  13232. this.trace('setLocalDescription::preTransform (Plan B)', dumpSDP(description));
  13233. // if we're running on FF, transform to Plan A first.
  13234. if (navigator.mozGetUserMedia) {
  13235. description = this.interop.toPlanA(description);
  13236. } else {
  13237. description = APP.simulcast.transformLocalDescription(description);
  13238. }
  13239. this.trace('setLocalDescription::postTransform (Plan A)', dumpSDP(description));
  13240. var self = this;
  13241. this.peerconnection.setLocalDescription(description,
  13242. function () {
  13243. self.trace('setLocalDescriptionOnSuccess');
  13244. successCallback();
  13245. },
  13246. function (err) {
  13247. self.trace('setLocalDescriptionOnFailure', err);
  13248. failureCallback(err);
  13249. }
  13250. );
  13251. /*
  13252. if (this.statsinterval === null && this.maxstats > 0) {
  13253. // start gathering stats
  13254. }
  13255. */
  13256. };
  13257. TraceablePeerConnection.prototype.setRemoteDescription = function (description, successCallback, failureCallback) {
  13258. this.trace('setRemoteDescription::preTransform (Plan B)', dumpSDP(description));
  13259. // if we're running on FF, transform to Plan A first.
  13260. if (navigator.mozGetUserMedia) {
  13261. description = this.interop.toPlanA(description);
  13262. }
  13263. else {
  13264. description = APP.simulcast.transformRemoteDescription(description);
  13265. }
  13266. this.trace('setRemoteDescription::postTransform (Plan A)', dumpSDP(description));
  13267. var self = this;
  13268. this.peerconnection.setRemoteDescription(description,
  13269. function () {
  13270. self.trace('setRemoteDescriptionOnSuccess');
  13271. successCallback();
  13272. },
  13273. function (err) {
  13274. self.trace('setRemoteDescriptionOnFailure', err);
  13275. failureCallback(err);
  13276. }
  13277. );
  13278. /*
  13279. if (this.statsinterval === null && this.maxstats > 0) {
  13280. // start gathering stats
  13281. }
  13282. */
  13283. };
  13284. TraceablePeerConnection.prototype.close = function () {
  13285. this.trace('stop');
  13286. if (this.statsinterval !== null) {
  13287. window.clearInterval(this.statsinterval);
  13288. this.statsinterval = null;
  13289. }
  13290. this.peerconnection.close();
  13291. };
  13292. TraceablePeerConnection.prototype.createOffer = function (successCallback, failureCallback, constraints) {
  13293. var self = this;
  13294. this.trace('createOffer', JSON.stringify(constraints, null, ' '));
  13295. this.peerconnection.createOffer(
  13296. function (offer) {
  13297. self.trace('createOfferOnSuccess::preTransform (Plan A)', dumpSDP(offer));
  13298. // if we're running on FF, transform to Plan B first.
  13299. if (navigator.mozGetUserMedia) {
  13300. offer = self.interop.toPlanB(offer);
  13301. }
  13302. self.trace('createOfferOnSuccess::postTransform (Plan B)', dumpSDP(offer));
  13303. successCallback(offer);
  13304. },
  13305. function(err) {
  13306. self.trace('createOfferOnFailure', err);
  13307. failureCallback(err);
  13308. },
  13309. constraints
  13310. );
  13311. };
  13312. TraceablePeerConnection.prototype.createAnswer = function (successCallback, failureCallback, constraints) {
  13313. var self = this;
  13314. this.trace('createAnswer', JSON.stringify(constraints, null, ' '));
  13315. this.peerconnection.createAnswer(
  13316. function (answer) {
  13317. self.trace('createAnswerOnSuccess::preTransfom (Plan A)', dumpSDP(answer));
  13318. // if we're running on FF, transform to Plan A first.
  13319. if (navigator.mozGetUserMedia) {
  13320. answer = self.interop.toPlanB(answer);
  13321. } else {
  13322. answer = APP.simulcast.transformAnswer(answer);
  13323. }
  13324. self.trace('createAnswerOnSuccess::postTransfom (Plan B)', dumpSDP(answer));
  13325. successCallback(answer);
  13326. },
  13327. function(err) {
  13328. self.trace('createAnswerOnFailure', err);
  13329. failureCallback(err);
  13330. },
  13331. constraints
  13332. );
  13333. };
  13334. TraceablePeerConnection.prototype.addIceCandidate = function (candidate, successCallback, failureCallback) {
  13335. var self = this;
  13336. this.trace('addIceCandidate', JSON.stringify(candidate, null, ' '));
  13337. this.peerconnection.addIceCandidate(candidate);
  13338. /* maybe later
  13339. this.peerconnection.addIceCandidate(candidate,
  13340. function () {
  13341. self.trace('addIceCandidateOnSuccess');
  13342. successCallback();
  13343. },
  13344. function (err) {
  13345. self.trace('addIceCandidateOnFailure', err);
  13346. failureCallback(err);
  13347. }
  13348. );
  13349. */
  13350. };
  13351. TraceablePeerConnection.prototype.getStats = function(callback, errback) {
  13352. if (navigator.mozGetUserMedia) {
  13353. // ignore for now...
  13354. if(!errback)
  13355. errback = function () {
  13356. }
  13357. this.peerconnection.getStats(null,callback,errback);
  13358. } else {
  13359. this.peerconnection.getStats(callback);
  13360. }
  13361. };
  13362. module.exports = TraceablePeerConnection;
  13363. },{"sdp-interop":83}],55:[function(require,module,exports){
  13364. /* global $, $iq, APP, config, connection, UI, messageHandler,
  13365. roomName, sessionTerminated, Strophe, Util */
  13366. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  13367. var Settings = require("../settings/Settings");
  13368. var AuthenticationEvents
  13369. = require("../../service/authentication/AuthenticationEvents");
  13370. /**
  13371. * Contains logic responsible for enabling/disabling functionality available
  13372. * only to moderator users.
  13373. */
  13374. var connection = null;
  13375. var focusUserJid;
  13376. function createExpBackoffTimer(step) {
  13377. var count = 1;
  13378. return function (reset) {
  13379. // Reset call
  13380. if (reset) {
  13381. count = 1;
  13382. return;
  13383. }
  13384. // Calculate next timeout
  13385. var timeout = Math.pow(2, count - 1);
  13386. count += 1;
  13387. return timeout * step;
  13388. };
  13389. }
  13390. var getNextTimeout = createExpBackoffTimer(1000);
  13391. var getNextErrorTimeout = createExpBackoffTimer(1000);
  13392. // External authentication stuff
  13393. var externalAuthEnabled = false;
  13394. // Sip gateway can be enabled by configuring Jigasi host in config.js or
  13395. // it will be enabled automatically if focus detects the component through
  13396. // service discovery.
  13397. var sipGatewayEnabled = config.hosts.call_control !== undefined;
  13398. var eventEmitter = null;
  13399. var Moderator = {
  13400. isModerator: function () {
  13401. return connection && connection.emuc.isModerator();
  13402. },
  13403. isPeerModerator: function (peerJid) {
  13404. return connection &&
  13405. connection.emuc.getMemberRole(peerJid) === 'moderator';
  13406. },
  13407. isExternalAuthEnabled: function () {
  13408. return externalAuthEnabled;
  13409. },
  13410. isSipGatewayEnabled: function () {
  13411. return sipGatewayEnabled;
  13412. },
  13413. setConnection: function (con) {
  13414. connection = con;
  13415. },
  13416. init: function (xmpp, emitter) {
  13417. this.xmppService = xmpp;
  13418. eventEmitter = emitter;
  13419. // Message listener that talks to POPUP window
  13420. function listener(event) {
  13421. if (event.data && event.data.sessionId) {
  13422. if (event.origin !== window.location.origin) {
  13423. console.warn(
  13424. "Ignoring sessionId from different origin: " + event.origin);
  13425. return;
  13426. }
  13427. localStorage.setItem('sessionId', event.data.sessionId);
  13428. // After popup is closed we will authenticate
  13429. }
  13430. }
  13431. // Register
  13432. if (window.addEventListener) {
  13433. window.addEventListener("message", listener, false);
  13434. } else {
  13435. window.attachEvent("onmessage", listener);
  13436. }
  13437. },
  13438. onMucMemberLeft: function (jid) {
  13439. console.info("Someone left is it focus ? " + jid);
  13440. var resource = Strophe.getResourceFromJid(jid);
  13441. if (resource === 'focus' && !this.xmppService.sessionTerminated) {
  13442. console.info(
  13443. "Focus has left the room - leaving conference");
  13444. //hangUp();
  13445. // We'd rather reload to have everything re-initialized
  13446. // FIXME: show some message before reload
  13447. location.reload();
  13448. }
  13449. },
  13450. setFocusUserJid: function (focusJid) {
  13451. if (!focusUserJid) {
  13452. focusUserJid = focusJid;
  13453. console.info("Focus jid set to: " + focusUserJid);
  13454. }
  13455. },
  13456. getFocusUserJid: function () {
  13457. return focusUserJid;
  13458. },
  13459. getFocusComponent: function () {
  13460. // Get focus component address
  13461. var focusComponent = config.hosts.focus;
  13462. // If not specified use default: 'focus.domain'
  13463. if (!focusComponent) {
  13464. focusComponent = 'focus.' + config.hosts.domain;
  13465. }
  13466. return focusComponent;
  13467. },
  13468. createConferenceIq: function (roomName) {
  13469. // Generate create conference IQ
  13470. var elem = $iq({to: Moderator.getFocusComponent(), type: 'set'});
  13471. // Session Id used for authentication
  13472. var sessionId = localStorage.getItem('sessionId');
  13473. var machineUID = Settings.getSettings().uid;
  13474. console.info(
  13475. "Session ID: " + sessionId + " machine UID: " + machineUID);
  13476. elem.c('conference', {
  13477. xmlns: 'http://jitsi.org/protocol/focus',
  13478. room: roomName,
  13479. 'machine-uid': machineUID
  13480. });
  13481. if (sessionId) {
  13482. elem.attrs({ 'session-id': sessionId});
  13483. }
  13484. if (config.hosts.bridge !== undefined) {
  13485. elem.c(
  13486. 'property',
  13487. { name: 'bridge', value: config.hosts.bridge})
  13488. .up();
  13489. }
  13490. // Tell the focus we have Jigasi configured
  13491. if (config.hosts.call_control !== undefined) {
  13492. elem.c(
  13493. 'property',
  13494. { name: 'call_control', value: config.hosts.call_control})
  13495. .up();
  13496. }
  13497. if (config.channelLastN !== undefined) {
  13498. elem.c(
  13499. 'property',
  13500. { name: 'channelLastN', value: config.channelLastN})
  13501. .up();
  13502. }
  13503. if (config.adaptiveLastN !== undefined) {
  13504. elem.c(
  13505. 'property',
  13506. { name: 'adaptiveLastN', value: config.adaptiveLastN})
  13507. .up();
  13508. }
  13509. if (config.adaptiveSimulcast !== undefined) {
  13510. elem.c(
  13511. 'property',
  13512. { name: 'adaptiveSimulcast', value: config.adaptiveSimulcast})
  13513. .up();
  13514. }
  13515. if (config.openSctp !== undefined) {
  13516. elem.c(
  13517. 'property',
  13518. { name: 'openSctp', value: config.openSctp})
  13519. .up();
  13520. }
  13521. elem.up();
  13522. return elem;
  13523. },
  13524. parseSessionId: function (resultIq) {
  13525. var sessionId = $(resultIq).find('conference').attr('session-id');
  13526. if (sessionId) {
  13527. console.info('Received sessionId: ' + sessionId);
  13528. localStorage.setItem('sessionId', sessionId);
  13529. }
  13530. },
  13531. parseConfigOptions: function (resultIq) {
  13532. Moderator.setFocusUserJid(
  13533. $(resultIq).find('conference').attr('focusjid'));
  13534. var authenticationEnabled
  13535. = $(resultIq).find(
  13536. '>conference>property' +
  13537. '[name=\'authentication\'][value=\'true\']').length > 0;
  13538. console.info("Authentication enabled: " + authenticationEnabled);
  13539. externalAuthEnabled
  13540. = $(resultIq).find(
  13541. '>conference>property' +
  13542. '[name=\'externalAuth\'][value=\'true\']').length > 0;
  13543. console.info('External authentication enabled: ' + externalAuthEnabled);
  13544. if (!externalAuthEnabled) {
  13545. // We expect to receive sessionId in 'internal' authentication mode
  13546. Moderator.parseSessionId(resultIq);
  13547. }
  13548. var authIdentity = $(resultIq).find('>conference').attr('identity');
  13549. eventEmitter.emit(AuthenticationEvents.IDENTITY_UPDATED,
  13550. authenticationEnabled, authIdentity);
  13551. // Check if focus has auto-detected Jigasi component(this will be also
  13552. // included if we have passed our host from the config)
  13553. if ($(resultIq).find(
  13554. '>conference>property' +
  13555. '[name=\'sipGatewayEnabled\'][value=\'true\']').length) {
  13556. sipGatewayEnabled = true;
  13557. }
  13558. console.info("Sip gateway enabled: " + sipGatewayEnabled);
  13559. },
  13560. // FIXME: we need to show the fact that we're waiting for the focus
  13561. // to the user(or that focus is not available)
  13562. allocateConferenceFocus: function (roomName, callback) {
  13563. // Try to use focus user JID from the config
  13564. Moderator.setFocusUserJid(config.focusUserJid);
  13565. // Send create conference IQ
  13566. var iq = Moderator.createConferenceIq(roomName);
  13567. var self = this;
  13568. connection.sendIQ(
  13569. iq,
  13570. function (result) {
  13571. // Setup config options
  13572. Moderator.parseConfigOptions(result);
  13573. if ('true' === $(result).find('conference').attr('ready')) {
  13574. // Reset both timers
  13575. getNextTimeout(true);
  13576. getNextErrorTimeout(true);
  13577. // Exec callback
  13578. callback();
  13579. } else {
  13580. var waitMs = getNextTimeout();
  13581. console.info("Waiting for the focus... " + waitMs);
  13582. // Reset error timeout
  13583. getNextErrorTimeout(true);
  13584. window.setTimeout(
  13585. function () {
  13586. Moderator.allocateConferenceFocus(
  13587. roomName, callback);
  13588. }, waitMs);
  13589. }
  13590. },
  13591. function (error) {
  13592. // Invalid session ? remove and try again
  13593. // without session ID to get a new one
  13594. var invalidSession
  13595. = $(error).find('>error>session-invalid').length;
  13596. if (invalidSession) {
  13597. console.info("Session expired! - removing");
  13598. localStorage.removeItem("sessionId");
  13599. }
  13600. if ($(error).find('>error>graceful-shutdown').length) {
  13601. eventEmitter.emit(XMPPEvents.GRACEFUL_SHUTDOWN);
  13602. return;
  13603. }
  13604. // Check for error returned by the reservation system
  13605. var reservationErr = $(error).find('>error>reservation-error');
  13606. if (reservationErr.length) {
  13607. // Trigger error event
  13608. var errorCode = reservationErr.attr('error-code');
  13609. var errorMsg;
  13610. if ($(error).find('>error>text')) {
  13611. errorMsg = $(error).find('>error>text').text();
  13612. }
  13613. eventEmitter.emit(
  13614. XMPPEvents.RESERVATION_ERROR, errorCode, errorMsg);
  13615. return;
  13616. }
  13617. // Not authorized to create new room
  13618. if ($(error).find('>error>not-authorized').length) {
  13619. console.warn("Unauthorized to start the conference", error);
  13620. var toDomain
  13621. = Strophe.getDomainFromJid(error.getAttribute('to'));
  13622. if (toDomain !== config.hosts.anonymousdomain) {
  13623. // FIXME: "is external" should come either from
  13624. // the focus or config.js
  13625. externalAuthEnabled = true;
  13626. }
  13627. eventEmitter.emit(
  13628. XMPPEvents.AUTHENTICATION_REQUIRED,
  13629. function () {
  13630. Moderator.allocateConferenceFocus(
  13631. roomName, callback);
  13632. });
  13633. return;
  13634. }
  13635. var waitMs = getNextErrorTimeout();
  13636. console.error("Focus error, retry after " + waitMs, error);
  13637. // Show message
  13638. var focusComponent = Moderator.getFocusComponent();
  13639. var retrySec = waitMs / 1000;
  13640. // FIXME: message is duplicated ?
  13641. // Do not show in case of session invalid
  13642. // which means just a retry
  13643. if (!invalidSession) {
  13644. APP.UI.messageHandler.notify(
  13645. null, "notify.focus",
  13646. 'disconnected', "notify.focusFail",
  13647. {component: focusComponent, ms: retrySec});
  13648. }
  13649. // Reset response timeout
  13650. getNextTimeout(true);
  13651. window.setTimeout(
  13652. function () {
  13653. Moderator.allocateConferenceFocus(roomName, callback);
  13654. }, waitMs);
  13655. }
  13656. );
  13657. },
  13658. getLoginUrl: function (roomName, urlCallback) {
  13659. var iq = $iq({to: Moderator.getFocusComponent(), type: 'get'});
  13660. iq.c('login-url', {
  13661. xmlns: 'http://jitsi.org/protocol/focus',
  13662. room: roomName,
  13663. 'machine-uid': Settings.getSettings().uid
  13664. });
  13665. connection.sendIQ(
  13666. iq,
  13667. function (result) {
  13668. var url = $(result).find('login-url').attr('url');
  13669. url = url = decodeURIComponent(url);
  13670. if (url) {
  13671. console.info("Got auth url: " + url);
  13672. urlCallback(url);
  13673. } else {
  13674. console.error(
  13675. "Failed to get auth url from the focus", result);
  13676. }
  13677. },
  13678. function (error) {
  13679. console.error("Get auth url error", error);
  13680. }
  13681. );
  13682. },
  13683. getPopupLoginUrl: function (roomName, urlCallback) {
  13684. var iq = $iq({to: Moderator.getFocusComponent(), type: 'get'});
  13685. iq.c('login-url', {
  13686. xmlns: 'http://jitsi.org/protocol/focus',
  13687. room: roomName,
  13688. 'machine-uid': Settings.getSettings().uid,
  13689. popup: true
  13690. });
  13691. connection.sendIQ(
  13692. iq,
  13693. function (result) {
  13694. var url = $(result).find('login-url').attr('url');
  13695. url = url = decodeURIComponent(url);
  13696. if (url) {
  13697. console.info("Got POPUP auth url: " + url);
  13698. urlCallback(url);
  13699. } else {
  13700. console.error(
  13701. "Failed to get POPUP auth url from the focus", result);
  13702. }
  13703. },
  13704. function (error) {
  13705. console.error('Get POPUP auth url error', error);
  13706. }
  13707. );
  13708. },
  13709. logout: function (callback) {
  13710. var iq = $iq({to: Moderator.getFocusComponent(), type: 'set'});
  13711. var sessionId = localStorage.getItem('sessionId');
  13712. if (!sessionId) {
  13713. callback();
  13714. return;
  13715. }
  13716. iq.c('logout', {
  13717. xmlns: 'http://jitsi.org/protocol/focus',
  13718. 'session-id': sessionId
  13719. });
  13720. connection.sendIQ(
  13721. iq,
  13722. function (result) {
  13723. var logoutUrl = $(result).find('logout').attr('logout-url');
  13724. if (logoutUrl) {
  13725. logoutUrl = decodeURIComponent(logoutUrl);
  13726. }
  13727. console.info("Log out OK, url: " + logoutUrl, result);
  13728. localStorage.removeItem('sessionId');
  13729. callback(logoutUrl);
  13730. },
  13731. function (error) {
  13732. console.error("Logout error", error);
  13733. }
  13734. );
  13735. }
  13736. };
  13737. module.exports = Moderator;
  13738. },{"../../service/authentication/AuthenticationEvents":96,"../../service/xmpp/XMPPEvents":101,"../settings/Settings":40}],56:[function(require,module,exports){
  13739. /* global $, $iq, config, connection, focusMucJid, messageHandler, Moderator,
  13740. Toolbar, Util */
  13741. var Moderator = require("./moderator");
  13742. var recordingToken = null;
  13743. var recordingEnabled;
  13744. /**
  13745. * Whether to use a jirecon component for recording, or use the videobridge
  13746. * through COLIBRI.
  13747. */
  13748. var useJirecon = (typeof config.hosts.jirecon != "undefined");
  13749. /**
  13750. * The ID of the jirecon recording session. Jirecon generates it when we
  13751. * initially start recording, and it needs to be used in subsequent requests
  13752. * to jirecon.
  13753. */
  13754. var jireconRid = null;
  13755. function setRecordingToken(token) {
  13756. recordingToken = token;
  13757. }
  13758. function setRecording(state, token, callback, connection) {
  13759. if (useJirecon){
  13760. setRecordingJirecon(state, token, callback, connection);
  13761. } else {
  13762. setRecordingColibri(state, token, callback, connection);
  13763. }
  13764. }
  13765. function setRecordingJirecon(state, token, callback, connection) {
  13766. if (state == recordingEnabled){
  13767. return;
  13768. }
  13769. var iq = $iq({to: config.hosts.jirecon, type: 'set'})
  13770. .c('recording', {xmlns: 'http://jitsi.org/protocol/jirecon',
  13771. action: state ? 'start' : 'stop',
  13772. mucjid: connection.emuc.roomjid});
  13773. if (!state){
  13774. iq.attrs({rid: jireconRid});
  13775. }
  13776. console.log('Start recording');
  13777. connection.sendIQ(
  13778. iq,
  13779. function (result) {
  13780. // TODO wait for an IQ with the real status, since this is
  13781. // provisional?
  13782. jireconRid = $(result).find('recording').attr('rid');
  13783. console.log('Recording ' + (state ? 'started' : 'stopped') +
  13784. '(jirecon)' + result);
  13785. recordingEnabled = state;
  13786. if (!state){
  13787. jireconRid = null;
  13788. }
  13789. callback(state);
  13790. },
  13791. function (error) {
  13792. console.log('Failed to start recording, error: ', error);
  13793. callback(recordingEnabled);
  13794. });
  13795. }
  13796. // Sends a COLIBRI message which enables or disables (according to 'state')
  13797. // the recording on the bridge. Waits for the result IQ and calls 'callback'
  13798. // with the new recording state, according to the IQ.
  13799. function setRecordingColibri(state, token, callback, connection) {
  13800. var elem = $iq({to: connection.emuc.focusMucJid, type: 'set'});
  13801. elem.c('conference', {
  13802. xmlns: 'http://jitsi.org/protocol/colibri'
  13803. });
  13804. elem.c('recording', {state: state, token: token});
  13805. connection.sendIQ(elem,
  13806. function (result) {
  13807. console.log('Set recording "', state, '". Result:', result);
  13808. var recordingElem = $(result).find('>conference>recording');
  13809. var newState = ('true' === recordingElem.attr('state'));
  13810. recordingEnabled = newState;
  13811. callback(newState);
  13812. },
  13813. function (error) {
  13814. console.warn(error);
  13815. callback(recordingEnabled);
  13816. }
  13817. );
  13818. }
  13819. var Recording = {
  13820. toggleRecording: function (tokenEmptyCallback,
  13821. startingCallback, startedCallback, connection) {
  13822. if (!Moderator.isModerator()) {
  13823. console.log(
  13824. 'non-focus, or conference not yet organized:' +
  13825. ' not enabling recording');
  13826. return;
  13827. }
  13828. var self = this;
  13829. // Jirecon does not (currently) support a token.
  13830. if (!recordingToken && !useJirecon) {
  13831. tokenEmptyCallback(function (value) {
  13832. setRecordingToken(value);
  13833. self.toggleRecording(tokenEmptyCallback,
  13834. startingCallback, startedCallback, connection);
  13835. });
  13836. return;
  13837. }
  13838. var oldState = recordingEnabled;
  13839. startingCallback(!oldState);
  13840. setRecording(!oldState,
  13841. recordingToken,
  13842. function (state) {
  13843. console.log("New recording state: ", state);
  13844. if (state === oldState) {
  13845. // FIXME: new focus:
  13846. // this will not work when moderator changes
  13847. // during active session. Then it will assume that
  13848. // recording status has changed to true, but it might have
  13849. // been already true(and we only received actual status from
  13850. // the focus).
  13851. //
  13852. // SO we start with status null, so that it is initialized
  13853. // here and will fail only after second click, so if invalid
  13854. // token was used we have to press the button twice before
  13855. // current status will be fetched and token will be reset.
  13856. //
  13857. // Reliable way would be to return authentication error.
  13858. // Or status update when moderator connects.
  13859. // Or we have to stop recording session when current
  13860. // moderator leaves the room.
  13861. // Failed to change, reset the token because it might
  13862. // have been wrong
  13863. setRecordingToken(null);
  13864. }
  13865. startedCallback(state);
  13866. },
  13867. connection
  13868. );
  13869. }
  13870. }
  13871. module.exports = Recording;
  13872. },{"./moderator":55}],57:[function(require,module,exports){
  13873. /* jshint -W117 */
  13874. /* a simple MUC connection plugin
  13875. * can only handle a single MUC room
  13876. */
  13877. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  13878. var Moderator = require("./moderator");
  13879. var JingleSession = require("./JingleSession");
  13880. var bridgeIsDown = false;
  13881. module.exports = function(XMPP, eventEmitter) {
  13882. Strophe.addConnectionPlugin('emuc', {
  13883. connection: null,
  13884. roomjid: null,
  13885. myroomjid: null,
  13886. members: {},
  13887. list_members: [], // so we can elect a new focus
  13888. presMap: {},
  13889. preziMap: {},
  13890. joined: false,
  13891. isOwner: false,
  13892. role: null,
  13893. focusMucJid: null,
  13894. ssrc2jid: {},
  13895. init: function (conn) {
  13896. this.connection = conn;
  13897. },
  13898. initPresenceMap: function (myroomjid) {
  13899. this.presMap['to'] = myroomjid;
  13900. this.presMap['xns'] = 'http://jabber.org/protocol/muc';
  13901. },
  13902. doJoin: function (jid, password) {
  13903. this.myroomjid = jid;
  13904. console.info("Joined MUC as " + this.myroomjid);
  13905. this.initPresenceMap(this.myroomjid);
  13906. if (!this.roomjid) {
  13907. this.roomjid = Strophe.getBareJidFromJid(jid);
  13908. // add handlers (just once)
  13909. this.connection.addHandler(this.onPresence.bind(this), null, 'presence', null, null, this.roomjid, {matchBare: true});
  13910. this.connection.addHandler(this.onPresenceUnavailable.bind(this), null, 'presence', 'unavailable', null, this.roomjid, {matchBare: true});
  13911. this.connection.addHandler(this.onPresenceError.bind(this), null, 'presence', 'error', null, this.roomjid, {matchBare: true});
  13912. this.connection.addHandler(this.onMessage.bind(this), null, 'message', null, null, this.roomjid, {matchBare: true});
  13913. }
  13914. if (password !== undefined) {
  13915. this.presMap['password'] = password;
  13916. }
  13917. this.sendPresence();
  13918. },
  13919. doLeave: function () {
  13920. console.log("do leave", this.myroomjid);
  13921. var pres = $pres({to: this.myroomjid, type: 'unavailable' });
  13922. this.presMap.length = 0;
  13923. this.connection.send(pres);
  13924. },
  13925. createNonAnonymousRoom: function () {
  13926. // http://xmpp.org/extensions/xep-0045.html#createroom-reserved
  13927. var getForm = $iq({type: 'get', to: this.roomjid})
  13928. .c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'})
  13929. .c('x', {xmlns: 'jabber:x:data', type: 'submit'});
  13930. var self = this;
  13931. this.connection.sendIQ(getForm, function (form) {
  13932. if (!$(form).find(
  13933. '>query>x[xmlns="jabber:x:data"]' +
  13934. '>field[var="muc#roomconfig_whois"]').length) {
  13935. console.error('non-anonymous rooms not supported');
  13936. return;
  13937. }
  13938. var formSubmit = $iq({to: this.roomjid, type: 'set'})
  13939. .c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'});
  13940. formSubmit.c('x', {xmlns: 'jabber:x:data', type: 'submit'});
  13941. formSubmit.c('field', {'var': 'FORM_TYPE'})
  13942. .c('value')
  13943. .t('http://jabber.org/protocol/muc#roomconfig').up().up();
  13944. formSubmit.c('field', {'var': 'muc#roomconfig_whois'})
  13945. .c('value').t('anyone').up().up();
  13946. self.connection.sendIQ(formSubmit);
  13947. }, function (error) {
  13948. console.error("Error getting room configuration form");
  13949. });
  13950. },
  13951. onPresence: function (pres) {
  13952. var from = pres.getAttribute('from');
  13953. // What is this for? A workaround for something?
  13954. if (pres.getAttribute('type')) {
  13955. return true;
  13956. }
  13957. // Parse etherpad tag.
  13958. var etherpad = $(pres).find('>etherpad');
  13959. if (etherpad.length) {
  13960. if (config.etherpad_base && !Moderator.isModerator()) {
  13961. eventEmitter.emit(XMPPEvents.ETHERPAD, etherpad.text());
  13962. }
  13963. }
  13964. // Parse prezi tag.
  13965. var presentation = $(pres).find('>prezi');
  13966. if (presentation.length) {
  13967. var url = presentation.attr('url');
  13968. var current = presentation.find('>current').text();
  13969. console.log('presentation info received from', from, url);
  13970. if (this.preziMap[from] == null) {
  13971. this.preziMap[from] = url;
  13972. $(document).trigger('presentationadded.muc', [from, url, current]);
  13973. }
  13974. else {
  13975. $(document).trigger('gotoslide.muc', [from, url, current]);
  13976. }
  13977. }
  13978. else if (this.preziMap[from] != null) {
  13979. var url = this.preziMap[from];
  13980. delete this.preziMap[from];
  13981. $(document).trigger('presentationremoved.muc', [from, url]);
  13982. }
  13983. // Parse audio info tag.
  13984. var audioMuted = $(pres).find('>audiomuted');
  13985. if (audioMuted.length) {
  13986. $(document).trigger('audiomuted.muc', [from, audioMuted.text()]);
  13987. }
  13988. // Parse video info tag.
  13989. var videoMuted = $(pres).find('>videomuted');
  13990. if (videoMuted.length) {
  13991. $(document).trigger('videomuted.muc', [from, videoMuted.text()]);
  13992. }
  13993. var devices = $(pres).find('>devices');
  13994. if(devices.length)
  13995. {
  13996. var audio = devices.find('>audio');
  13997. var video = devices.find('>video');
  13998. var devicesValues = {audio: false, video: false};
  13999. if(audio.length && audio.text() === "true")
  14000. {
  14001. devicesValues.audio = true;
  14002. }
  14003. if(video.length && video.text() === "true")
  14004. {
  14005. devicesValues.video = true;
  14006. }
  14007. eventEmitter.emit(XMPPEvents.DEVICE_AVAILABLE,
  14008. Strophe.getResourceFromJid(from), devicesValues);
  14009. }
  14010. var stats = $(pres).find('>stats');
  14011. if (stats.length) {
  14012. var statsObj = {};
  14013. Strophe.forEachChild(stats[0], "stat", function (el) {
  14014. statsObj[el.getAttribute("name")] = el.getAttribute("value");
  14015. });
  14016. eventEmitter.emit(XMPPEvents.REMOTE_STATS, from, statsObj);
  14017. }
  14018. // Parse status.
  14019. if ($(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>status[code="201"]').length) {
  14020. this.isOwner = true;
  14021. this.createNonAnonymousRoom();
  14022. }
  14023. // Parse roles.
  14024. var member = {};
  14025. member.show = $(pres).find('>show').text();
  14026. member.status = $(pres).find('>status').text();
  14027. var tmp = $(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>item');
  14028. member.affiliation = tmp.attr('affiliation');
  14029. member.role = tmp.attr('role');
  14030. // Focus recognition
  14031. member.jid = tmp.attr('jid');
  14032. member.isFocus = false;
  14033. if (member.jid
  14034. && member.jid.indexOf(Moderator.getFocusUserJid() + "/") == 0) {
  14035. member.isFocus = true;
  14036. }
  14037. var nicktag = $(pres).find('>nick[xmlns="http://jabber.org/protocol/nick"]');
  14038. member.displayName = (nicktag.length > 0 ? nicktag.html() : null);
  14039. if (from == this.myroomjid) {
  14040. if (member.affiliation == 'owner') this.isOwner = true;
  14041. if (this.role !== member.role) {
  14042. this.role = member.role;
  14043. eventEmitter.emit(XMPPEvents.LOCAL_ROLE_CHANGED,
  14044. from, member, pres, Moderator.isModerator());
  14045. }
  14046. if (!this.joined) {
  14047. this.joined = true;
  14048. eventEmitter.emit(XMPPEvents.MUC_JOINED, from, member);
  14049. this.list_members.push(from);
  14050. }
  14051. } else if (this.members[from] === undefined) {
  14052. // new participant
  14053. this.members[from] = member;
  14054. this.list_members.push(from);
  14055. console.log('entered', from, member);
  14056. if (member.isFocus) {
  14057. this.focusMucJid = from;
  14058. console.info("Ignore focus: " + from + ", real JID: " + member.jid);
  14059. }
  14060. else {
  14061. var id = $(pres).find('>userId').text();
  14062. var email = $(pres).find('>email');
  14063. if (email.length > 0) {
  14064. id = email.text();
  14065. }
  14066. eventEmitter.emit(XMPPEvents.MUC_MEMBER_JOINED, from, id, member.displayName);
  14067. }
  14068. } else {
  14069. // Presence update for existing participant
  14070. // Watch role change:
  14071. if (this.members[from].role != member.role) {
  14072. this.members[from].role = member.role;
  14073. eventEmitter.emit(XMPPEvents.MUC_ROLE_CHANGED,
  14074. member.role, member.displayName);
  14075. }
  14076. }
  14077. // Always trigger presence to update bindings
  14078. this.parsePresence(from, member, pres);
  14079. // Trigger status message update
  14080. if (member.status) {
  14081. eventEmitter.emit(XMPPEvents.PRESENCE_STATUS, from, member);
  14082. }
  14083. return true;
  14084. },
  14085. onPresenceUnavailable: function (pres) {
  14086. var from = pres.getAttribute('from');
  14087. // room destroyed ?
  14088. if ($(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]' +
  14089. '>destroy').length) {
  14090. var reason;
  14091. var reasonSelect = $(pres).find(
  14092. '>x[xmlns="http://jabber.org/protocol/muc#user"]' +
  14093. '>destroy>reason');
  14094. if (reasonSelect.length) {
  14095. reason = reasonSelect.text();
  14096. }
  14097. XMPP.disposeConference(false);
  14098. eventEmitter.emit(XMPPEvents.MUC_DESTROYED, reason);
  14099. return true;
  14100. }
  14101. // Status code 110 indicates that this notification is "self-presence".
  14102. if (!$(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>status[code="110"]').length) {
  14103. delete this.members[from];
  14104. this.list_members.splice(this.list_members.indexOf(from), 1);
  14105. this.onParticipantLeft(from);
  14106. }
  14107. // If the status code is 110 this means we're leaving and we would like
  14108. // to remove everyone else from our view, so we trigger the event.
  14109. else if (this.list_members.length > 1) {
  14110. for (var i = 0; i < this.list_members.length; i++) {
  14111. var member = this.list_members[i];
  14112. delete this.members[i];
  14113. this.list_members.splice(i, 1);
  14114. this.onParticipantLeft(member);
  14115. }
  14116. }
  14117. if ($(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>status[code="307"]').length) {
  14118. $(document).trigger('kicked.muc', [from]);
  14119. if (this.myroomjid === from) {
  14120. XMPP.disposeConference(false);
  14121. eventEmitter.emit(XMPPEvents.KICKED);
  14122. }
  14123. }
  14124. return true;
  14125. },
  14126. onPresenceError: function (pres) {
  14127. var from = pres.getAttribute('from');
  14128. if ($(pres).find('>error[type="auth"]>not-authorized[xmlns="urn:ietf:params:xml:ns:xmpp-stanzas"]').length) {
  14129. console.log('on password required', from);
  14130. var self = this;
  14131. eventEmitter.emit(XMPPEvents.PASSWORD_REQUIRED, function (value) {
  14132. self.doJoin(from, value);
  14133. });
  14134. } else if ($(pres).find(
  14135. '>error[type="cancel"]>not-allowed[xmlns="urn:ietf:params:xml:ns:xmpp-stanzas"]').length) {
  14136. var toDomain = Strophe.getDomainFromJid(pres.getAttribute('to'));
  14137. if (toDomain === config.hosts.anonymousdomain) {
  14138. // enter the room by replying with 'not-authorized'. This would
  14139. // result in reconnection from authorized domain.
  14140. // We're either missing Jicofo/Prosody config for anonymous
  14141. // domains or something is wrong.
  14142. // XMPP.promptLogin();
  14143. APP.UI.messageHandler.openReportDialog(null,
  14144. "dialog.joinError", pres);
  14145. } else {
  14146. console.warn('onPresError ', pres);
  14147. APP.UI.messageHandler.openReportDialog(null,
  14148. "dialog.connectError",
  14149. pres);
  14150. }
  14151. } else {
  14152. console.warn('onPresError ', pres);
  14153. APP.UI.messageHandler.openReportDialog(null,
  14154. "dialog.connectError",
  14155. pres);
  14156. }
  14157. return true;
  14158. },
  14159. sendMessage: function (body, nickname) {
  14160. var msg = $msg({to: this.roomjid, type: 'groupchat'});
  14161. msg.c('body', body).up();
  14162. if (nickname) {
  14163. msg.c('nick', {xmlns: 'http://jabber.org/protocol/nick'}).t(nickname).up().up();
  14164. }
  14165. this.connection.send(msg);
  14166. eventEmitter.emit(XMPPEvents.SENDING_CHAT_MESSAGE, body);
  14167. },
  14168. setSubject: function (subject) {
  14169. var msg = $msg({to: this.roomjid, type: 'groupchat'});
  14170. msg.c('subject', subject);
  14171. this.connection.send(msg);
  14172. console.log("topic changed to " + subject);
  14173. },
  14174. onMessage: function (msg) {
  14175. // FIXME: this is a hack. but jingle on muc makes nickchanges hard
  14176. var from = msg.getAttribute('from');
  14177. var nick =
  14178. $(msg).find('>nick[xmlns="http://jabber.org/protocol/nick"]')
  14179. .text() ||
  14180. Strophe.getResourceFromJid(from);
  14181. var txt = $(msg).find('>body').text();
  14182. var type = msg.getAttribute("type");
  14183. if (type == "error") {
  14184. eventEmitter.emit(XMPPEvents.CHAT_ERROR_RECEIVED,
  14185. $(msg).find('>text').text(), txt);
  14186. return true;
  14187. }
  14188. var subject = $(msg).find('>subject');
  14189. if (subject.length) {
  14190. var subjectText = subject.text();
  14191. if (subjectText || subjectText == "") {
  14192. eventEmitter.emit(XMPPEvents.SUBJECT_CHANGED, subjectText);
  14193. console.log("Subject is changed to " + subjectText);
  14194. }
  14195. }
  14196. if (txt) {
  14197. console.log('chat', nick, txt);
  14198. eventEmitter.emit(XMPPEvents.MESSAGE_RECEIVED,
  14199. from, nick, txt, this.myroomjid);
  14200. }
  14201. return true;
  14202. },
  14203. lockRoom: function (key, onSuccess, onError, onNotSupported) {
  14204. //http://xmpp.org/extensions/xep-0045.html#roomconfig
  14205. var ob = this;
  14206. this.connection.sendIQ($iq({to: this.roomjid, type: 'get'}).c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'}),
  14207. function (res) {
  14208. if ($(res).find('>query>x[xmlns="jabber:x:data"]>field[var="muc#roomconfig_roomsecret"]').length) {
  14209. var formsubmit = $iq({to: ob.roomjid, type: 'set'}).c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'});
  14210. formsubmit.c('x', {xmlns: 'jabber:x:data', type: 'submit'});
  14211. formsubmit.c('field', {'var': 'FORM_TYPE'}).c('value').t('http://jabber.org/protocol/muc#roomconfig').up().up();
  14212. formsubmit.c('field', {'var': 'muc#roomconfig_roomsecret'}).c('value').t(key).up().up();
  14213. // Fixes a bug in prosody 0.9.+ https://code.google.com/p/lxmppd/issues/detail?id=373
  14214. formsubmit.c('field', {'var': 'muc#roomconfig_whois'}).c('value').t('anyone').up().up();
  14215. // FIXME: is muc#roomconfig_passwordprotectedroom required?
  14216. ob.connection.sendIQ(formsubmit,
  14217. onSuccess,
  14218. onError);
  14219. } else {
  14220. onNotSupported();
  14221. }
  14222. }, onError);
  14223. },
  14224. kick: function (jid) {
  14225. var kickIQ = $iq({to: this.roomjid, type: 'set'})
  14226. .c('query', {xmlns: 'http://jabber.org/protocol/muc#admin'})
  14227. .c('item', {nick: Strophe.getResourceFromJid(jid), role: 'none'})
  14228. .c('reason').t('You have been kicked.').up().up().up();
  14229. this.connection.sendIQ(
  14230. kickIQ,
  14231. function (result) {
  14232. console.log('Kick participant with jid: ', jid, result);
  14233. },
  14234. function (error) {
  14235. console.log('Kick participant error: ', error);
  14236. });
  14237. },
  14238. sendPresence: function () {
  14239. if (!this.presMap['to']) {
  14240. // Too early to send presence - not initialized
  14241. return;
  14242. }
  14243. var pres = $pres({to: this.presMap['to'] });
  14244. pres.c('x', {xmlns: this.presMap['xns']});
  14245. if (this.presMap['password']) {
  14246. pres.c('password').t(this.presMap['password']).up();
  14247. }
  14248. pres.up();
  14249. // Send XEP-0115 'c' stanza that contains our capabilities info
  14250. if (this.connection.caps) {
  14251. this.connection.caps.node = config.clientNode;
  14252. pres.c('c', this.connection.caps.generateCapsAttrs()).up();
  14253. }
  14254. pres.c('user-agent', {xmlns: 'http://jitsi.org/jitmeet/user-agent'})
  14255. .t(navigator.userAgent).up();
  14256. if (this.presMap['bridgeIsDown']) {
  14257. pres.c('bridgeIsDown').up();
  14258. }
  14259. if (this.presMap['email']) {
  14260. pres.c('email').t(this.presMap['email']).up();
  14261. }
  14262. if (this.presMap['userId']) {
  14263. pres.c('userId').t(this.presMap['userId']).up();
  14264. }
  14265. if (this.presMap['displayName']) {
  14266. // XEP-0172
  14267. pres.c('nick', {xmlns: 'http://jabber.org/protocol/nick'})
  14268. .t(this.presMap['displayName']).up();
  14269. }
  14270. if(this.presMap["devices"])
  14271. {
  14272. pres.c('devices').c('audio').t(this.presMap['devices'].audio).up()
  14273. .c('video').t(this.presMap['devices'].video).up().up();
  14274. }
  14275. if (this.presMap['audions']) {
  14276. pres.c('audiomuted', {xmlns: this.presMap['audions']})
  14277. .t(this.presMap['audiomuted']).up();
  14278. }
  14279. if (this.presMap['videons']) {
  14280. pres.c('videomuted', {xmlns: this.presMap['videons']})
  14281. .t(this.presMap['videomuted']).up();
  14282. }
  14283. if (this.presMap['statsns']) {
  14284. var stats = pres.c('stats', {xmlns: this.presMap['statsns']});
  14285. for (var stat in this.presMap["stats"])
  14286. if (this.presMap["stats"][stat] != null)
  14287. stats.c("stat", {name: stat, value: this.presMap["stats"][stat]}).up();
  14288. pres.up();
  14289. }
  14290. if (this.presMap['prezins']) {
  14291. pres.c('prezi',
  14292. {xmlns: this.presMap['prezins'],
  14293. 'url': this.presMap['preziurl']})
  14294. .c('current').t(this.presMap['prezicurrent']).up().up();
  14295. }
  14296. if (this.presMap['etherpadns']) {
  14297. pres.c('etherpad', {xmlns: this.presMap['etherpadns']})
  14298. .t(this.presMap['etherpadname']).up();
  14299. }
  14300. if (this.presMap['medians']) {
  14301. pres.c('media', {xmlns: this.presMap['medians']});
  14302. var sourceNumber = 0;
  14303. Object.keys(this.presMap).forEach(function (key) {
  14304. if (key.indexOf('source') >= 0) {
  14305. sourceNumber++;
  14306. }
  14307. });
  14308. if (sourceNumber > 0)
  14309. for (var i = 1; i <= sourceNumber / 3; i++) {
  14310. pres.c('source',
  14311. {type: this.presMap['source' + i + '_type'],
  14312. ssrc: this.presMap['source' + i + '_ssrc'],
  14313. direction: this.presMap['source' + i + '_direction']
  14314. || 'sendrecv' }
  14315. ).up();
  14316. }
  14317. }
  14318. pres.up();
  14319. this.connection.send(pres);
  14320. },
  14321. addDisplayNameToPresence: function (displayName) {
  14322. this.presMap['displayName'] = displayName;
  14323. },
  14324. addMediaToPresence: function (sourceNumber, mtype, ssrcs, direction) {
  14325. if (!this.presMap['medians'])
  14326. this.presMap['medians'] = 'http://estos.de/ns/mjs';
  14327. this.presMap['source' + sourceNumber + '_type'] = mtype;
  14328. this.presMap['source' + sourceNumber + '_ssrc'] = ssrcs;
  14329. this.presMap['source' + sourceNumber + '_direction'] = direction;
  14330. },
  14331. addDevicesToPresence: function (devices) {
  14332. this.presMap['devices'] = devices;
  14333. },
  14334. clearPresenceMedia: function () {
  14335. var self = this;
  14336. Object.keys(this.presMap).forEach(function (key) {
  14337. if (key.indexOf('source') != -1) {
  14338. delete self.presMap[key];
  14339. }
  14340. });
  14341. },
  14342. addPreziToPresence: function (url, currentSlide) {
  14343. this.presMap['prezins'] = 'http://jitsi.org/jitmeet/prezi';
  14344. this.presMap['preziurl'] = url;
  14345. this.presMap['prezicurrent'] = currentSlide;
  14346. },
  14347. removePreziFromPresence: function () {
  14348. delete this.presMap['prezins'];
  14349. delete this.presMap['preziurl'];
  14350. delete this.presMap['prezicurrent'];
  14351. },
  14352. addCurrentSlideToPresence: function (currentSlide) {
  14353. this.presMap['prezicurrent'] = currentSlide;
  14354. },
  14355. getPrezi: function (roomjid) {
  14356. return this.preziMap[roomjid];
  14357. },
  14358. addEtherpadToPresence: function (etherpadName) {
  14359. this.presMap['etherpadns'] = 'http://jitsi.org/jitmeet/etherpad';
  14360. this.presMap['etherpadname'] = etherpadName;
  14361. },
  14362. addAudioInfoToPresence: function (isMuted) {
  14363. this.presMap['audions'] = 'http://jitsi.org/jitmeet/audio';
  14364. this.presMap['audiomuted'] = isMuted.toString();
  14365. },
  14366. addVideoInfoToPresence: function (isMuted) {
  14367. this.presMap['videons'] = 'http://jitsi.org/jitmeet/video';
  14368. this.presMap['videomuted'] = isMuted.toString();
  14369. },
  14370. addConnectionInfoToPresence: function (stats) {
  14371. this.presMap['statsns'] = 'http://jitsi.org/jitmeet/stats';
  14372. this.presMap['stats'] = stats;
  14373. },
  14374. findJidFromResource: function (resourceJid) {
  14375. if (resourceJid &&
  14376. resourceJid === Strophe.getResourceFromJid(this.myroomjid)) {
  14377. return this.myroomjid;
  14378. }
  14379. var peerJid = null;
  14380. Object.keys(this.members).some(function (jid) {
  14381. peerJid = jid;
  14382. return Strophe.getResourceFromJid(jid) === resourceJid;
  14383. });
  14384. return peerJid;
  14385. },
  14386. addBridgeIsDownToPresence: function () {
  14387. this.presMap['bridgeIsDown'] = true;
  14388. },
  14389. addEmailToPresence: function (email) {
  14390. this.presMap['email'] = email;
  14391. },
  14392. addUserIdToPresence: function (userId) {
  14393. this.presMap['userId'] = userId;
  14394. },
  14395. isModerator: function () {
  14396. return this.role === 'moderator';
  14397. },
  14398. getMemberRole: function (peerJid) {
  14399. if (this.members[peerJid]) {
  14400. return this.members[peerJid].role;
  14401. }
  14402. return null;
  14403. },
  14404. onParticipantLeft: function (jid) {
  14405. eventEmitter.emit(XMPPEvents.MUC_MEMBER_LEFT, jid);
  14406. this.connection.jingle.terminateByJid(jid);
  14407. if (this.getPrezi(jid)) {
  14408. $(document).trigger('presentationremoved.muc',
  14409. [jid, this.getPrezi(jid)]);
  14410. }
  14411. Moderator.onMucMemberLeft(jid);
  14412. },
  14413. parsePresence: function (from, memeber, pres) {
  14414. if($(pres).find(">bridgeIsDown").length > 0 && !bridgeIsDown) {
  14415. bridgeIsDown = true;
  14416. eventEmitter.emit(XMPPEvents.BRIDGE_DOWN);
  14417. }
  14418. if(memeber.isFocus)
  14419. return;
  14420. var self = this;
  14421. // Remove old ssrcs coming from the jid
  14422. Object.keys(this.ssrc2jid).forEach(function (ssrc) {
  14423. if (self.ssrc2jid[ssrc] == from) {
  14424. delete self.ssrc2jid[ssrc];
  14425. }
  14426. });
  14427. var changedStreams = [];
  14428. $(pres).find('>media[xmlns="http://estos.de/ns/mjs"]>source').each(function (idx, ssrc) {
  14429. //console.log(jid, 'assoc ssrc', ssrc.getAttribute('type'), ssrc.getAttribute('ssrc'));
  14430. var ssrcV = ssrc.getAttribute('ssrc');
  14431. self.ssrc2jid[ssrcV] = from;
  14432. JingleSession.notReceivedSSRCs.push(ssrcV);
  14433. var type = ssrc.getAttribute('type');
  14434. var direction = ssrc.getAttribute('direction');
  14435. changedStreams.push({type: type, direction: direction});
  14436. });
  14437. eventEmitter.emit(XMPPEvents.STREAMS_CHANGED, from, changedStreams);
  14438. var displayName = !config.displayJids
  14439. ? memeber.displayName : Strophe.getResourceFromJid(from);
  14440. if (displayName && displayName.length > 0)
  14441. {
  14442. eventEmitter.emit(XMPPEvents.DISPLAY_NAME_CHANGED, from, displayName);
  14443. }
  14444. var id = $(pres).find('>userID').text();
  14445. var email = $(pres).find('>email');
  14446. if(email.length > 0) {
  14447. id = email.text();
  14448. }
  14449. eventEmitter.emit(XMPPEvents.USER_ID_CHANGED, from, id);
  14450. }
  14451. });
  14452. };
  14453. },{"../../service/xmpp/XMPPEvents":101,"./JingleSession":50,"./moderator":55}],58:[function(require,module,exports){
  14454. /* jshint -W117 */
  14455. var JingleSession = require("./JingleSession");
  14456. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  14457. module.exports = function(XMPP, eventEmitter)
  14458. {
  14459. function CallIncomingJingle(sid, connection) {
  14460. var sess = connection.jingle.sessions[sid];
  14461. // TODO: do we check activecall == null?
  14462. connection.jingle.activecall = sess;
  14463. eventEmitter.emit(XMPPEvents.CALL_INCOMING, sess);
  14464. // TODO: check affiliation and/or role
  14465. console.log('emuc data for', sess.peerjid, connection.emuc.members[sess.peerjid]);
  14466. sess.usedrip = true; // not-so-naive trickle ice
  14467. sess.sendAnswer();
  14468. sess.accept();
  14469. };
  14470. Strophe.addConnectionPlugin('jingle', {
  14471. connection: null,
  14472. sessions: {},
  14473. jid2session: {},
  14474. ice_config: {iceServers: []},
  14475. pc_constraints: {},
  14476. activecall: null,
  14477. media_constraints: {
  14478. mandatory: {
  14479. 'OfferToReceiveAudio': true,
  14480. 'OfferToReceiveVideo': true
  14481. }
  14482. // MozDontOfferDataChannel: true when this is firefox
  14483. },
  14484. init: function (conn) {
  14485. this.connection = conn;
  14486. if (this.connection.disco) {
  14487. // http://xmpp.org/extensions/xep-0167.html#support
  14488. // http://xmpp.org/extensions/xep-0176.html#support
  14489. this.connection.disco.addFeature('urn:xmpp:jingle:1');
  14490. this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:1');
  14491. this.connection.disco.addFeature('urn:xmpp:jingle:transports:ice-udp:1');
  14492. this.connection.disco.addFeature('urn:xmpp:jingle:transports:dtls-sctp:1');
  14493. this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:audio');
  14494. this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:video');
  14495. // this is dealt with by SDP O/A so we don't need to annouce this
  14496. //this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:rtcp-fb:0'); // XEP-0293
  14497. //this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:rtp-hdrext:0'); // XEP-0294
  14498. if (config.useRtcpMux) {
  14499. this.connection.disco.addFeature('urn:ietf:rfc:5761'); // rtcp-mux
  14500. }
  14501. if (config.useBundle) {
  14502. this.connection.disco.addFeature('urn:ietf:rfc:5888'); // a=group, e.g. bundle
  14503. }
  14504. //this.connection.disco.addFeature('urn:ietf:rfc:5576'); // a=ssrc
  14505. }
  14506. this.connection.addHandler(this.onJingle.bind(this), 'urn:xmpp:jingle:1', 'iq', 'set', null, null);
  14507. },
  14508. onJingle: function (iq) {
  14509. var sid = $(iq).find('jingle').attr('sid');
  14510. var action = $(iq).find('jingle').attr('action');
  14511. var fromJid = iq.getAttribute('from');
  14512. // send ack first
  14513. var ack = $iq({type: 'result',
  14514. to: fromJid,
  14515. id: iq.getAttribute('id')
  14516. });
  14517. console.log('on jingle ' + action + ' from ' + fromJid, iq);
  14518. var sess = this.sessions[sid];
  14519. if ('session-initiate' != action) {
  14520. if (sess === null) {
  14521. ack.type = 'error';
  14522. ack.c('error', {type: 'cancel'})
  14523. .c('item-not-found', {xmlns: 'urn:ietf:params:xml:ns:xmpp-stanzas'}).up()
  14524. .c('unknown-session', {xmlns: 'urn:xmpp:jingle:errors:1'});
  14525. this.connection.send(ack);
  14526. return true;
  14527. }
  14528. // compare from to sess.peerjid (bare jid comparison for later compat with message-mode)
  14529. // local jid is not checked
  14530. if (Strophe.getBareJidFromJid(fromJid) != Strophe.getBareJidFromJid(sess.peerjid)) {
  14531. console.warn('jid mismatch for session id', sid, fromJid, sess.peerjid);
  14532. ack.type = 'error';
  14533. ack.c('error', {type: 'cancel'})
  14534. .c('item-not-found', {xmlns: 'urn:ietf:params:xml:ns:xmpp-stanzas'}).up()
  14535. .c('unknown-session', {xmlns: 'urn:xmpp:jingle:errors:1'});
  14536. this.connection.send(ack);
  14537. return true;
  14538. }
  14539. } else if (sess !== undefined) {
  14540. // existing session with same session id
  14541. // this might be out-of-order if the sess.peerjid is the same as from
  14542. ack.type = 'error';
  14543. ack.c('error', {type: 'cancel'})
  14544. .c('service-unavailable', {xmlns: 'urn:ietf:params:xml:ns:xmpp-stanzas'}).up();
  14545. console.warn('duplicate session id', sid);
  14546. this.connection.send(ack);
  14547. return true;
  14548. }
  14549. // FIXME: check for a defined action
  14550. this.connection.send(ack);
  14551. // see http://xmpp.org/extensions/xep-0166.html#concepts-session
  14552. switch (action) {
  14553. case 'session-initiate':
  14554. sess = new JingleSession(
  14555. $(iq).attr('to'), $(iq).find('jingle').attr('sid'),
  14556. this.connection, XMPP);
  14557. // configure session
  14558. sess.media_constraints = this.media_constraints;
  14559. sess.pc_constraints = this.pc_constraints;
  14560. sess.ice_config = this.ice_config;
  14561. sess.initiate(fromJid, false);
  14562. // FIXME: setRemoteDescription should only be done when this call is to be accepted
  14563. sess.setRemoteDescription($(iq).find('>jingle'), 'offer');
  14564. this.sessions[sess.sid] = sess;
  14565. this.jid2session[sess.peerjid] = sess;
  14566. // the callback should either
  14567. // .sendAnswer and .accept
  14568. // or .sendTerminate -- not necessarily synchronus
  14569. CallIncomingJingle(sess.sid, this.connection);
  14570. break;
  14571. case 'session-accept':
  14572. sess.setRemoteDescription($(iq).find('>jingle'), 'answer');
  14573. sess.accept();
  14574. $(document).trigger('callaccepted.jingle', [sess.sid]);
  14575. break;
  14576. case 'session-terminate':
  14577. // If this is not the focus sending the terminate, we have
  14578. // nothing more to do here.
  14579. if (Object.keys(this.sessions).length < 1
  14580. || !(this.sessions[Object.keys(this.sessions)[0]]
  14581. instanceof JingleSession))
  14582. {
  14583. break;
  14584. }
  14585. console.log('terminating...', sess.sid);
  14586. sess.terminate();
  14587. this.terminate(sess.sid);
  14588. if ($(iq).find('>jingle>reason').length) {
  14589. $(document).trigger('callterminated.jingle', [
  14590. sess.sid,
  14591. sess.peerjid,
  14592. $(iq).find('>jingle>reason>:first')[0].tagName,
  14593. $(iq).find('>jingle>reason>text').text()
  14594. ]);
  14595. } else {
  14596. $(document).trigger('callterminated.jingle',
  14597. [sess.sid, sess.peerjid]);
  14598. }
  14599. break;
  14600. case 'transport-info':
  14601. sess.addIceCandidate($(iq).find('>jingle>content'));
  14602. break;
  14603. case 'session-info':
  14604. var affected;
  14605. if ($(iq).find('>jingle>ringing[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').length) {
  14606. $(document).trigger('ringing.jingle', [sess.sid]);
  14607. } else if ($(iq).find('>jingle>mute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').length) {
  14608. affected = $(iq).find('>jingle>mute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').attr('name');
  14609. $(document).trigger('mute.jingle', [sess.sid, affected]);
  14610. } else if ($(iq).find('>jingle>unmute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').length) {
  14611. affected = $(iq).find('>jingle>unmute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').attr('name');
  14612. $(document).trigger('unmute.jingle', [sess.sid, affected]);
  14613. }
  14614. break;
  14615. case 'addsource': // FIXME: proprietary, un-jingleish
  14616. case 'source-add': // FIXME: proprietary
  14617. sess.addSource($(iq).find('>jingle>content'), fromJid);
  14618. break;
  14619. case 'removesource': // FIXME: proprietary, un-jingleish
  14620. case 'source-remove': // FIXME: proprietary
  14621. sess.removeSource($(iq).find('>jingle>content'), fromJid);
  14622. break;
  14623. default:
  14624. console.warn('jingle action not implemented', action);
  14625. break;
  14626. }
  14627. return true;
  14628. },
  14629. initiate: function (peerjid, myjid) { // initiate a new jinglesession to peerjid
  14630. var sess = new JingleSession(myjid || this.connection.jid,
  14631. Math.random().toString(36).substr(2, 12), // random string
  14632. this.connection, XMPP);
  14633. // configure session
  14634. sess.media_constraints = this.media_constraints;
  14635. sess.pc_constraints = this.pc_constraints;
  14636. sess.ice_config = this.ice_config;
  14637. sess.initiate(peerjid, true);
  14638. this.sessions[sess.sid] = sess;
  14639. this.jid2session[sess.peerjid] = sess;
  14640. sess.sendOffer();
  14641. return sess;
  14642. },
  14643. terminate: function (sid, reason, text) { // terminate by sessionid (or all sessions)
  14644. if (sid === null || sid === undefined) {
  14645. for (sid in this.sessions) {
  14646. if (this.sessions[sid].state != 'ended') {
  14647. this.sessions[sid].sendTerminate(reason || (!this.sessions[sid].active()) ? 'cancel' : null, text);
  14648. this.sessions[sid].terminate();
  14649. }
  14650. delete this.jid2session[this.sessions[sid].peerjid];
  14651. delete this.sessions[sid];
  14652. }
  14653. } else if (this.sessions.hasOwnProperty(sid)) {
  14654. if (this.sessions[sid].state != 'ended') {
  14655. this.sessions[sid].sendTerminate(reason || (!this.sessions[sid].active()) ? 'cancel' : null, text);
  14656. this.sessions[sid].terminate();
  14657. }
  14658. delete this.jid2session[this.sessions[sid].peerjid];
  14659. delete this.sessions[sid];
  14660. }
  14661. },
  14662. // Used to terminate a session when an unavailable presence is received.
  14663. terminateByJid: function (jid) {
  14664. if (this.jid2session.hasOwnProperty(jid)) {
  14665. var sess = this.jid2session[jid];
  14666. if (sess) {
  14667. sess.terminate();
  14668. console.log('peer went away silently', jid);
  14669. delete this.sessions[sess.sid];
  14670. delete this.jid2session[jid];
  14671. $(document).trigger('callterminated.jingle',
  14672. [sess.sid, jid], 'gone');
  14673. }
  14674. }
  14675. },
  14676. terminateRemoteByJid: function (jid, reason) {
  14677. if (this.jid2session.hasOwnProperty(jid)) {
  14678. var sess = this.jid2session[jid];
  14679. if (sess) {
  14680. sess.sendTerminate(reason || (!sess.active()) ? 'kick' : null);
  14681. sess.terminate();
  14682. console.log('terminate peer with jid', sess.sid, jid);
  14683. delete this.sessions[sess.sid];
  14684. delete this.jid2session[jid];
  14685. $(document).trigger('callterminated.jingle',
  14686. [sess.sid, jid, 'kicked']);
  14687. }
  14688. }
  14689. },
  14690. getStunAndTurnCredentials: function () {
  14691. // get stun and turn configuration from server via xep-0215
  14692. // uses time-limited credentials as described in
  14693. // http://tools.ietf.org/html/draft-uberti-behave-turn-rest-00
  14694. //
  14695. // see https://code.google.com/p/prosody-modules/source/browse/mod_turncredentials/mod_turncredentials.lua
  14696. // for a prosody module which implements this
  14697. //
  14698. // currently, this doesn't work with updateIce and therefore credentials with a long
  14699. // validity have to be fetched before creating the peerconnection
  14700. // TODO: implement refresh via updateIce as described in
  14701. // https://code.google.com/p/webrtc/issues/detail?id=1650
  14702. var self = this;
  14703. this.connection.sendIQ(
  14704. $iq({type: 'get', to: this.connection.domain})
  14705. .c('services', {xmlns: 'urn:xmpp:extdisco:1'}).c('service', {host: 'turn.' + this.connection.domain}),
  14706. function (res) {
  14707. var iceservers = [];
  14708. $(res).find('>services>service').each(function (idx, el) {
  14709. el = $(el);
  14710. var dict = {};
  14711. var type = el.attr('type');
  14712. switch (type) {
  14713. case 'stun':
  14714. dict.url = 'stun:' + el.attr('host');
  14715. if (el.attr('port')) {
  14716. dict.url += ':' + el.attr('port');
  14717. }
  14718. iceservers.push(dict);
  14719. break;
  14720. case 'turn':
  14721. case 'turns':
  14722. dict.url = type + ':';
  14723. if (el.attr('username')) { // https://code.google.com/p/webrtc/issues/detail?id=1508
  14724. if (navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./) && parseInt(navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./)[2], 10) < 28) {
  14725. dict.url += el.attr('username') + '@';
  14726. } else {
  14727. dict.username = el.attr('username'); // only works in M28
  14728. }
  14729. }
  14730. dict.url += el.attr('host');
  14731. if (el.attr('port') && el.attr('port') != '3478') {
  14732. dict.url += ':' + el.attr('port');
  14733. }
  14734. if (el.attr('transport') && el.attr('transport') != 'udp') {
  14735. dict.url += '?transport=' + el.attr('transport');
  14736. }
  14737. if (el.attr('password')) {
  14738. dict.credential = el.attr('password');
  14739. }
  14740. iceservers.push(dict);
  14741. break;
  14742. }
  14743. });
  14744. self.ice_config.iceServers = iceservers;
  14745. },
  14746. function (err) {
  14747. console.warn('getting turn credentials failed', err);
  14748. console.warn('is mod_turncredentials or similar installed?');
  14749. }
  14750. );
  14751. // implement push?
  14752. },
  14753. /**
  14754. * Populates the log data
  14755. */
  14756. populateData: function () {
  14757. var data = {};
  14758. Object.keys(this.sessions).forEach(function (sid) {
  14759. var session = this.sessions[sid];
  14760. if (session.peerconnection && session.peerconnection.updateLog) {
  14761. // FIXME: should probably be a .dump call
  14762. data["jingle_" + session.sid] = {
  14763. updateLog: session.peerconnection.updateLog,
  14764. stats: session.peerconnection.stats,
  14765. url: window.location.href
  14766. };
  14767. }
  14768. });
  14769. return data;
  14770. }
  14771. });
  14772. };
  14773. },{"../../service/xmpp/XMPPEvents":101,"./JingleSession":50}],59:[function(require,module,exports){
  14774. /* global Strophe */
  14775. module.exports = function () {
  14776. Strophe.addConnectionPlugin('logger', {
  14777. // logs raw stanzas and makes them available for download as JSON
  14778. connection: null,
  14779. log: [],
  14780. init: function (conn) {
  14781. this.connection = conn;
  14782. this.connection.rawInput = this.log_incoming.bind(this);
  14783. this.connection.rawOutput = this.log_outgoing.bind(this);
  14784. },
  14785. log_incoming: function (stanza) {
  14786. this.log.push([new Date().getTime(), 'incoming', stanza]);
  14787. },
  14788. log_outgoing: function (stanza) {
  14789. this.log.push([new Date().getTime(), 'outgoing', stanza]);
  14790. }
  14791. });
  14792. };
  14793. },{}],60:[function(require,module,exports){
  14794. /* global $, $iq, config, connection, focusMucJid, forceMuted,
  14795. setAudioMuted, Strophe */
  14796. /**
  14797. * Moderate connection plugin.
  14798. */
  14799. module.exports = function (XMPP) {
  14800. Strophe.addConnectionPlugin('moderate', {
  14801. connection: null,
  14802. init: function (conn) {
  14803. this.connection = conn;
  14804. this.connection.addHandler(this.onMute.bind(this),
  14805. 'http://jitsi.org/jitmeet/audio',
  14806. 'iq',
  14807. 'set',
  14808. null,
  14809. null);
  14810. },
  14811. setMute: function (jid, mute) {
  14812. console.info("set mute", mute);
  14813. var iqToFocus = $iq({to: this.connection.emuc.focusMucJid, type: 'set'})
  14814. .c('mute', {
  14815. xmlns: 'http://jitsi.org/jitmeet/audio',
  14816. jid: jid
  14817. })
  14818. .t(mute.toString())
  14819. .up();
  14820. this.connection.sendIQ(
  14821. iqToFocus,
  14822. function (result) {
  14823. console.log('set mute', result);
  14824. },
  14825. function (error) {
  14826. console.log('set mute error', error);
  14827. });
  14828. },
  14829. onMute: function (iq) {
  14830. var from = iq.getAttribute('from');
  14831. if (from !== this.connection.emuc.focusMucJid) {
  14832. console.warn("Ignored mute from non focus peer");
  14833. return false;
  14834. }
  14835. var mute = $(iq).find('mute');
  14836. if (mute.length) {
  14837. var doMuteAudio = mute.text() === "true";
  14838. APP.UI.setAudioMuted(doMuteAudio);
  14839. XMPP.forceMuted = doMuteAudio;
  14840. }
  14841. return true;
  14842. },
  14843. eject: function (jid) {
  14844. // We're not the focus, so can't terminate
  14845. //connection.jingle.terminateRemoteByJid(jid, 'kick');
  14846. this.connection.emuc.kick(jid);
  14847. }
  14848. });
  14849. }
  14850. },{}],61:[function(require,module,exports){
  14851. /* jshint -W117 */
  14852. module.exports = function() {
  14853. Strophe.addConnectionPlugin('rayo',
  14854. {
  14855. RAYO_XMLNS: 'urn:xmpp:rayo:1',
  14856. connection: null,
  14857. init: function (conn) {
  14858. this.connection = conn;
  14859. if (this.connection.disco) {
  14860. this.connection.disco.addFeature('urn:xmpp:rayo:client:1');
  14861. }
  14862. this.connection.addHandler(
  14863. this.onRayo.bind(this), this.RAYO_XMLNS, 'iq', 'set', null, null);
  14864. },
  14865. onRayo: function (iq) {
  14866. console.info("Rayo IQ", iq);
  14867. },
  14868. dial: function (to, from, roomName, roomPass) {
  14869. var self = this;
  14870. var req = $iq(
  14871. {
  14872. type: 'set',
  14873. to: this.connection.emuc.focusMucJid
  14874. }
  14875. );
  14876. req.c('dial',
  14877. {
  14878. xmlns: this.RAYO_XMLNS,
  14879. to: to,
  14880. from: from
  14881. });
  14882. req.c('header',
  14883. {
  14884. name: 'JvbRoomName',
  14885. value: roomName
  14886. }).up();
  14887. if (roomPass !== null && roomPass.length) {
  14888. req.c('header',
  14889. {
  14890. name: 'JvbRoomPassword',
  14891. value: roomPass
  14892. }).up();
  14893. }
  14894. this.connection.sendIQ(
  14895. req,
  14896. function (result) {
  14897. console.info('Dial result ', result);
  14898. var resource = $(result).find('ref').attr('uri');
  14899. this.call_resource = resource.substr('xmpp:'.length);
  14900. console.info(
  14901. "Received call resource: " + this.call_resource);
  14902. },
  14903. function (error) {
  14904. console.info('Dial error ', error);
  14905. }
  14906. );
  14907. },
  14908. hang_up: function () {
  14909. if (!this.call_resource) {
  14910. console.warn("No call in progress");
  14911. return;
  14912. }
  14913. var self = this;
  14914. var req = $iq(
  14915. {
  14916. type: 'set',
  14917. to: this.call_resource
  14918. }
  14919. );
  14920. req.c('hangup',
  14921. {
  14922. xmlns: this.RAYO_XMLNS
  14923. });
  14924. this.connection.sendIQ(
  14925. req,
  14926. function (result) {
  14927. console.info('Hangup result ', result);
  14928. self.call_resource = null;
  14929. },
  14930. function (error) {
  14931. console.info('Hangup error ', error);
  14932. self.call_resource = null;
  14933. }
  14934. );
  14935. }
  14936. }
  14937. );
  14938. };
  14939. },{}],62:[function(require,module,exports){
  14940. /**
  14941. * Strophe logger implementation. Logs from level WARN and above.
  14942. */
  14943. module.exports = function () {
  14944. Strophe.log = function (level, msg) {
  14945. switch (level) {
  14946. case Strophe.LogLevel.WARN:
  14947. console.warn("Strophe: " + msg);
  14948. break;
  14949. case Strophe.LogLevel.ERROR:
  14950. case Strophe.LogLevel.FATAL:
  14951. console.error("Strophe: " + msg);
  14952. break;
  14953. }
  14954. };
  14955. Strophe.getStatusString = function (status) {
  14956. switch (status) {
  14957. case Strophe.Status.ERROR:
  14958. return "ERROR";
  14959. case Strophe.Status.CONNECTING:
  14960. return "CONNECTING";
  14961. case Strophe.Status.CONNFAIL:
  14962. return "CONNFAIL";
  14963. case Strophe.Status.AUTHENTICATING:
  14964. return "AUTHENTICATING";
  14965. case Strophe.Status.AUTHFAIL:
  14966. return "AUTHFAIL";
  14967. case Strophe.Status.CONNECTED:
  14968. return "CONNECTED";
  14969. case Strophe.Status.DISCONNECTED:
  14970. return "DISCONNECTED";
  14971. case Strophe.Status.DISCONNECTING:
  14972. return "DISCONNECTING";
  14973. case Strophe.Status.ATTACHED:
  14974. return "ATTACHED";
  14975. default:
  14976. return "unknown";
  14977. }
  14978. };
  14979. };
  14980. },{}],63:[function(require,module,exports){
  14981. /* global $, APP, config, Strophe*/
  14982. var Moderator = require("./moderator");
  14983. var EventEmitter = require("events");
  14984. var Recording = require("./recording");
  14985. var SDP = require("./SDP");
  14986. var Settings = require("../settings/Settings");
  14987. var Pako = require("pako");
  14988. var StreamEventTypes = require("../../service/RTC/StreamEventTypes");
  14989. var RTCEvents = require("../../service/RTC/RTCEvents");
  14990. var UIEvents = require("../../service/UI/UIEvents");
  14991. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  14992. var eventEmitter = new EventEmitter();
  14993. var connection = null;
  14994. var authenticatedUser = false;
  14995. function connect(jid, password) {
  14996. connection = XMPP.createConnection();
  14997. Moderator.setConnection(connection);
  14998. if (connection.disco) {
  14999. // for chrome, add multistream cap
  15000. }
  15001. connection.jingle.pc_constraints = APP.RTC.getPCConstraints();
  15002. if (config.useIPv6) {
  15003. // https://code.google.com/p/webrtc/issues/detail?id=2828
  15004. if (!connection.jingle.pc_constraints.optional)
  15005. connection.jingle.pc_constraints.optional = [];
  15006. connection.jingle.pc_constraints.optional.push({googIPv6: true});
  15007. }
  15008. // Include user info in MUC presence
  15009. var settings = Settings.getSettings();
  15010. if (settings.email) {
  15011. connection.emuc.addEmailToPresence(settings.email);
  15012. }
  15013. if (settings.uid) {
  15014. connection.emuc.addUserIdToPresence(settings.uid);
  15015. }
  15016. if (settings.displayName) {
  15017. connection.emuc.addDisplayNameToPresence(settings.displayName);
  15018. }
  15019. var anonymousConnectionFailed = false;
  15020. connection.connect(jid, password, function (status, msg) {
  15021. console.log('Strophe status changed to',
  15022. Strophe.getStatusString(status));
  15023. if (status === Strophe.Status.CONNECTED) {
  15024. if (config.useStunTurn) {
  15025. connection.jingle.getStunAndTurnCredentials();
  15026. }
  15027. console.info("My Jabber ID: " + connection.jid);
  15028. if(password)
  15029. authenticatedUser = true;
  15030. maybeDoJoin();
  15031. } else if (status === Strophe.Status.CONNFAIL) {
  15032. if(msg === 'x-strophe-bad-non-anon-jid') {
  15033. anonymousConnectionFailed = true;
  15034. }
  15035. } else if (status === Strophe.Status.DISCONNECTED) {
  15036. if(anonymousConnectionFailed) {
  15037. // prompt user for username and password
  15038. XMPP.promptLogin();
  15039. }
  15040. } else if (status === Strophe.Status.AUTHFAIL) {
  15041. // wrong password or username, prompt user
  15042. XMPP.promptLogin();
  15043. }
  15044. });
  15045. }
  15046. function maybeDoJoin() {
  15047. if (connection && connection.connected &&
  15048. Strophe.getResourceFromJid(connection.jid)
  15049. && (APP.RTC.localAudio || APP.RTC.localVideo)) {
  15050. // .connected is true while connecting?
  15051. doJoin();
  15052. }
  15053. }
  15054. function doJoin() {
  15055. var roomName = APP.UI.generateRoomName();
  15056. Moderator.allocateConferenceFocus(
  15057. roomName, APP.UI.checkForNicknameAndJoin);
  15058. }
  15059. function initStrophePlugins()
  15060. {
  15061. require("./strophe.emuc")(XMPP, eventEmitter);
  15062. require("./strophe.jingle")(XMPP, eventEmitter);
  15063. require("./strophe.moderate")(XMPP);
  15064. require("./strophe.util")();
  15065. require("./strophe.rayo")();
  15066. require("./strophe.logger")();
  15067. }
  15068. function registerListeners() {
  15069. APP.RTC.addStreamListener(maybeDoJoin,
  15070. StreamEventTypes.EVENT_TYPE_LOCAL_CREATED);
  15071. APP.RTC.addListener(RTCEvents.AVAILABLE_DEVICES_CHANGED, function (devices) {
  15072. XMPP.addToPresence("devices", devices);
  15073. })
  15074. APP.UI.addListener(UIEvents.NICKNAME_CHANGED, function (nickname) {
  15075. XMPP.addToPresence("displayName", nickname);
  15076. });
  15077. }
  15078. function setupEvents() {
  15079. $(window).bind('beforeunload', function () {
  15080. if (connection && connection.connected) {
  15081. // ensure signout
  15082. $.ajax({
  15083. type: 'POST',
  15084. url: config.bosh,
  15085. async: false,
  15086. cache: false,
  15087. contentType: 'application/xml',
  15088. data: "<body rid='" + (connection.rid || connection._proto.rid)
  15089. + "' xmlns='http://jabber.org/protocol/httpbind' sid='"
  15090. + (connection.sid || connection._proto.sid)
  15091. + "' type='terminate'>" +
  15092. "<presence xmlns='jabber:client' type='unavailable'/>" +
  15093. "</body>",
  15094. success: function (data) {
  15095. console.log('signed out');
  15096. console.log(data);
  15097. },
  15098. error: function (XMLHttpRequest, textStatus, errorThrown) {
  15099. console.log('signout error',
  15100. textStatus + ' (' + errorThrown + ')');
  15101. }
  15102. });
  15103. }
  15104. XMPP.disposeConference(true);
  15105. });
  15106. }
  15107. var XMPP = {
  15108. getConnection: function(){ return connection; },
  15109. sessionTerminated: false,
  15110. /**
  15111. * XMPP connection status
  15112. */
  15113. Status: Strophe.Status,
  15114. /**
  15115. * Remembers if we were muted by the focus.
  15116. * @type {boolean}
  15117. */
  15118. forceMuted: false,
  15119. start: function () {
  15120. setupEvents();
  15121. initStrophePlugins();
  15122. registerListeners();
  15123. Moderator.init(this, eventEmitter);
  15124. var configDomain = config.hosts.anonymousdomain || config.hosts.domain;
  15125. // Force authenticated domain if room is appended with '?login=true'
  15126. if (config.hosts.anonymousdomain &&
  15127. window.location.search.indexOf("login=true") !== -1) {
  15128. configDomain = config.hosts.domain;
  15129. }
  15130. var jid = configDomain || window.location.hostname;
  15131. connect(jid, null);
  15132. },
  15133. createConnection: function () {
  15134. var bosh = config.bosh || '/http-bind';
  15135. return new Strophe.Connection(bosh);
  15136. },
  15137. getStatusString: function (status) {
  15138. return Strophe.getStatusString(status);
  15139. },
  15140. promptLogin: function () {
  15141. // FIXME: re-use LoginDialog which supports retries
  15142. APP.UI.showLoginPopup(connect);
  15143. },
  15144. joinRoom: function(roomName, useNicks, nick)
  15145. {
  15146. var roomjid;
  15147. roomjid = roomName;
  15148. if (useNicks) {
  15149. if (nick) {
  15150. roomjid += '/' + nick;
  15151. } else {
  15152. roomjid += '/' + Strophe.getNodeFromJid(connection.jid);
  15153. }
  15154. } else {
  15155. var tmpJid = Strophe.getNodeFromJid(connection.jid);
  15156. if(!authenticatedUser)
  15157. tmpJid = tmpJid.substr(0, 8);
  15158. roomjid += '/' + tmpJid;
  15159. }
  15160. connection.emuc.doJoin(roomjid);
  15161. },
  15162. myJid: function () {
  15163. if(!connection)
  15164. return null;
  15165. return connection.emuc.myroomjid;
  15166. },
  15167. myResource: function () {
  15168. if(!connection || ! connection.emuc.myroomjid)
  15169. return null;
  15170. return Strophe.getResourceFromJid(connection.emuc.myroomjid);
  15171. },
  15172. disposeConference: function (onUnload) {
  15173. eventEmitter.emit(XMPPEvents.DISPOSE_CONFERENCE, onUnload);
  15174. var handler = connection.jingle.activecall;
  15175. if (handler && handler.peerconnection) {
  15176. // FIXME: probably removing streams is not required and close() should
  15177. // be enough
  15178. if (APP.RTC.localAudio) {
  15179. handler.peerconnection.removeStream(
  15180. APP.RTC.localAudio.getOriginalStream(), onUnload);
  15181. }
  15182. if (APP.RTC.localVideo) {
  15183. handler.peerconnection.removeStream(
  15184. APP.RTC.localVideo.getOriginalStream(), onUnload);
  15185. }
  15186. handler.peerconnection.close();
  15187. }
  15188. connection.jingle.activecall = null;
  15189. if(!onUnload)
  15190. {
  15191. this.sessionTerminated = true;
  15192. connection.emuc.doLeave();
  15193. }
  15194. },
  15195. addListener: function(type, listener)
  15196. {
  15197. eventEmitter.on(type, listener);
  15198. },
  15199. removeListener: function (type, listener) {
  15200. eventEmitter.removeListener(type, listener);
  15201. },
  15202. allocateConferenceFocus: function(roomName, callback) {
  15203. Moderator.allocateConferenceFocus(roomName, callback);
  15204. },
  15205. getLoginUrl: function (roomName, callback) {
  15206. Moderator.getLoginUrl(roomName, callback);
  15207. },
  15208. getPopupLoginUrl: function (roomName, callback) {
  15209. Moderator.getPopupLoginUrl(roomName, callback);
  15210. },
  15211. isModerator: function () {
  15212. return Moderator.isModerator();
  15213. },
  15214. isSipGatewayEnabled: function () {
  15215. return Moderator.isSipGatewayEnabled();
  15216. },
  15217. isExternalAuthEnabled: function () {
  15218. return Moderator.isExternalAuthEnabled();
  15219. },
  15220. switchStreams: function (stream, oldStream, callback) {
  15221. if (connection && connection.jingle.activecall) {
  15222. // FIXME: will block switchInProgress on true value in case of exception
  15223. connection.jingle.activecall.switchStreams(stream, oldStream, callback);
  15224. } else {
  15225. // We are done immediately
  15226. console.warn("No conference handler or conference not started yet");
  15227. callback();
  15228. }
  15229. },
  15230. sendVideoInfoPresence: function (mute) {
  15231. connection.emuc.addVideoInfoToPresence(mute);
  15232. connection.emuc.sendPresence();
  15233. },
  15234. setVideoMute: function (mute, callback, options) {
  15235. if(!connection)
  15236. return;
  15237. var self = this;
  15238. var localCallback = function (mute) {
  15239. self.sendVideoInfoPresence(mute);
  15240. return callback(mute);
  15241. };
  15242. if(connection.jingle.activecall)
  15243. {
  15244. connection.jingle.activecall.setVideoMute(
  15245. mute, localCallback, options);
  15246. }
  15247. else {
  15248. localCallback(mute);
  15249. }
  15250. },
  15251. setAudioMute: function (mute, callback) {
  15252. if (!(connection && APP.RTC.localAudio)) {
  15253. return false;
  15254. }
  15255. if (this.forceMuted && !mute) {
  15256. console.info("Asking focus for unmute");
  15257. connection.moderate.setMute(connection.emuc.myroomjid, mute);
  15258. // FIXME: wait for result before resetting muted status
  15259. this.forceMuted = false;
  15260. }
  15261. if (mute == APP.RTC.localAudio.isMuted()) {
  15262. // Nothing to do
  15263. return true;
  15264. }
  15265. // It is not clear what is the right way to handle multiple tracks.
  15266. // So at least make sure that they are all muted or all unmuted and
  15267. // that we send presence just once.
  15268. APP.RTC.localAudio.mute();
  15269. // isMuted is the opposite of audioEnabled
  15270. connection.emuc.addAudioInfoToPresence(mute);
  15271. connection.emuc.sendPresence();
  15272. callback();
  15273. return true;
  15274. },
  15275. // Really mute video, i.e. dont even send black frames
  15276. muteVideo: function (pc, unmute) {
  15277. // FIXME: this probably needs another of those lovely state safeguards...
  15278. // which checks for iceconn == connected and sigstate == stable
  15279. pc.setRemoteDescription(pc.remoteDescription,
  15280. function () {
  15281. pc.createAnswer(
  15282. function (answer) {
  15283. var sdp = new SDP(answer.sdp);
  15284. if (sdp.media.length > 1) {
  15285. if (unmute)
  15286. sdp.media[1] = sdp.media[1].replace('a=recvonly', 'a=sendrecv');
  15287. else
  15288. sdp.media[1] = sdp.media[1].replace('a=sendrecv', 'a=recvonly');
  15289. sdp.raw = sdp.session + sdp.media.join('');
  15290. answer.sdp = sdp.raw;
  15291. }
  15292. pc.setLocalDescription(answer,
  15293. function () {
  15294. console.log('mute SLD ok');
  15295. },
  15296. function (error) {
  15297. console.log('mute SLD error');
  15298. APP.UI.messageHandler.showError("dialog.error",
  15299. "dialog.SLDFailure");
  15300. }
  15301. );
  15302. },
  15303. function (error) {
  15304. console.log(error);
  15305. APP.UI.messageHandler.showError();
  15306. }
  15307. );
  15308. },
  15309. function (error) {
  15310. console.log('muteVideo SRD error');
  15311. APP.UI.messageHandler.showError("dialog.error",
  15312. "dialog.SRDFailure");
  15313. }
  15314. );
  15315. },
  15316. toggleRecording: function (tokenEmptyCallback,
  15317. startingCallback, startedCallback) {
  15318. Recording.toggleRecording(tokenEmptyCallback,
  15319. startingCallback, startedCallback, connection);
  15320. },
  15321. addToPresence: function (name, value, dontSend) {
  15322. switch (name)
  15323. {
  15324. case "displayName":
  15325. connection.emuc.addDisplayNameToPresence(value);
  15326. break;
  15327. case "etherpad":
  15328. connection.emuc.addEtherpadToPresence(value);
  15329. break;
  15330. case "prezi":
  15331. connection.emuc.addPreziToPresence(value, 0);
  15332. break;
  15333. case "preziSlide":
  15334. connection.emuc.addCurrentSlideToPresence(value);
  15335. break;
  15336. case "connectionQuality":
  15337. connection.emuc.addConnectionInfoToPresence(value);
  15338. break;
  15339. case "email":
  15340. connection.emuc.addEmailToPresence(value);
  15341. break;
  15342. case "devices":
  15343. connection.emuc.addDevicesToPresence(value);
  15344. break;
  15345. default :
  15346. console.log("Unknown tag for presence: " + name);
  15347. return;
  15348. }
  15349. if (!dontSend)
  15350. connection.emuc.sendPresence();
  15351. },
  15352. /**
  15353. * Sends 'data' as a log message to the focus. Returns true iff a message
  15354. * was sent.
  15355. * @param data
  15356. * @returns {boolean} true iff a message was sent.
  15357. */
  15358. sendLogs: function (data) {
  15359. if(!connection.emuc.focusMucJid)
  15360. return false;
  15361. var deflate = true;
  15362. var content = JSON.stringify(data);
  15363. if (deflate) {
  15364. content = String.fromCharCode.apply(null, Pako.deflateRaw(content));
  15365. }
  15366. content = Base64.encode(content);
  15367. // XEP-0337-ish
  15368. var message = $msg({to: connection.emuc.focusMucJid, type: 'normal'});
  15369. message.c('log', { xmlns: 'urn:xmpp:eventlog',
  15370. id: 'PeerConnectionStats'});
  15371. message.c('message').t(content).up();
  15372. if (deflate) {
  15373. message.c('tag', {name: "deflated", value: "true"}).up();
  15374. }
  15375. message.up();
  15376. connection.send(message);
  15377. return true;
  15378. },
  15379. populateData: function () {
  15380. var data = {};
  15381. if (connection.jingle) {
  15382. data = connection.jingle.populateData();
  15383. }
  15384. return data;
  15385. },
  15386. getLogger: function () {
  15387. if(connection.logger)
  15388. return connection.logger.log;
  15389. return null;
  15390. },
  15391. getPrezi: function () {
  15392. return connection.emuc.getPrezi(this.myJid());
  15393. },
  15394. removePreziFromPresence: function () {
  15395. connection.emuc.removePreziFromPresence();
  15396. connection.emuc.sendPresence();
  15397. },
  15398. sendChatMessage: function (message, nickname) {
  15399. connection.emuc.sendMessage(message, nickname);
  15400. },
  15401. setSubject: function (topic) {
  15402. connection.emuc.setSubject(topic);
  15403. },
  15404. lockRoom: function (key, onSuccess, onError, onNotSupported) {
  15405. connection.emuc.lockRoom(key, onSuccess, onError, onNotSupported);
  15406. },
  15407. dial: function (to, from, roomName,roomPass) {
  15408. connection.rayo.dial(to, from, roomName,roomPass);
  15409. },
  15410. setMute: function (jid, mute) {
  15411. connection.moderate.setMute(jid, mute);
  15412. },
  15413. eject: function (jid) {
  15414. connection.moderate.eject(jid);
  15415. },
  15416. logout: function (callback) {
  15417. Moderator.logout(callback);
  15418. },
  15419. findJidFromResource: function (resource) {
  15420. return connection.emuc.findJidFromResource(resource);
  15421. },
  15422. getMembers: function () {
  15423. return connection.emuc.members;
  15424. },
  15425. getJidFromSSRC: function (ssrc) {
  15426. if(!connection)
  15427. return null;
  15428. return connection.emuc.ssrc2jid[ssrc];
  15429. },
  15430. getMUCJoined: function () {
  15431. return connection.emuc.joined;
  15432. },
  15433. getSessions: function () {
  15434. return connection.jingle.sessions;
  15435. },
  15436. removeStream: function (stream) {
  15437. if(!connection || !connection.jingle.activecall ||
  15438. !connection.jingle.activecall.peerconnection)
  15439. return;
  15440. connection.jingle.activecall.peerconnection.removeStream(stream);
  15441. }
  15442. };
  15443. module.exports = XMPP;
  15444. },{"../../service/RTC/RTCEvents":92,"../../service/RTC/StreamEventTypes":94,"../../service/UI/UIEvents":95,"../../service/xmpp/XMPPEvents":101,"../settings/Settings":40,"./SDP":51,"./moderator":55,"./recording":56,"./strophe.emuc":57,"./strophe.jingle":58,"./strophe.logger":59,"./strophe.moderate":60,"./strophe.rayo":61,"./strophe.util":62,"events":102,"pako":66}],64:[function(require,module,exports){
  15445. (function (process){
  15446. /*!
  15447. * async
  15448. * https://github.com/caolan/async
  15449. *
  15450. * Copyright 2010-2014 Caolan McMahon
  15451. * Released under the MIT license
  15452. */
  15453. /*jshint onevar: false, indent:4 */
  15454. /*global setImmediate: false, setTimeout: false, console: false */
  15455. (function () {
  15456. var async = {};
  15457. // global on the server, window in the browser
  15458. var root, previous_async;
  15459. root = this;
  15460. if (root != null) {
  15461. previous_async = root.async;
  15462. }
  15463. async.noConflict = function () {
  15464. root.async = previous_async;
  15465. return async;
  15466. };
  15467. function only_once(fn) {
  15468. var called = false;
  15469. return function() {
  15470. if (called) throw new Error("Callback was already called.");
  15471. called = true;
  15472. fn.apply(root, arguments);
  15473. }
  15474. }
  15475. //// cross-browser compatiblity functions ////
  15476. var _toString = Object.prototype.toString;
  15477. var _isArray = Array.isArray || function (obj) {
  15478. return _toString.call(obj) === '[object Array]';
  15479. };
  15480. var _each = function (arr, iterator) {
  15481. if (arr.forEach) {
  15482. return arr.forEach(iterator);
  15483. }
  15484. for (var i = 0; i < arr.length; i += 1) {
  15485. iterator(arr[i], i, arr);
  15486. }
  15487. };
  15488. var _map = function (arr, iterator) {
  15489. if (arr.map) {
  15490. return arr.map(iterator);
  15491. }
  15492. var results = [];
  15493. _each(arr, function (x, i, a) {
  15494. results.push(iterator(x, i, a));
  15495. });
  15496. return results;
  15497. };
  15498. var _reduce = function (arr, iterator, memo) {
  15499. if (arr.reduce) {
  15500. return arr.reduce(iterator, memo);
  15501. }
  15502. _each(arr, function (x, i, a) {
  15503. memo = iterator(memo, x, i, a);
  15504. });
  15505. return memo;
  15506. };
  15507. var _keys = function (obj) {
  15508. if (Object.keys) {
  15509. return Object.keys(obj);
  15510. }
  15511. var keys = [];
  15512. for (var k in obj) {
  15513. if (obj.hasOwnProperty(k)) {
  15514. keys.push(k);
  15515. }
  15516. }
  15517. return keys;
  15518. };
  15519. //// exported async module functions ////
  15520. //// nextTick implementation with browser-compatible fallback ////
  15521. if (typeof process === 'undefined' || !(process.nextTick)) {
  15522. if (typeof setImmediate === 'function') {
  15523. async.nextTick = function (fn) {
  15524. // not a direct alias for IE10 compatibility
  15525. setImmediate(fn);
  15526. };
  15527. async.setImmediate = async.nextTick;
  15528. }
  15529. else {
  15530. async.nextTick = function (fn) {
  15531. setTimeout(fn, 0);
  15532. };
  15533. async.setImmediate = async.nextTick;
  15534. }
  15535. }
  15536. else {
  15537. async.nextTick = process.nextTick;
  15538. if (typeof setImmediate !== 'undefined') {
  15539. async.setImmediate = function (fn) {
  15540. // not a direct alias for IE10 compatibility
  15541. setImmediate(fn);
  15542. };
  15543. }
  15544. else {
  15545. async.setImmediate = async.nextTick;
  15546. }
  15547. }
  15548. async.each = function (arr, iterator, callback) {
  15549. callback = callback || function () {};
  15550. if (!arr.length) {
  15551. return callback();
  15552. }
  15553. var completed = 0;
  15554. _each(arr, function (x) {
  15555. iterator(x, only_once(done) );
  15556. });
  15557. function done(err) {
  15558. if (err) {
  15559. callback(err);
  15560. callback = function () {};
  15561. }
  15562. else {
  15563. completed += 1;
  15564. if (completed >= arr.length) {
  15565. callback();
  15566. }
  15567. }
  15568. }
  15569. };
  15570. async.forEach = async.each;
  15571. async.eachSeries = function (arr, iterator, callback) {
  15572. callback = callback || function () {};
  15573. if (!arr.length) {
  15574. return callback();
  15575. }
  15576. var completed = 0;
  15577. var iterate = function () {
  15578. iterator(arr[completed], function (err) {
  15579. if (err) {
  15580. callback(err);
  15581. callback = function () {};
  15582. }
  15583. else {
  15584. completed += 1;
  15585. if (completed >= arr.length) {
  15586. callback();
  15587. }
  15588. else {
  15589. iterate();
  15590. }
  15591. }
  15592. });
  15593. };
  15594. iterate();
  15595. };
  15596. async.forEachSeries = async.eachSeries;
  15597. async.eachLimit = function (arr, limit, iterator, callback) {
  15598. var fn = _eachLimit(limit);
  15599. fn.apply(null, [arr, iterator, callback]);
  15600. };
  15601. async.forEachLimit = async.eachLimit;
  15602. var _eachLimit = function (limit) {
  15603. return function (arr, iterator, callback) {
  15604. callback = callback || function () {};
  15605. if (!arr.length || limit <= 0) {
  15606. return callback();
  15607. }
  15608. var completed = 0;
  15609. var started = 0;
  15610. var running = 0;
  15611. (function replenish () {
  15612. if (completed >= arr.length) {
  15613. return callback();
  15614. }
  15615. while (running < limit && started < arr.length) {
  15616. started += 1;
  15617. running += 1;
  15618. iterator(arr[started - 1], function (err) {
  15619. if (err) {
  15620. callback(err);
  15621. callback = function () {};
  15622. }
  15623. else {
  15624. completed += 1;
  15625. running -= 1;
  15626. if (completed >= arr.length) {
  15627. callback();
  15628. }
  15629. else {
  15630. replenish();
  15631. }
  15632. }
  15633. });
  15634. }
  15635. })();
  15636. };
  15637. };
  15638. var doParallel = function (fn) {
  15639. return function () {
  15640. var args = Array.prototype.slice.call(arguments);
  15641. return fn.apply(null, [async.each].concat(args));
  15642. };
  15643. };
  15644. var doParallelLimit = function(limit, fn) {
  15645. return function () {
  15646. var args = Array.prototype.slice.call(arguments);
  15647. return fn.apply(null, [_eachLimit(limit)].concat(args));
  15648. };
  15649. };
  15650. var doSeries = function (fn) {
  15651. return function () {
  15652. var args = Array.prototype.slice.call(arguments);
  15653. return fn.apply(null, [async.eachSeries].concat(args));
  15654. };
  15655. };
  15656. var _asyncMap = function (eachfn, arr, iterator, callback) {
  15657. arr = _map(arr, function (x, i) {
  15658. return {index: i, value: x};
  15659. });
  15660. if (!callback) {
  15661. eachfn(arr, function (x, callback) {
  15662. iterator(x.value, function (err) {
  15663. callback(err);
  15664. });
  15665. });
  15666. } else {
  15667. var results = [];
  15668. eachfn(arr, function (x, callback) {
  15669. iterator(x.value, function (err, v) {
  15670. results[x.index] = v;
  15671. callback(err);
  15672. });
  15673. }, function (err) {
  15674. callback(err, results);
  15675. });
  15676. }
  15677. };
  15678. async.map = doParallel(_asyncMap);
  15679. async.mapSeries = doSeries(_asyncMap);
  15680. async.mapLimit = function (arr, limit, iterator, callback) {
  15681. return _mapLimit(limit)(arr, iterator, callback);
  15682. };
  15683. var _mapLimit = function(limit) {
  15684. return doParallelLimit(limit, _asyncMap);
  15685. };
  15686. // reduce only has a series version, as doing reduce in parallel won't
  15687. // work in many situations.
  15688. async.reduce = function (arr, memo, iterator, callback) {
  15689. async.eachSeries(arr, function (x, callback) {
  15690. iterator(memo, x, function (err, v) {
  15691. memo = v;
  15692. callback(err);
  15693. });
  15694. }, function (err) {
  15695. callback(err, memo);
  15696. });
  15697. };
  15698. // inject alias
  15699. async.inject = async.reduce;
  15700. // foldl alias
  15701. async.foldl = async.reduce;
  15702. async.reduceRight = function (arr, memo, iterator, callback) {
  15703. var reversed = _map(arr, function (x) {
  15704. return x;
  15705. }).reverse();
  15706. async.reduce(reversed, memo, iterator, callback);
  15707. };
  15708. // foldr alias
  15709. async.foldr = async.reduceRight;
  15710. var _filter = function (eachfn, arr, iterator, callback) {
  15711. var results = [];
  15712. arr = _map(arr, function (x, i) {
  15713. return {index: i, value: x};
  15714. });
  15715. eachfn(arr, function (x, callback) {
  15716. iterator(x.value, function (v) {
  15717. if (v) {
  15718. results.push(x);
  15719. }
  15720. callback();
  15721. });
  15722. }, function (err) {
  15723. callback(_map(results.sort(function (a, b) {
  15724. return a.index - b.index;
  15725. }), function (x) {
  15726. return x.value;
  15727. }));
  15728. });
  15729. };
  15730. async.filter = doParallel(_filter);
  15731. async.filterSeries = doSeries(_filter);
  15732. // select alias
  15733. async.select = async.filter;
  15734. async.selectSeries = async.filterSeries;
  15735. var _reject = function (eachfn, arr, iterator, callback) {
  15736. var results = [];
  15737. arr = _map(arr, function (x, i) {
  15738. return {index: i, value: x};
  15739. });
  15740. eachfn(arr, function (x, callback) {
  15741. iterator(x.value, function (v) {
  15742. if (!v) {
  15743. results.push(x);
  15744. }
  15745. callback();
  15746. });
  15747. }, function (err) {
  15748. callback(_map(results.sort(function (a, b) {
  15749. return a.index - b.index;
  15750. }), function (x) {
  15751. return x.value;
  15752. }));
  15753. });
  15754. };
  15755. async.reject = doParallel(_reject);
  15756. async.rejectSeries = doSeries(_reject);
  15757. var _detect = function (eachfn, arr, iterator, main_callback) {
  15758. eachfn(arr, function (x, callback) {
  15759. iterator(x, function (result) {
  15760. if (result) {
  15761. main_callback(x);
  15762. main_callback = function () {};
  15763. }
  15764. else {
  15765. callback();
  15766. }
  15767. });
  15768. }, function (err) {
  15769. main_callback();
  15770. });
  15771. };
  15772. async.detect = doParallel(_detect);
  15773. async.detectSeries = doSeries(_detect);
  15774. async.some = function (arr, iterator, main_callback) {
  15775. async.each(arr, function (x, callback) {
  15776. iterator(x, function (v) {
  15777. if (v) {
  15778. main_callback(true);
  15779. main_callback = function () {};
  15780. }
  15781. callback();
  15782. });
  15783. }, function (err) {
  15784. main_callback(false);
  15785. });
  15786. };
  15787. // any alias
  15788. async.any = async.some;
  15789. async.every = function (arr, iterator, main_callback) {
  15790. async.each(arr, function (x, callback) {
  15791. iterator(x, function (v) {
  15792. if (!v) {
  15793. main_callback(false);
  15794. main_callback = function () {};
  15795. }
  15796. callback();
  15797. });
  15798. }, function (err) {
  15799. main_callback(true);
  15800. });
  15801. };
  15802. // all alias
  15803. async.all = async.every;
  15804. async.sortBy = function (arr, iterator, callback) {
  15805. async.map(arr, function (x, callback) {
  15806. iterator(x, function (err, criteria) {
  15807. if (err) {
  15808. callback(err);
  15809. }
  15810. else {
  15811. callback(null, {value: x, criteria: criteria});
  15812. }
  15813. });
  15814. }, function (err, results) {
  15815. if (err) {
  15816. return callback(err);
  15817. }
  15818. else {
  15819. var fn = function (left, right) {
  15820. var a = left.criteria, b = right.criteria;
  15821. return a < b ? -1 : a > b ? 1 : 0;
  15822. };
  15823. callback(null, _map(results.sort(fn), function (x) {
  15824. return x.value;
  15825. }));
  15826. }
  15827. });
  15828. };
  15829. async.auto = function (tasks, callback) {
  15830. callback = callback || function () {};
  15831. var keys = _keys(tasks);
  15832. var remainingTasks = keys.length
  15833. if (!remainingTasks) {
  15834. return callback();
  15835. }
  15836. var results = {};
  15837. var listeners = [];
  15838. var addListener = function (fn) {
  15839. listeners.unshift(fn);
  15840. };
  15841. var removeListener = function (fn) {
  15842. for (var i = 0; i < listeners.length; i += 1) {
  15843. if (listeners[i] === fn) {
  15844. listeners.splice(i, 1);
  15845. return;
  15846. }
  15847. }
  15848. };
  15849. var taskComplete = function () {
  15850. remainingTasks--
  15851. _each(listeners.slice(0), function (fn) {
  15852. fn();
  15853. });
  15854. };
  15855. addListener(function () {
  15856. if (!remainingTasks) {
  15857. var theCallback = callback;
  15858. // prevent final callback from calling itself if it errors
  15859. callback = function () {};
  15860. theCallback(null, results);
  15861. }
  15862. });
  15863. _each(keys, function (k) {
  15864. var task = _isArray(tasks[k]) ? tasks[k]: [tasks[k]];
  15865. var taskCallback = function (err) {
  15866. var args = Array.prototype.slice.call(arguments, 1);
  15867. if (args.length <= 1) {
  15868. args = args[0];
  15869. }
  15870. if (err) {
  15871. var safeResults = {};
  15872. _each(_keys(results), function(rkey) {
  15873. safeResults[rkey] = results[rkey];
  15874. });
  15875. safeResults[k] = args;
  15876. callback(err, safeResults);
  15877. // stop subsequent errors hitting callback multiple times
  15878. callback = function () {};
  15879. }
  15880. else {
  15881. results[k] = args;
  15882. async.setImmediate(taskComplete);
  15883. }
  15884. };
  15885. var requires = task.slice(0, Math.abs(task.length - 1)) || [];
  15886. var ready = function () {
  15887. return _reduce(requires, function (a, x) {
  15888. return (a && results.hasOwnProperty(x));
  15889. }, true) && !results.hasOwnProperty(k);
  15890. };
  15891. if (ready()) {
  15892. task[task.length - 1](taskCallback, results);
  15893. }
  15894. else {
  15895. var listener = function () {
  15896. if (ready()) {
  15897. removeListener(listener);
  15898. task[task.length - 1](taskCallback, results);
  15899. }
  15900. };
  15901. addListener(listener);
  15902. }
  15903. });
  15904. };
  15905. async.retry = function(times, task, callback) {
  15906. var DEFAULT_TIMES = 5;
  15907. var attempts = [];
  15908. // Use defaults if times not passed
  15909. if (typeof times === 'function') {
  15910. callback = task;
  15911. task = times;
  15912. times = DEFAULT_TIMES;
  15913. }
  15914. // Make sure times is a number
  15915. times = parseInt(times, 10) || DEFAULT_TIMES;
  15916. var wrappedTask = function(wrappedCallback, wrappedResults) {
  15917. var retryAttempt = function(task, finalAttempt) {
  15918. return function(seriesCallback) {
  15919. task(function(err, result){
  15920. seriesCallback(!err || finalAttempt, {err: err, result: result});
  15921. }, wrappedResults);
  15922. };
  15923. };
  15924. while (times) {
  15925. attempts.push(retryAttempt(task, !(times-=1)));
  15926. }
  15927. async.series(attempts, function(done, data){
  15928. data = data[data.length - 1];
  15929. (wrappedCallback || callback)(data.err, data.result);
  15930. });
  15931. }
  15932. // If a callback is passed, run this as a controll flow
  15933. return callback ? wrappedTask() : wrappedTask
  15934. };
  15935. async.waterfall = function (tasks, callback) {
  15936. callback = callback || function () {};
  15937. if (!_isArray(tasks)) {
  15938. var err = new Error('First argument to waterfall must be an array of functions');
  15939. return callback(err);
  15940. }
  15941. if (!tasks.length) {
  15942. return callback();
  15943. }
  15944. var wrapIterator = function (iterator) {
  15945. return function (err) {
  15946. if (err) {
  15947. callback.apply(null, arguments);
  15948. callback = function () {};
  15949. }
  15950. else {
  15951. var args = Array.prototype.slice.call(arguments, 1);
  15952. var next = iterator.next();
  15953. if (next) {
  15954. args.push(wrapIterator(next));
  15955. }
  15956. else {
  15957. args.push(callback);
  15958. }
  15959. async.setImmediate(function () {
  15960. iterator.apply(null, args);
  15961. });
  15962. }
  15963. };
  15964. };
  15965. wrapIterator(async.iterator(tasks))();
  15966. };
  15967. var _parallel = function(eachfn, tasks, callback) {
  15968. callback = callback || function () {};
  15969. if (_isArray(tasks)) {
  15970. eachfn.map(tasks, function (fn, callback) {
  15971. if (fn) {
  15972. fn(function (err) {
  15973. var args = Array.prototype.slice.call(arguments, 1);
  15974. if (args.length <= 1) {
  15975. args = args[0];
  15976. }
  15977. callback.call(null, err, args);
  15978. });
  15979. }
  15980. }, callback);
  15981. }
  15982. else {
  15983. var results = {};
  15984. eachfn.each(_keys(tasks), function (k, callback) {
  15985. tasks[k](function (err) {
  15986. var args = Array.prototype.slice.call(arguments, 1);
  15987. if (args.length <= 1) {
  15988. args = args[0];
  15989. }
  15990. results[k] = args;
  15991. callback(err);
  15992. });
  15993. }, function (err) {
  15994. callback(err, results);
  15995. });
  15996. }
  15997. };
  15998. async.parallel = function (tasks, callback) {
  15999. _parallel({ map: async.map, each: async.each }, tasks, callback);
  16000. };
  16001. async.parallelLimit = function(tasks, limit, callback) {
  16002. _parallel({ map: _mapLimit(limit), each: _eachLimit(limit) }, tasks, callback);
  16003. };
  16004. async.series = function (tasks, callback) {
  16005. callback = callback || function () {};
  16006. if (_isArray(tasks)) {
  16007. async.mapSeries(tasks, function (fn, callback) {
  16008. if (fn) {
  16009. fn(function (err) {
  16010. var args = Array.prototype.slice.call(arguments, 1);
  16011. if (args.length <= 1) {
  16012. args = args[0];
  16013. }
  16014. callback.call(null, err, args);
  16015. });
  16016. }
  16017. }, callback);
  16018. }
  16019. else {
  16020. var results = {};
  16021. async.eachSeries(_keys(tasks), function (k, callback) {
  16022. tasks[k](function (err) {
  16023. var args = Array.prototype.slice.call(arguments, 1);
  16024. if (args.length <= 1) {
  16025. args = args[0];
  16026. }
  16027. results[k] = args;
  16028. callback(err);
  16029. });
  16030. }, function (err) {
  16031. callback(err, results);
  16032. });
  16033. }
  16034. };
  16035. async.iterator = function (tasks) {
  16036. var makeCallback = function (index) {
  16037. var fn = function () {
  16038. if (tasks.length) {
  16039. tasks[index].apply(null, arguments);
  16040. }
  16041. return fn.next();
  16042. };
  16043. fn.next = function () {
  16044. return (index < tasks.length - 1) ? makeCallback(index + 1): null;
  16045. };
  16046. return fn;
  16047. };
  16048. return makeCallback(0);
  16049. };
  16050. async.apply = function (fn) {
  16051. var args = Array.prototype.slice.call(arguments, 1);
  16052. return function () {
  16053. return fn.apply(
  16054. null, args.concat(Array.prototype.slice.call(arguments))
  16055. );
  16056. };
  16057. };
  16058. var _concat = function (eachfn, arr, fn, callback) {
  16059. var r = [];
  16060. eachfn(arr, function (x, cb) {
  16061. fn(x, function (err, y) {
  16062. r = r.concat(y || []);
  16063. cb(err);
  16064. });
  16065. }, function (err) {
  16066. callback(err, r);
  16067. });
  16068. };
  16069. async.concat = doParallel(_concat);
  16070. async.concatSeries = doSeries(_concat);
  16071. async.whilst = function (test, iterator, callback) {
  16072. if (test()) {
  16073. iterator(function (err) {
  16074. if (err) {
  16075. return callback(err);
  16076. }
  16077. async.whilst(test, iterator, callback);
  16078. });
  16079. }
  16080. else {
  16081. callback();
  16082. }
  16083. };
  16084. async.doWhilst = function (iterator, test, callback) {
  16085. iterator(function (err) {
  16086. if (err) {
  16087. return callback(err);
  16088. }
  16089. var args = Array.prototype.slice.call(arguments, 1);
  16090. if (test.apply(null, args)) {
  16091. async.doWhilst(iterator, test, callback);
  16092. }
  16093. else {
  16094. callback();
  16095. }
  16096. });
  16097. };
  16098. async.until = function (test, iterator, callback) {
  16099. if (!test()) {
  16100. iterator(function (err) {
  16101. if (err) {
  16102. return callback(err);
  16103. }
  16104. async.until(test, iterator, callback);
  16105. });
  16106. }
  16107. else {
  16108. callback();
  16109. }
  16110. };
  16111. async.doUntil = function (iterator, test, callback) {
  16112. iterator(function (err) {
  16113. if (err) {
  16114. return callback(err);
  16115. }
  16116. var args = Array.prototype.slice.call(arguments, 1);
  16117. if (!test.apply(null, args)) {
  16118. async.doUntil(iterator, test, callback);
  16119. }
  16120. else {
  16121. callback();
  16122. }
  16123. });
  16124. };
  16125. async.queue = function (worker, concurrency) {
  16126. if (concurrency === undefined) {
  16127. concurrency = 1;
  16128. }
  16129. function _insert(q, data, pos, callback) {
  16130. if (!q.started){
  16131. q.started = true;
  16132. }
  16133. if (!_isArray(data)) {
  16134. data = [data];
  16135. }
  16136. if(data.length == 0) {
  16137. // call drain immediately if there are no tasks
  16138. return async.setImmediate(function() {
  16139. if (q.drain) {
  16140. q.drain();
  16141. }
  16142. });
  16143. }
  16144. _each(data, function(task) {
  16145. var item = {
  16146. data: task,
  16147. callback: typeof callback === 'function' ? callback : null
  16148. };
  16149. if (pos) {
  16150. q.tasks.unshift(item);
  16151. } else {
  16152. q.tasks.push(item);
  16153. }
  16154. if (q.saturated && q.tasks.length === q.concurrency) {
  16155. q.saturated();
  16156. }
  16157. async.setImmediate(q.process);
  16158. });
  16159. }
  16160. var workers = 0;
  16161. var q = {
  16162. tasks: [],
  16163. concurrency: concurrency,
  16164. saturated: null,
  16165. empty: null,
  16166. drain: null,
  16167. started: false,
  16168. paused: false,
  16169. push: function (data, callback) {
  16170. _insert(q, data, false, callback);
  16171. },
  16172. kill: function () {
  16173. q.drain = null;
  16174. q.tasks = [];
  16175. },
  16176. unshift: function (data, callback) {
  16177. _insert(q, data, true, callback);
  16178. },
  16179. process: function () {
  16180. if (!q.paused && workers < q.concurrency && q.tasks.length) {
  16181. var task = q.tasks.shift();
  16182. if (q.empty && q.tasks.length === 0) {
  16183. q.empty();
  16184. }
  16185. workers += 1;
  16186. var next = function () {
  16187. workers -= 1;
  16188. if (task.callback) {
  16189. task.callback.apply(task, arguments);
  16190. }
  16191. if (q.drain && q.tasks.length + workers === 0) {
  16192. q.drain();
  16193. }
  16194. q.process();
  16195. };
  16196. var cb = only_once(next);
  16197. worker(task.data, cb);
  16198. }
  16199. },
  16200. length: function () {
  16201. return q.tasks.length;
  16202. },
  16203. running: function () {
  16204. return workers;
  16205. },
  16206. idle: function() {
  16207. return q.tasks.length + workers === 0;
  16208. },
  16209. pause: function () {
  16210. if (q.paused === true) { return; }
  16211. q.paused = true;
  16212. q.process();
  16213. },
  16214. resume: function () {
  16215. if (q.paused === false) { return; }
  16216. q.paused = false;
  16217. q.process();
  16218. }
  16219. };
  16220. return q;
  16221. };
  16222. async.priorityQueue = function (worker, concurrency) {
  16223. function _compareTasks(a, b){
  16224. return a.priority - b.priority;
  16225. };
  16226. function _binarySearch(sequence, item, compare) {
  16227. var beg = -1,
  16228. end = sequence.length - 1;
  16229. while (beg < end) {
  16230. var mid = beg + ((end - beg + 1) >>> 1);
  16231. if (compare(item, sequence[mid]) >= 0) {
  16232. beg = mid;
  16233. } else {
  16234. end = mid - 1;
  16235. }
  16236. }
  16237. return beg;
  16238. }
  16239. function _insert(q, data, priority, callback) {
  16240. if (!q.started){
  16241. q.started = true;
  16242. }
  16243. if (!_isArray(data)) {
  16244. data = [data];
  16245. }
  16246. if(data.length == 0) {
  16247. // call drain immediately if there are no tasks
  16248. return async.setImmediate(function() {
  16249. if (q.drain) {
  16250. q.drain();
  16251. }
  16252. });
  16253. }
  16254. _each(data, function(task) {
  16255. var item = {
  16256. data: task,
  16257. priority: priority,
  16258. callback: typeof callback === 'function' ? callback : null
  16259. };
  16260. q.tasks.splice(_binarySearch(q.tasks, item, _compareTasks) + 1, 0, item);
  16261. if (q.saturated && q.tasks.length === q.concurrency) {
  16262. q.saturated();
  16263. }
  16264. async.setImmediate(q.process);
  16265. });
  16266. }
  16267. // Start with a normal queue
  16268. var q = async.queue(worker, concurrency);
  16269. // Override push to accept second parameter representing priority
  16270. q.push = function (data, priority, callback) {
  16271. _insert(q, data, priority, callback);
  16272. };
  16273. // Remove unshift function
  16274. delete q.unshift;
  16275. return q;
  16276. };
  16277. async.cargo = function (worker, payload) {
  16278. var working = false,
  16279. tasks = [];
  16280. var cargo = {
  16281. tasks: tasks,
  16282. payload: payload,
  16283. saturated: null,
  16284. empty: null,
  16285. drain: null,
  16286. drained: true,
  16287. push: function (data, callback) {
  16288. if (!_isArray(data)) {
  16289. data = [data];
  16290. }
  16291. _each(data, function(task) {
  16292. tasks.push({
  16293. data: task,
  16294. callback: typeof callback === 'function' ? callback : null
  16295. });
  16296. cargo.drained = false;
  16297. if (cargo.saturated && tasks.length === payload) {
  16298. cargo.saturated();
  16299. }
  16300. });
  16301. async.setImmediate(cargo.process);
  16302. },
  16303. process: function process() {
  16304. if (working) return;
  16305. if (tasks.length === 0) {
  16306. if(cargo.drain && !cargo.drained) cargo.drain();
  16307. cargo.drained = true;
  16308. return;
  16309. }
  16310. var ts = typeof payload === 'number'
  16311. ? tasks.splice(0, payload)
  16312. : tasks.splice(0, tasks.length);
  16313. var ds = _map(ts, function (task) {
  16314. return task.data;
  16315. });
  16316. if(cargo.empty) cargo.empty();
  16317. working = true;
  16318. worker(ds, function () {
  16319. working = false;
  16320. var args = arguments;
  16321. _each(ts, function (data) {
  16322. if (data.callback) {
  16323. data.callback.apply(null, args);
  16324. }
  16325. });
  16326. process();
  16327. });
  16328. },
  16329. length: function () {
  16330. return tasks.length;
  16331. },
  16332. running: function () {
  16333. return working;
  16334. }
  16335. };
  16336. return cargo;
  16337. };
  16338. var _console_fn = function (name) {
  16339. return function (fn) {
  16340. var args = Array.prototype.slice.call(arguments, 1);
  16341. fn.apply(null, args.concat([function (err) {
  16342. var args = Array.prototype.slice.call(arguments, 1);
  16343. if (typeof console !== 'undefined') {
  16344. if (err) {
  16345. if (console.error) {
  16346. console.error(err);
  16347. }
  16348. }
  16349. else if (console[name]) {
  16350. _each(args, function (x) {
  16351. console[name](x);
  16352. });
  16353. }
  16354. }
  16355. }]));
  16356. };
  16357. };
  16358. async.log = _console_fn('log');
  16359. async.dir = _console_fn('dir');
  16360. /*async.info = _console_fn('info');
  16361. async.warn = _console_fn('warn');
  16362. async.error = _console_fn('error');*/
  16363. async.memoize = function (fn, hasher) {
  16364. var memo = {};
  16365. var queues = {};
  16366. hasher = hasher || function (x) {
  16367. return x;
  16368. };
  16369. var memoized = function () {
  16370. var args = Array.prototype.slice.call(arguments);
  16371. var callback = args.pop();
  16372. var key = hasher.apply(null, args);
  16373. if (key in memo) {
  16374. async.nextTick(function () {
  16375. callback.apply(null, memo[key]);
  16376. });
  16377. }
  16378. else if (key in queues) {
  16379. queues[key].push(callback);
  16380. }
  16381. else {
  16382. queues[key] = [callback];
  16383. fn.apply(null, args.concat([function () {
  16384. memo[key] = arguments;
  16385. var q = queues[key];
  16386. delete queues[key];
  16387. for (var i = 0, l = q.length; i < l; i++) {
  16388. q[i].apply(null, arguments);
  16389. }
  16390. }]));
  16391. }
  16392. };
  16393. memoized.memo = memo;
  16394. memoized.unmemoized = fn;
  16395. return memoized;
  16396. };
  16397. async.unmemoize = function (fn) {
  16398. return function () {
  16399. return (fn.unmemoized || fn).apply(null, arguments);
  16400. };
  16401. };
  16402. async.times = function (count, iterator, callback) {
  16403. var counter = [];
  16404. for (var i = 0; i < count; i++) {
  16405. counter.push(i);
  16406. }
  16407. return async.map(counter, iterator, callback);
  16408. };
  16409. async.timesSeries = function (count, iterator, callback) {
  16410. var counter = [];
  16411. for (var i = 0; i < count; i++) {
  16412. counter.push(i);
  16413. }
  16414. return async.mapSeries(counter, iterator, callback);
  16415. };
  16416. async.seq = function (/* functions... */) {
  16417. var fns = arguments;
  16418. return function () {
  16419. var that = this;
  16420. var args = Array.prototype.slice.call(arguments);
  16421. var callback = args.pop();
  16422. async.reduce(fns, args, function (newargs, fn, cb) {
  16423. fn.apply(that, newargs.concat([function () {
  16424. var err = arguments[0];
  16425. var nextargs = Array.prototype.slice.call(arguments, 1);
  16426. cb(err, nextargs);
  16427. }]))
  16428. },
  16429. function (err, results) {
  16430. callback.apply(that, [err].concat(results));
  16431. });
  16432. };
  16433. };
  16434. async.compose = function (/* functions... */) {
  16435. return async.seq.apply(null, Array.prototype.reverse.call(arguments));
  16436. };
  16437. var _applyEach = function (eachfn, fns /*args...*/) {
  16438. var go = function () {
  16439. var that = this;
  16440. var args = Array.prototype.slice.call(arguments);
  16441. var callback = args.pop();
  16442. return eachfn(fns, function (fn, cb) {
  16443. fn.apply(that, args.concat([cb]));
  16444. },
  16445. callback);
  16446. };
  16447. if (arguments.length > 2) {
  16448. var args = Array.prototype.slice.call(arguments, 2);
  16449. return go.apply(this, args);
  16450. }
  16451. else {
  16452. return go;
  16453. }
  16454. };
  16455. async.applyEach = doParallel(_applyEach);
  16456. async.applyEachSeries = doSeries(_applyEach);
  16457. async.forever = function (fn, callback) {
  16458. function next(err) {
  16459. if (err) {
  16460. if (callback) {
  16461. return callback(err);
  16462. }
  16463. throw err;
  16464. }
  16465. fn(next);
  16466. }
  16467. next();
  16468. };
  16469. // Node.js
  16470. if (typeof module !== 'undefined' && module.exports) {
  16471. module.exports = async;
  16472. }
  16473. // AMD / RequireJS
  16474. else if (typeof define !== 'undefined' && define.amd) {
  16475. define([], function () {
  16476. return async;
  16477. });
  16478. }
  16479. // included directly via <script> tag
  16480. else {
  16481. root.async = async;
  16482. }
  16483. }());
  16484. }).call(this,require('_process'))
  16485. },{"_process":103}],65:[function(require,module,exports){
  16486. // i18next, v1.7.7
  16487. // Copyright (c)2014 Jan Mühlemann (jamuhl).
  16488. // Distributed under MIT license
  16489. // http://i18next.com
  16490. (function() {
  16491. // add indexOf to non ECMA-262 standard compliant browsers
  16492. if (!Array.prototype.indexOf) {
  16493. Array.prototype.indexOf = function (searchElement /*, fromIndex */ ) {
  16494. "use strict";
  16495. if (this == null) {
  16496. throw new TypeError();
  16497. }
  16498. var t = Object(this);
  16499. var len = t.length >>> 0;
  16500. if (len === 0) {
  16501. return -1;
  16502. }
  16503. var n = 0;
  16504. if (arguments.length > 0) {
  16505. n = Number(arguments[1]);
  16506. if (n != n) { // shortcut for verifying if it's NaN
  16507. n = 0;
  16508. } else if (n != 0 && n != Infinity && n != -Infinity) {
  16509. n = (n > 0 || -1) * Math.floor(Math.abs(n));
  16510. }
  16511. }
  16512. if (n >= len) {
  16513. return -1;
  16514. }
  16515. var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);
  16516. for (; k < len; k++) {
  16517. if (k in t && t[k] === searchElement) {
  16518. return k;
  16519. }
  16520. }
  16521. return -1;
  16522. }
  16523. }
  16524. // add lastIndexOf to non ECMA-262 standard compliant browsers
  16525. if (!Array.prototype.lastIndexOf) {
  16526. Array.prototype.lastIndexOf = function(searchElement /*, fromIndex*/) {
  16527. "use strict";
  16528. if (this == null) {
  16529. throw new TypeError();
  16530. }
  16531. var t = Object(this);
  16532. var len = t.length >>> 0;
  16533. if (len === 0) {
  16534. return -1;
  16535. }
  16536. var n = len;
  16537. if (arguments.length > 1) {
  16538. n = Number(arguments[1]);
  16539. if (n != n) {
  16540. n = 0;
  16541. } else if (n != 0 && n != (1 / 0) && n != -(1 / 0)) {
  16542. n = (n > 0 || -1) * Math.floor(Math.abs(n));
  16543. }
  16544. }
  16545. var k = n >= 0 ? Math.min(n, len - 1) : len - Math.abs(n);
  16546. for (; k >= 0; k--) {
  16547. if (k in t && t[k] === searchElement) {
  16548. return k;
  16549. }
  16550. }
  16551. return -1;
  16552. };
  16553. }
  16554. // Add string trim for IE8.
  16555. if (typeof String.prototype.trim !== 'function') {
  16556. String.prototype.trim = function() {
  16557. return this.replace(/^\s+|\s+$/g, '');
  16558. }
  16559. }
  16560. var root = this
  16561. , $ = root.jQuery || root.Zepto
  16562. , i18n = {}
  16563. , resStore = {}
  16564. , currentLng
  16565. , replacementCounter = 0
  16566. , languages = []
  16567. , initialized = false
  16568. , sync = {};
  16569. // Export the i18next object for **CommonJS**.
  16570. // If we're not in CommonJS, add `i18n` to the
  16571. // global object or to jquery.
  16572. if (typeof module !== 'undefined' && module.exports) {
  16573. if (!$) {
  16574. try {
  16575. $ = require('jquery');
  16576. } catch(e) {
  16577. // just ignore
  16578. }
  16579. }
  16580. if ($) {
  16581. $.i18n = $.i18n || i18n;
  16582. }
  16583. module.exports = i18n;
  16584. } else {
  16585. if ($) {
  16586. $.i18n = $.i18n || i18n;
  16587. }
  16588. root.i18n = root.i18n || i18n;
  16589. }
  16590. sync = {
  16591. load: function(lngs, options, cb) {
  16592. if (options.useLocalStorage) {
  16593. sync._loadLocal(lngs, options, function(err, store) {
  16594. var missingLngs = [];
  16595. for (var i = 0, len = lngs.length; i < len; i++) {
  16596. if (!store[lngs[i]]) missingLngs.push(lngs[i]);
  16597. }
  16598. if (missingLngs.length > 0) {
  16599. sync._fetch(missingLngs, options, function(err, fetched) {
  16600. f.extend(store, fetched);
  16601. sync._storeLocal(fetched);
  16602. cb(null, store);
  16603. });
  16604. } else {
  16605. cb(null, store);
  16606. }
  16607. });
  16608. } else {
  16609. sync._fetch(lngs, options, function(err, store){
  16610. cb(null, store);
  16611. });
  16612. }
  16613. },
  16614. _loadLocal: function(lngs, options, cb) {
  16615. var store = {}
  16616. , nowMS = new Date().getTime();
  16617. if(window.localStorage) {
  16618. var todo = lngs.length;
  16619. f.each(lngs, function(key, lng) {
  16620. var local = window.localStorage.getItem('res_' + lng);
  16621. if (local) {
  16622. local = JSON.parse(local);
  16623. if (local.i18nStamp && local.i18nStamp + options.localStorageExpirationTime > nowMS) {
  16624. store[lng] = local;
  16625. }
  16626. }
  16627. todo--; // wait for all done befor callback
  16628. if (todo === 0) cb(null, store);
  16629. });
  16630. }
  16631. },
  16632. _storeLocal: function(store) {
  16633. if(window.localStorage) {
  16634. for (var m in store) {
  16635. store[m].i18nStamp = new Date().getTime();
  16636. f.localStorage.setItem('res_' + m, JSON.stringify(store[m]));
  16637. }
  16638. }
  16639. return;
  16640. },
  16641. _fetch: function(lngs, options, cb) {
  16642. var ns = options.ns
  16643. , store = {};
  16644. if (!options.dynamicLoad) {
  16645. var todo = ns.namespaces.length * lngs.length
  16646. , errors;
  16647. // load each file individual
  16648. f.each(ns.namespaces, function(nsIndex, nsValue) {
  16649. f.each(lngs, function(lngIndex, lngValue) {
  16650. // Call this once our translation has returned.
  16651. var loadComplete = function(err, data) {
  16652. if (err) {
  16653. errors = errors || [];
  16654. errors.push(err);
  16655. }
  16656. store[lngValue] = store[lngValue] || {};
  16657. store[lngValue][nsValue] = data;
  16658. todo--; // wait for all done befor callback
  16659. if (todo === 0) cb(errors, store);
  16660. };
  16661. if(typeof options.customLoad == 'function'){
  16662. // Use the specified custom callback.
  16663. options.customLoad(lngValue, nsValue, options, loadComplete);
  16664. } else {
  16665. //~ // Use our inbuilt sync.
  16666. sync._fetchOne(lngValue, nsValue, options, loadComplete);
  16667. }
  16668. });
  16669. });
  16670. } else {
  16671. // Call this once our translation has returned.
  16672. var loadComplete = function(err, data) {
  16673. cb(null, data);
  16674. };
  16675. if(typeof options.customLoad == 'function'){
  16676. // Use the specified custom callback.
  16677. options.customLoad(lngs, ns.namespaces, options, loadComplete);
  16678. } else {
  16679. var url = applyReplacement(options.resGetPath, { lng: lngs.join('+'), ns: ns.namespaces.join('+') });
  16680. // load all needed stuff once
  16681. f.ajax({
  16682. url: url,
  16683. success: function(data, status, xhr) {
  16684. f.log('loaded: ' + url);
  16685. loadComplete(null, data);
  16686. },
  16687. error : function(xhr, status, error) {
  16688. f.log('failed loading: ' + url);
  16689. loadComplete('failed loading resource.json error: ' + error);
  16690. },
  16691. dataType: "json",
  16692. async : options.getAsync
  16693. });
  16694. }
  16695. }
  16696. },
  16697. _fetchOne: function(lng, ns, options, done) {
  16698. var url = applyReplacement(options.resGetPath, { lng: lng, ns: ns });
  16699. f.ajax({
  16700. url: url,
  16701. success: function(data, status, xhr) {
  16702. f.log('loaded: ' + url);
  16703. done(null, data);
  16704. },
  16705. error : function(xhr, status, error) {
  16706. if ((status && status == 200) || (xhr && xhr.status && xhr.status == 200)) {
  16707. // file loaded but invalid json, stop waste time !
  16708. f.error('There is a typo in: ' + url);
  16709. } else if ((status && status == 404) || (xhr && xhr.status && xhr.status == 404)) {
  16710. f.log('Does not exist: ' + url);
  16711. } else {
  16712. var theStatus = status ? status : ((xhr && xhr.status) ? xhr.status : null);
  16713. f.log(theStatus + ' when loading ' + url);
  16714. }
  16715. done(error, {});
  16716. },
  16717. dataType: "json",
  16718. async : options.getAsync
  16719. });
  16720. },
  16721. postMissing: function(lng, ns, key, defaultValue, lngs) {
  16722. var payload = {};
  16723. payload[key] = defaultValue;
  16724. var urls = [];
  16725. if (o.sendMissingTo === 'fallback' && o.fallbackLng[0] !== false) {
  16726. for (var i = 0; i < o.fallbackLng.length; i++) {
  16727. urls.push({lng: o.fallbackLng[i], url: applyReplacement(o.resPostPath, { lng: o.fallbackLng[i], ns: ns })});
  16728. }
  16729. } else if (o.sendMissingTo === 'current' || (o.sendMissingTo === 'fallback' && o.fallbackLng[0] === false) ) {
  16730. urls.push({lng: lng, url: applyReplacement(o.resPostPath, { lng: lng, ns: ns })});
  16731. } else if (o.sendMissingTo === 'all') {
  16732. for (var i = 0, l = lngs.length; i < l; i++) {
  16733. urls.push({lng: lngs[i], url: applyReplacement(o.resPostPath, { lng: lngs[i], ns: ns })});
  16734. }
  16735. }
  16736. for (var y = 0, len = urls.length; y < len; y++) {
  16737. var item = urls[y];
  16738. f.ajax({
  16739. url: item.url,
  16740. type: o.sendType,
  16741. data: payload,
  16742. success: function(data, status, xhr) {
  16743. f.log('posted missing key \'' + key + '\' to: ' + item.url);
  16744. // add key to resStore
  16745. var keys = key.split('.');
  16746. var x = 0;
  16747. var value = resStore[item.lng][ns];
  16748. while (keys[x]) {
  16749. if (x === keys.length - 1) {
  16750. value = value[keys[x]] = defaultValue;
  16751. } else {
  16752. value = value[keys[x]] = value[keys[x]] || {};
  16753. }
  16754. x++;
  16755. }
  16756. },
  16757. error : function(xhr, status, error) {
  16758. f.log('failed posting missing key \'' + key + '\' to: ' + item.url);
  16759. },
  16760. dataType: "json",
  16761. async : o.postAsync
  16762. });
  16763. }
  16764. },
  16765. reload: reload
  16766. };
  16767. // defaults
  16768. var o = {
  16769. lng: undefined,
  16770. load: 'all',
  16771. preload: [],
  16772. lowerCaseLng: false,
  16773. returnObjectTrees: false,
  16774. fallbackLng: ['dev'],
  16775. fallbackNS: [],
  16776. detectLngQS: 'setLng',
  16777. detectLngFromLocalStorage: false,
  16778. ns: 'translation',
  16779. fallbackOnNull: true,
  16780. fallbackOnEmpty: false,
  16781. fallbackToDefaultNS: false,
  16782. nsseparator: ':',
  16783. keyseparator: '.',
  16784. selectorAttr: 'data-i18n',
  16785. debug: false,
  16786. resGetPath: 'locales/__lng__/__ns__.json',
  16787. resPostPath: 'locales/add/__lng__/__ns__',
  16788. getAsync: true,
  16789. postAsync: true,
  16790. resStore: undefined,
  16791. useLocalStorage: false,
  16792. localStorageExpirationTime: 7*24*60*60*1000,
  16793. dynamicLoad: false,
  16794. sendMissing: false,
  16795. sendMissingTo: 'fallback', // current | all
  16796. sendType: 'POST',
  16797. interpolationPrefix: '__',
  16798. interpolationSuffix: '__',
  16799. defaultVariables: false,
  16800. reusePrefix: '$t(',
  16801. reuseSuffix: ')',
  16802. pluralSuffix: '_plural',
  16803. pluralNotFound: ['plural_not_found', Math.random()].join(''),
  16804. contextNotFound: ['context_not_found', Math.random()].join(''),
  16805. escapeInterpolation: false,
  16806. indefiniteSuffix: '_indefinite',
  16807. indefiniteNotFound: ['indefinite_not_found', Math.random()].join(''),
  16808. setJqueryExt: true,
  16809. defaultValueFromContent: true,
  16810. useDataAttrOptions: false,
  16811. cookieExpirationTime: undefined,
  16812. useCookie: true,
  16813. cookieName: 'i18next',
  16814. cookieDomain: undefined,
  16815. objectTreeKeyHandler: undefined,
  16816. postProcess: undefined,
  16817. parseMissingKey: undefined,
  16818. missingKeyHandler: sync.postMissing,
  16819. shortcutFunction: 'sprintf' // or: defaultValue
  16820. };
  16821. function _extend(target, source) {
  16822. if (!source || typeof source === 'function') {
  16823. return target;
  16824. }
  16825. for (var attr in source) { target[attr] = source[attr]; }
  16826. return target;
  16827. }
  16828. function _deepExtend(target, source) {
  16829. for (var prop in source)
  16830. if (prop in target)
  16831. _deepExtend(target[prop], source[prop]);
  16832. else
  16833. target[prop] = source[prop];
  16834. return target;
  16835. }
  16836. function _each(object, callback, args) {
  16837. var name, i = 0,
  16838. length = object.length,
  16839. isObj = length === undefined || Object.prototype.toString.apply(object) !== '[object Array]' || typeof object === "function";
  16840. if (args) {
  16841. if (isObj) {
  16842. for (name in object) {
  16843. if (callback.apply(object[name], args) === false) {
  16844. break;
  16845. }
  16846. }
  16847. } else {
  16848. for ( ; i < length; ) {
  16849. if (callback.apply(object[i++], args) === false) {
  16850. break;
  16851. }
  16852. }
  16853. }
  16854. // A special, fast, case for the most common use of each
  16855. } else {
  16856. if (isObj) {
  16857. for (name in object) {
  16858. if (callback.call(object[name], name, object[name]) === false) {
  16859. break;
  16860. }
  16861. }
  16862. } else {
  16863. for ( ; i < length; ) {
  16864. if (callback.call(object[i], i, object[i++]) === false) {
  16865. break;
  16866. }
  16867. }
  16868. }
  16869. }
  16870. return object;
  16871. }
  16872. var _entityMap = {
  16873. "&": "&amp;",
  16874. "<": "&lt;",
  16875. ">": "&gt;",
  16876. '"': '&quot;',
  16877. "'": '&#39;',
  16878. "/": '&#x2F;'
  16879. };
  16880. function _escape(data) {
  16881. if (typeof data === 'string') {
  16882. return data.replace(/[&<>"'\/]/g, function (s) {
  16883. return _entityMap[s];
  16884. });
  16885. }else{
  16886. return data;
  16887. }
  16888. }
  16889. function _ajax(options) {
  16890. // v0.5.0 of https://github.com/goloroden/http.js
  16891. var getXhr = function (callback) {
  16892. // Use the native XHR object if the browser supports it.
  16893. if (window.XMLHttpRequest) {
  16894. return callback(null, new XMLHttpRequest());
  16895. } else if (window.ActiveXObject) {
  16896. // In Internet Explorer check for ActiveX versions of the XHR object.
  16897. try {
  16898. return callback(null, new ActiveXObject("Msxml2.XMLHTTP"));
  16899. } catch (e) {
  16900. return callback(null, new ActiveXObject("Microsoft.XMLHTTP"));
  16901. }
  16902. }
  16903. // If no XHR support was found, throw an error.
  16904. return callback(new Error());
  16905. };
  16906. var encodeUsingUrlEncoding = function (data) {
  16907. if(typeof data === 'string') {
  16908. return data;
  16909. }
  16910. var result = [];
  16911. for(var dataItem in data) {
  16912. if(data.hasOwnProperty(dataItem)) {
  16913. result.push(encodeURIComponent(dataItem) + '=' + encodeURIComponent(data[dataItem]));
  16914. }
  16915. }
  16916. return result.join('&');
  16917. };
  16918. var utf8 = function (text) {
  16919. text = text.replace(/\r\n/g, '\n');
  16920. var result = '';
  16921. for(var i = 0; i < text.length; i++) {
  16922. var c = text.charCodeAt(i);
  16923. if(c < 128) {
  16924. result += String.fromCharCode(c);
  16925. } else if((c > 127) && (c < 2048)) {
  16926. result += String.fromCharCode((c >> 6) | 192);
  16927. result += String.fromCharCode((c & 63) | 128);
  16928. } else {
  16929. result += String.fromCharCode((c >> 12) | 224);
  16930. result += String.fromCharCode(((c >> 6) & 63) | 128);
  16931. result += String.fromCharCode((c & 63) | 128);
  16932. }
  16933. }
  16934. return result;
  16935. };
  16936. var base64 = function (text) {
  16937. var keyStr = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
  16938. text = utf8(text);
  16939. var result = '',
  16940. chr1, chr2, chr3,
  16941. enc1, enc2, enc3, enc4,
  16942. i = 0;
  16943. do {
  16944. chr1 = text.charCodeAt(i++);
  16945. chr2 = text.charCodeAt(i++);
  16946. chr3 = text.charCodeAt(i++);
  16947. enc1 = chr1 >> 2;
  16948. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  16949. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  16950. enc4 = chr3 & 63;
  16951. if(isNaN(chr2)) {
  16952. enc3 = enc4 = 64;
  16953. } else if(isNaN(chr3)) {
  16954. enc4 = 64;
  16955. }
  16956. result +=
  16957. keyStr.charAt(enc1) +
  16958. keyStr.charAt(enc2) +
  16959. keyStr.charAt(enc3) +
  16960. keyStr.charAt(enc4);
  16961. chr1 = chr2 = chr3 = '';
  16962. enc1 = enc2 = enc3 = enc4 = '';
  16963. } while(i < text.length);
  16964. return result;
  16965. };
  16966. var mergeHeaders = function () {
  16967. // Use the first header object as base.
  16968. var result = arguments[0];
  16969. // Iterate through the remaining header objects and add them.
  16970. for(var i = 1; i < arguments.length; i++) {
  16971. var currentHeaders = arguments[i];
  16972. for(var header in currentHeaders) {
  16973. if(currentHeaders.hasOwnProperty(header)) {
  16974. result[header] = currentHeaders[header];
  16975. }
  16976. }
  16977. }
  16978. // Return the merged headers.
  16979. return result;
  16980. };
  16981. var ajax = function (method, url, options, callback) {
  16982. // Adjust parameters.
  16983. if(typeof options === 'function') {
  16984. callback = options;
  16985. options = {};
  16986. }
  16987. // Set default parameter values.
  16988. options.cache = options.cache || false;
  16989. options.data = options.data || {};
  16990. options.headers = options.headers || {};
  16991. options.jsonp = options.jsonp || false;
  16992. options.async = options.async === undefined ? true : options.async;
  16993. // Merge the various header objects.
  16994. var headers = mergeHeaders({
  16995. 'accept': '*/*',
  16996. 'content-type': 'application/x-www-form-urlencoded;charset=UTF-8'
  16997. }, ajax.headers, options.headers);
  16998. // Encode the data according to the content-type.
  16999. var payload;
  17000. if (headers['content-type'] === 'application/json') {
  17001. payload = JSON.stringify(options.data);
  17002. } else {
  17003. payload = encodeUsingUrlEncoding(options.data);
  17004. }
  17005. // Specially prepare GET requests: Setup the query string, handle caching and make a JSONP call
  17006. // if neccessary.
  17007. if(method === 'GET') {
  17008. // Setup the query string.
  17009. var queryString = [];
  17010. if(payload) {
  17011. queryString.push(payload);
  17012. payload = null;
  17013. }
  17014. // Handle caching.
  17015. if(!options.cache) {
  17016. queryString.push('_=' + (new Date()).getTime());
  17017. }
  17018. // If neccessary prepare the query string for a JSONP call.
  17019. if(options.jsonp) {
  17020. queryString.push('callback=' + options.jsonp);
  17021. queryString.push('jsonp=' + options.jsonp);
  17022. }
  17023. // Merge the query string and attach it to the url.
  17024. queryString = queryString.join('&');
  17025. if (queryString.length > 1) {
  17026. if (url.indexOf('?') > -1) {
  17027. url += '&' + queryString;
  17028. } else {
  17029. url += '?' + queryString;
  17030. }
  17031. }
  17032. // Make a JSONP call if neccessary.
  17033. if(options.jsonp) {
  17034. var head = document.getElementsByTagName('head')[0];
  17035. var script = document.createElement('script');
  17036. script.type = 'text/javascript';
  17037. script.src = url;
  17038. head.appendChild(script);
  17039. return;
  17040. }
  17041. }
  17042. // Since we got here, it is no JSONP request, so make a normal XHR request.
  17043. getXhr(function (err, xhr) {
  17044. if(err) return callback(err);
  17045. // Open the request.
  17046. xhr.open(method, url, options.async);
  17047. // Set the request headers.
  17048. for(var header in headers) {
  17049. if(headers.hasOwnProperty(header)) {
  17050. xhr.setRequestHeader(header, headers[header]);
  17051. }
  17052. }
  17053. // Handle the request events.
  17054. xhr.onreadystatechange = function () {
  17055. if(xhr.readyState === 4) {
  17056. var data = xhr.responseText || '';
  17057. // If no callback is given, return.
  17058. if(!callback) {
  17059. return;
  17060. }
  17061. // Return an object that provides access to the data as text and JSON.
  17062. callback(xhr.status, {
  17063. text: function () {
  17064. return data;
  17065. },
  17066. json: function () {
  17067. try {
  17068. return JSON.parse(data)
  17069. } catch (e) {
  17070. f.error('Can not parse JSON. URL: ' + url);
  17071. return {};
  17072. }
  17073. }
  17074. });
  17075. }
  17076. };
  17077. // Actually send the XHR request.
  17078. xhr.send(payload);
  17079. });
  17080. };
  17081. // Define the external interface.
  17082. var http = {
  17083. authBasic: function (username, password) {
  17084. ajax.headers['Authorization'] = 'Basic ' + base64(username + ':' + password);
  17085. },
  17086. connect: function (url, options, callback) {
  17087. return ajax('CONNECT', url, options, callback);
  17088. },
  17089. del: function (url, options, callback) {
  17090. return ajax('DELETE', url, options, callback);
  17091. },
  17092. get: function (url, options, callback) {
  17093. return ajax('GET', url, options, callback);
  17094. },
  17095. head: function (url, options, callback) {
  17096. return ajax('HEAD', url, options, callback);
  17097. },
  17098. headers: function (headers) {
  17099. ajax.headers = headers || {};
  17100. },
  17101. isAllowed: function (url, verb, callback) {
  17102. this.options(url, function (status, data) {
  17103. callback(data.text().indexOf(verb) !== -1);
  17104. });
  17105. },
  17106. options: function (url, options, callback) {
  17107. return ajax('OPTIONS', url, options, callback);
  17108. },
  17109. patch: function (url, options, callback) {
  17110. return ajax('PATCH', url, options, callback);
  17111. },
  17112. post: function (url, options, callback) {
  17113. return ajax('POST', url, options, callback);
  17114. },
  17115. put: function (url, options, callback) {
  17116. return ajax('PUT', url, options, callback);
  17117. },
  17118. trace: function (url, options, callback) {
  17119. return ajax('TRACE', url, options, callback);
  17120. }
  17121. };
  17122. var methode = options.type ? options.type.toLowerCase() : 'get';
  17123. http[methode](options.url, options, function (status, data) {
  17124. // file: protocol always gives status code 0, so check for data
  17125. if (status === 200 || (status === 0 && data.text())) {
  17126. options.success(data.json(), status, null);
  17127. } else {
  17128. options.error(data.text(), status, null);
  17129. }
  17130. });
  17131. }
  17132. var _cookie = {
  17133. create: function(name,value,minutes,domain) {
  17134. var expires;
  17135. if (minutes) {
  17136. var date = new Date();
  17137. date.setTime(date.getTime()+(minutes*60*1000));
  17138. expires = "; expires="+date.toGMTString();
  17139. }
  17140. else expires = "";
  17141. domain = (domain)? "domain="+domain+";" : "";
  17142. document.cookie = name+"="+value+expires+";"+domain+"path=/";
  17143. },
  17144. read: function(name) {
  17145. var nameEQ = name + "=";
  17146. var ca = document.cookie.split(';');
  17147. for(var i=0;i < ca.length;i++) {
  17148. var c = ca[i];
  17149. while (c.charAt(0)==' ') c = c.substring(1,c.length);
  17150. if (c.indexOf(nameEQ) === 0) return c.substring(nameEQ.length,c.length);
  17151. }
  17152. return null;
  17153. },
  17154. remove: function(name) {
  17155. this.create(name,"",-1);
  17156. }
  17157. };
  17158. var cookie_noop = {
  17159. create: function(name,value,minutes,domain) {},
  17160. read: function(name) { return null; },
  17161. remove: function(name) {}
  17162. };
  17163. // move dependent functions to a container so that
  17164. // they can be overriden easier in no jquery environment (node.js)
  17165. var f = {
  17166. extend: $ ? $.extend : _extend,
  17167. deepExtend: _deepExtend,
  17168. each: $ ? $.each : _each,
  17169. ajax: $ ? $.ajax : (typeof document !== 'undefined' ? _ajax : function() {}),
  17170. cookie: typeof document !== 'undefined' ? _cookie : cookie_noop,
  17171. detectLanguage: detectLanguage,
  17172. escape: _escape,
  17173. log: function(str) {
  17174. if (o.debug && typeof console !== "undefined") console.log(str);
  17175. },
  17176. error: function(str) {
  17177. if (typeof console !== "undefined") console.error(str);
  17178. },
  17179. getCountyIndexOfLng: function(lng) {
  17180. var lng_index = 0;
  17181. if (lng === 'nb-NO' || lng === 'nn-NO' || lng === 'nb-no' || lng === 'nn-no') lng_index = 1;
  17182. return lng_index;
  17183. },
  17184. toLanguages: function(lng) {
  17185. var log = this.log;
  17186. function applyCase(l) {
  17187. var ret = l;
  17188. if (typeof l === 'string' && l.indexOf('-') > -1) {
  17189. var parts = l.split('-');
  17190. ret = o.lowerCaseLng ?
  17191. parts[0].toLowerCase() + '-' + parts[1].toLowerCase() :
  17192. parts[0].toLowerCase() + '-' + parts[1].toUpperCase();
  17193. } else {
  17194. ret = o.lowerCaseLng ? l.toLowerCase() : l;
  17195. }
  17196. return ret;
  17197. }
  17198. var languages = [];
  17199. var whitelist = o.lngWhitelist || false;
  17200. var addLanguage = function(language){
  17201. //reject langs not whitelisted
  17202. if(!whitelist || whitelist.indexOf(language) > -1){
  17203. languages.push(language);
  17204. }else{
  17205. log('rejecting non-whitelisted language: ' + language);
  17206. }
  17207. };
  17208. if (typeof lng === 'string' && lng.indexOf('-') > -1) {
  17209. var parts = lng.split('-');
  17210. if (o.load !== 'unspecific') addLanguage(applyCase(lng));
  17211. if (o.load !== 'current') addLanguage(applyCase(parts[this.getCountyIndexOfLng(lng)]));
  17212. } else {
  17213. addLanguage(applyCase(lng));
  17214. }
  17215. for (var i = 0; i < o.fallbackLng.length; i++) {
  17216. if (languages.indexOf(o.fallbackLng[i]) === -1 && o.fallbackLng[i]) languages.push(applyCase(o.fallbackLng[i]));
  17217. }
  17218. return languages;
  17219. },
  17220. regexEscape: function(str) {
  17221. return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
  17222. },
  17223. regexReplacementEscape: function(strOrFn) {
  17224. if (typeof strOrFn === 'string') {
  17225. return strOrFn.replace(/\$/g, "$$$$");
  17226. } else {
  17227. return strOrFn;
  17228. }
  17229. },
  17230. localStorage: {
  17231. setItem: function(key, value) {
  17232. if (window.localStorage) {
  17233. try {
  17234. window.localStorage.setItem(key, value);
  17235. } catch (e) {
  17236. f.log('failed to set value for key "' + key + '" to localStorage.');
  17237. }
  17238. }
  17239. }
  17240. }
  17241. };
  17242. function init(options, cb) {
  17243. if (typeof options === 'function') {
  17244. cb = options;
  17245. options = {};
  17246. }
  17247. options = options || {};
  17248. // override defaults with passed in options
  17249. f.extend(o, options);
  17250. delete o.fixLng; /* passed in each time */
  17251. // override functions: .log(), .detectLanguage(), etc
  17252. if (o.functions) {
  17253. delete o.functions;
  17254. f.extend(f, options.functions);
  17255. }
  17256. // create namespace object if namespace is passed in as string
  17257. if (typeof o.ns == 'string') {
  17258. o.ns = { namespaces: [o.ns], defaultNs: o.ns};
  17259. }
  17260. // fallback namespaces
  17261. if (typeof o.fallbackNS == 'string') {
  17262. o.fallbackNS = [o.fallbackNS];
  17263. }
  17264. // fallback languages
  17265. if (typeof o.fallbackLng == 'string' || typeof o.fallbackLng == 'boolean') {
  17266. o.fallbackLng = [o.fallbackLng];
  17267. }
  17268. // escape prefix/suffix
  17269. o.interpolationPrefixEscaped = f.regexEscape(o.interpolationPrefix);
  17270. o.interpolationSuffixEscaped = f.regexEscape(o.interpolationSuffix);
  17271. if (!o.lng) o.lng = f.detectLanguage();
  17272. languages = f.toLanguages(o.lng);
  17273. currentLng = languages[0];
  17274. f.log('currentLng set to: ' + currentLng);
  17275. if (o.useCookie && f.cookie.read(o.cookieName) !== currentLng){ //cookie is unset or invalid
  17276. f.cookie.create(o.cookieName, currentLng, o.cookieExpirationTime, o.cookieDomain);
  17277. }
  17278. if (o.detectLngFromLocalStorage && typeof document !== 'undefined' && window.localStorage) {
  17279. f.localStorage.setItem('i18next_lng', currentLng);
  17280. }
  17281. var lngTranslate = translate;
  17282. if (options.fixLng) {
  17283. lngTranslate = function(key, options) {
  17284. options = options || {};
  17285. options.lng = options.lng || lngTranslate.lng;
  17286. return translate(key, options);
  17287. };
  17288. lngTranslate.lng = currentLng;
  17289. }
  17290. pluralExtensions.setCurrentLng(currentLng);
  17291. // add JQuery extensions
  17292. if ($ && o.setJqueryExt) addJqueryFunct();
  17293. // jQuery deferred
  17294. var deferred;
  17295. if ($ && $.Deferred) {
  17296. deferred = $.Deferred();
  17297. }
  17298. // return immidiatly if res are passed in
  17299. if (o.resStore) {
  17300. resStore = o.resStore;
  17301. initialized = true;
  17302. if (cb) cb(lngTranslate);
  17303. if (deferred) deferred.resolve(lngTranslate);
  17304. if (deferred) return deferred.promise();
  17305. return;
  17306. }
  17307. // languages to load
  17308. var lngsToLoad = f.toLanguages(o.lng);
  17309. if (typeof o.preload === 'string') o.preload = [o.preload];
  17310. for (var i = 0, l = o.preload.length; i < l; i++) {
  17311. var pres = f.toLanguages(o.preload[i]);
  17312. for (var y = 0, len = pres.length; y < len; y++) {
  17313. if (lngsToLoad.indexOf(pres[y]) < 0) {
  17314. lngsToLoad.push(pres[y]);
  17315. }
  17316. }
  17317. }
  17318. // else load them
  17319. i18n.sync.load(lngsToLoad, o, function(err, store) {
  17320. resStore = store;
  17321. initialized = true;
  17322. if (cb) cb(lngTranslate);
  17323. if (deferred) deferred.resolve(lngTranslate);
  17324. });
  17325. if (deferred) return deferred.promise();
  17326. }
  17327. function preload(lngs, cb) {
  17328. if (typeof lngs === 'string') lngs = [lngs];
  17329. for (var i = 0, l = lngs.length; i < l; i++) {
  17330. if (o.preload.indexOf(lngs[i]) < 0) {
  17331. o.preload.push(lngs[i]);
  17332. }
  17333. }
  17334. return init(cb);
  17335. }
  17336. function addResourceBundle(lng, ns, resources, deep) {
  17337. if (typeof ns !== 'string') {
  17338. resources = ns;
  17339. ns = o.ns.defaultNs;
  17340. } else if (o.ns.namespaces.indexOf(ns) < 0) {
  17341. o.ns.namespaces.push(ns);
  17342. }
  17343. resStore[lng] = resStore[lng] || {};
  17344. resStore[lng][ns] = resStore[lng][ns] || {};
  17345. if (deep) {
  17346. f.deepExtend(resStore[lng][ns], resources);
  17347. } else {
  17348. f.extend(resStore[lng][ns], resources);
  17349. }
  17350. }
  17351. function hasResourceBundle(lng, ns) {
  17352. if (typeof ns !== 'string') {
  17353. ns = o.ns.defaultNs;
  17354. }
  17355. resStore[lng] = resStore[lng] || {};
  17356. var res = resStore[lng][ns] || {};
  17357. var hasValues = false;
  17358. for(var prop in res) {
  17359. if (res.hasOwnProperty(prop)) {
  17360. hasValues = true;
  17361. }
  17362. }
  17363. return hasValues;
  17364. }
  17365. function removeResourceBundle(lng, ns) {
  17366. if (typeof ns !== 'string') {
  17367. ns = o.ns.defaultNs;
  17368. }
  17369. resStore[lng] = resStore[lng] || {};
  17370. resStore[lng][ns] = {};
  17371. }
  17372. function addResource(lng, ns, key, value) {
  17373. if (typeof ns !== 'string') {
  17374. resource = ns;
  17375. ns = o.ns.defaultNs;
  17376. } else if (o.ns.namespaces.indexOf(ns) < 0) {
  17377. o.ns.namespaces.push(ns);
  17378. }
  17379. resStore[lng] = resStore[lng] || {};
  17380. resStore[lng][ns] = resStore[lng][ns] || {};
  17381. var keys = key.split(o.keyseparator);
  17382. var x = 0;
  17383. var node = resStore[lng][ns];
  17384. var origRef = node;
  17385. while (keys[x]) {
  17386. if (x == keys.length - 1)
  17387. node[keys[x]] = value;
  17388. else {
  17389. if (node[keys[x]] == null)
  17390. node[keys[x]] = {};
  17391. node = node[keys[x]];
  17392. }
  17393. x++;
  17394. }
  17395. }
  17396. function addResources(lng, ns, resources) {
  17397. if (typeof ns !== 'string') {
  17398. resource = ns;
  17399. ns = o.ns.defaultNs;
  17400. } else if (o.ns.namespaces.indexOf(ns) < 0) {
  17401. o.ns.namespaces.push(ns);
  17402. }
  17403. for (var m in resources) {
  17404. if (typeof resources[m] === 'string') addResource(lng, ns, m, resources[m]);
  17405. }
  17406. }
  17407. function setDefaultNamespace(ns) {
  17408. o.ns.defaultNs = ns;
  17409. }
  17410. function loadNamespace(namespace, cb) {
  17411. loadNamespaces([namespace], cb);
  17412. }
  17413. function loadNamespaces(namespaces, cb) {
  17414. var opts = {
  17415. dynamicLoad: o.dynamicLoad,
  17416. resGetPath: o.resGetPath,
  17417. getAsync: o.getAsync,
  17418. customLoad: o.customLoad,
  17419. ns: { namespaces: namespaces, defaultNs: ''} /* new namespaces to load */
  17420. };
  17421. // languages to load
  17422. var lngsToLoad = f.toLanguages(o.lng);
  17423. if (typeof o.preload === 'string') o.preload = [o.preload];
  17424. for (var i = 0, l = o.preload.length; i < l; i++) {
  17425. var pres = f.toLanguages(o.preload[i]);
  17426. for (var y = 0, len = pres.length; y < len; y++) {
  17427. if (lngsToLoad.indexOf(pres[y]) < 0) {
  17428. lngsToLoad.push(pres[y]);
  17429. }
  17430. }
  17431. }
  17432. // check if we have to load
  17433. var lngNeedLoad = [];
  17434. for (var a = 0, lenA = lngsToLoad.length; a < lenA; a++) {
  17435. var needLoad = false;
  17436. var resSet = resStore[lngsToLoad[a]];
  17437. if (resSet) {
  17438. for (var b = 0, lenB = namespaces.length; b < lenB; b++) {
  17439. if (!resSet[namespaces[b]]) needLoad = true;
  17440. }
  17441. } else {
  17442. needLoad = true;
  17443. }
  17444. if (needLoad) lngNeedLoad.push(lngsToLoad[a]);
  17445. }
  17446. if (lngNeedLoad.length) {
  17447. i18n.sync._fetch(lngNeedLoad, opts, function(err, store) {
  17448. var todo = namespaces.length * lngNeedLoad.length;
  17449. // load each file individual
  17450. f.each(namespaces, function(nsIndex, nsValue) {
  17451. // append namespace to namespace array
  17452. if (o.ns.namespaces.indexOf(nsValue) < 0) {
  17453. o.ns.namespaces.push(nsValue);
  17454. }
  17455. f.each(lngNeedLoad, function(lngIndex, lngValue) {
  17456. resStore[lngValue] = resStore[lngValue] || {};
  17457. resStore[lngValue][nsValue] = store[lngValue][nsValue];
  17458. todo--; // wait for all done befor callback
  17459. if (todo === 0 && cb) {
  17460. if (o.useLocalStorage) i18n.sync._storeLocal(resStore);
  17461. cb();
  17462. }
  17463. });
  17464. });
  17465. });
  17466. } else {
  17467. if (cb) cb();
  17468. }
  17469. }
  17470. function setLng(lng, options, cb) {
  17471. if (typeof options === 'function') {
  17472. cb = options;
  17473. options = {};
  17474. } else if (!options) {
  17475. options = {};
  17476. }
  17477. options.lng = lng;
  17478. return init(options, cb);
  17479. }
  17480. function lng() {
  17481. return currentLng;
  17482. }
  17483. function reload(cb) {
  17484. resStore = {};
  17485. setLng(currentLng, cb);
  17486. }
  17487. function addJqueryFunct() {
  17488. // $.t shortcut
  17489. $.t = $.t || translate;
  17490. function parse(ele, key, options) {
  17491. if (key.length === 0) return;
  17492. var attr = 'text';
  17493. if (key.indexOf('[') === 0) {
  17494. var parts = key.split(']');
  17495. key = parts[1];
  17496. attr = parts[0].substr(1, parts[0].length-1);
  17497. }
  17498. if (key.indexOf(';') === key.length-1) {
  17499. key = key.substr(0, key.length-2);
  17500. }
  17501. var optionsToUse;
  17502. if (attr === 'html') {
  17503. optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.html() }, options) : options;
  17504. ele.html($.t(key, optionsToUse));
  17505. } else if (attr === 'text') {
  17506. optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.text() }, options) : options;
  17507. ele.text($.t(key, optionsToUse));
  17508. } else if (attr === 'prepend') {
  17509. optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.html() }, options) : options;
  17510. ele.prepend($.t(key, optionsToUse));
  17511. } else if (attr === 'append') {
  17512. optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.html() }, options) : options;
  17513. ele.append($.t(key, optionsToUse));
  17514. } else if (attr.indexOf("data-") === 0) {
  17515. var dataAttr = attr.substr(("data-").length);
  17516. optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.data(dataAttr) }, options) : options;
  17517. var translated = $.t(key, optionsToUse);
  17518. //we change into the data cache
  17519. ele.data(dataAttr, translated);
  17520. //we change into the dom
  17521. ele.attr(attr, translated);
  17522. } else {
  17523. optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.attr(attr) }, options) : options;
  17524. ele.attr(attr, $.t(key, optionsToUse));
  17525. }
  17526. }
  17527. function localize(ele, options) {
  17528. var key = ele.attr(o.selectorAttr);
  17529. if (!key && typeof key !== 'undefined' && key !== false) key = ele.text() || ele.val();
  17530. if (!key) return;
  17531. var target = ele
  17532. , targetSelector = ele.data("i18n-target");
  17533. if (targetSelector) {
  17534. target = ele.find(targetSelector) || ele;
  17535. }
  17536. if (!options && o.useDataAttrOptions === true) {
  17537. options = ele.data("i18n-options");
  17538. }
  17539. options = options || {};
  17540. if (key.indexOf(';') >= 0) {
  17541. var keys = key.split(';');
  17542. $.each(keys, function(m, k) {
  17543. if (k !== '') parse(target, k, options);
  17544. });
  17545. } else {
  17546. parse(target, key, options);
  17547. }
  17548. if (o.useDataAttrOptions === true) ele.data("i18n-options", options);
  17549. }
  17550. // fn
  17551. $.fn.i18n = function (options) {
  17552. return this.each(function() {
  17553. // localize element itself
  17554. localize($(this), options);
  17555. // localize childs
  17556. var elements = $(this).find('[' + o.selectorAttr + ']');
  17557. elements.each(function() {
  17558. localize($(this), options);
  17559. });
  17560. });
  17561. };
  17562. }
  17563. function applyReplacement(str, replacementHash, nestedKey, options) {
  17564. if (!str) return str;
  17565. options = options || replacementHash; // first call uses replacement hash combined with options
  17566. if (str.indexOf(options.interpolationPrefix || o.interpolationPrefix) < 0) return str;
  17567. var prefix = options.interpolationPrefix ? f.regexEscape(options.interpolationPrefix) : o.interpolationPrefixEscaped
  17568. , suffix = options.interpolationSuffix ? f.regexEscape(options.interpolationSuffix) : o.interpolationSuffixEscaped
  17569. , unEscapingSuffix = 'HTML'+suffix;
  17570. var hash = replacementHash.replace && typeof replacementHash.replace === 'object' ? replacementHash.replace : replacementHash;
  17571. f.each(hash, function(key, value) {
  17572. var nextKey = nestedKey ? nestedKey + o.keyseparator + key : key;
  17573. if (typeof value === 'object' && value !== null) {
  17574. str = applyReplacement(str, value, nextKey, options);
  17575. } else {
  17576. if (options.escapeInterpolation || o.escapeInterpolation) {
  17577. str = str.replace(new RegExp([prefix, nextKey, unEscapingSuffix].join(''), 'g'), f.regexReplacementEscape(value));
  17578. str = str.replace(new RegExp([prefix, nextKey, suffix].join(''), 'g'), f.regexReplacementEscape(f.escape(value)));
  17579. } else {
  17580. str = str.replace(new RegExp([prefix, nextKey, suffix].join(''), 'g'), f.regexReplacementEscape(value));
  17581. }
  17582. // str = options.escapeInterpolation;
  17583. }
  17584. });
  17585. return str;
  17586. }
  17587. // append it to functions
  17588. f.applyReplacement = applyReplacement;
  17589. function applyReuse(translated, options) {
  17590. var comma = ',';
  17591. var options_open = '{';
  17592. var options_close = '}';
  17593. var opts = f.extend({}, options);
  17594. delete opts.postProcess;
  17595. while (translated.indexOf(o.reusePrefix) != -1) {
  17596. replacementCounter++;
  17597. if (replacementCounter > o.maxRecursion) { break; } // safety net for too much recursion
  17598. var index_of_opening = translated.lastIndexOf(o.reusePrefix);
  17599. var index_of_end_of_closing = translated.indexOf(o.reuseSuffix, index_of_opening) + o.reuseSuffix.length;
  17600. var token = translated.substring(index_of_opening, index_of_end_of_closing);
  17601. var token_without_symbols = token.replace(o.reusePrefix, '').replace(o.reuseSuffix, '');
  17602. if (index_of_end_of_closing <= index_of_opening) {
  17603. f.error('there is an missing closing in following translation value', translated);
  17604. return '';
  17605. }
  17606. if (token_without_symbols.indexOf(comma) != -1) {
  17607. var index_of_token_end_of_closing = token_without_symbols.indexOf(comma);
  17608. if (token_without_symbols.indexOf(options_open, index_of_token_end_of_closing) != -1 && token_without_symbols.indexOf(options_close, index_of_token_end_of_closing) != -1) {
  17609. var index_of_opts_opening = token_without_symbols.indexOf(options_open, index_of_token_end_of_closing);
  17610. var index_of_opts_end_of_closing = token_without_symbols.indexOf(options_close, index_of_opts_opening) + options_close.length;
  17611. try {
  17612. opts = f.extend(opts, JSON.parse(token_without_symbols.substring(index_of_opts_opening, index_of_opts_end_of_closing)));
  17613. token_without_symbols = token_without_symbols.substring(0, index_of_token_end_of_closing);
  17614. } catch (e) {
  17615. }
  17616. }
  17617. }
  17618. var translated_token = _translate(token_without_symbols, opts);
  17619. translated = translated.replace(token, f.regexReplacementEscape(translated_token));
  17620. }
  17621. return translated;
  17622. }
  17623. function hasContext(options) {
  17624. return (options.context && (typeof options.context == 'string' || typeof options.context == 'number'));
  17625. }
  17626. function needsPlural(options, lng) {
  17627. return (options.count !== undefined && typeof options.count != 'string'/* && pluralExtensions.needsPlural(lng, options.count)*/);
  17628. }
  17629. function needsIndefiniteArticle(options) {
  17630. return (options.indefinite_article !== undefined && typeof options.indefinite_article != 'string' && options.indefinite_article);
  17631. }
  17632. function exists(key, options) {
  17633. options = options || {};
  17634. var notFound = _getDefaultValue(key, options)
  17635. , found = _find(key, options);
  17636. return found !== undefined || found === notFound;
  17637. }
  17638. function translate(key, options) {
  17639. options = options || {};
  17640. if (!initialized) {
  17641. f.log('i18next not finished initialization. you might have called t function before loading resources finished.')
  17642. return options.defaultValue || '';
  17643. };
  17644. replacementCounter = 0;
  17645. return _translate.apply(null, arguments);
  17646. }
  17647. function _getDefaultValue(key, options) {
  17648. return (options.defaultValue !== undefined) ? options.defaultValue : key;
  17649. }
  17650. function _injectSprintfProcessor() {
  17651. var values = [];
  17652. // mh: build array from second argument onwards
  17653. for (var i = 1; i < arguments.length; i++) {
  17654. values.push(arguments[i]);
  17655. }
  17656. return {
  17657. postProcess: 'sprintf',
  17658. sprintf: values
  17659. };
  17660. }
  17661. function _translate(potentialKeys, options) {
  17662. if (options && typeof options !== 'object') {
  17663. if (o.shortcutFunction === 'sprintf') {
  17664. // mh: gettext like sprintf syntax found, automatically create sprintf processor
  17665. options = _injectSprintfProcessor.apply(null, arguments);
  17666. } else if (o.shortcutFunction === 'defaultValue') {
  17667. options = {
  17668. defaultValue: options
  17669. }
  17670. }
  17671. } else {
  17672. options = options || {};
  17673. }
  17674. if (typeof o.defaultVariables === 'object') {
  17675. options = f.extend({}, o.defaultVariables, options);
  17676. }
  17677. if (potentialKeys === undefined || potentialKeys === null || potentialKeys === '') return '';
  17678. if (typeof potentialKeys === 'string') {
  17679. potentialKeys = [potentialKeys];
  17680. }
  17681. var key = potentialKeys[0];
  17682. if (potentialKeys.length > 1) {
  17683. for (var i = 0; i < potentialKeys.length; i++) {
  17684. key = potentialKeys[i];
  17685. if (exists(key, options)) {
  17686. break;
  17687. }
  17688. }
  17689. }
  17690. var notFound = _getDefaultValue(key, options)
  17691. , found = _find(key, options)
  17692. , lngs = options.lng ? f.toLanguages(options.lng, options.fallbackLng) : languages
  17693. , ns = options.ns || o.ns.defaultNs
  17694. , parts;
  17695. // split ns and key
  17696. if (key.indexOf(o.nsseparator) > -1) {
  17697. parts = key.split(o.nsseparator);
  17698. ns = parts[0];
  17699. key = parts[1];
  17700. }
  17701. if (found === undefined && o.sendMissing && typeof o.missingKeyHandler === 'function') {
  17702. if (options.lng) {
  17703. o.missingKeyHandler(lngs[0], ns, key, notFound, lngs);
  17704. } else {
  17705. o.missingKeyHandler(o.lng, ns, key, notFound, lngs);
  17706. }
  17707. }
  17708. var postProcessor = options.postProcess || o.postProcess;
  17709. if (found !== undefined && postProcessor) {
  17710. if (postProcessors[postProcessor]) {
  17711. found = postProcessors[postProcessor](found, key, options);
  17712. }
  17713. }
  17714. // process notFound if function exists
  17715. var splitNotFound = notFound;
  17716. if (notFound.indexOf(o.nsseparator) > -1) {
  17717. parts = notFound.split(o.nsseparator);
  17718. splitNotFound = parts[1];
  17719. }
  17720. if (splitNotFound === key && o.parseMissingKey) {
  17721. notFound = o.parseMissingKey(notFound);
  17722. }
  17723. if (found === undefined) {
  17724. notFound = applyReplacement(notFound, options);
  17725. notFound = applyReuse(notFound, options);
  17726. if (postProcessor && postProcessors[postProcessor]) {
  17727. var val = _getDefaultValue(key, options);
  17728. found = postProcessors[postProcessor](val, key, options);
  17729. }
  17730. }
  17731. return (found !== undefined) ? found : notFound;
  17732. }
  17733. function _find(key, options) {
  17734. options = options || {};
  17735. var optionWithoutCount, translated
  17736. , notFound = _getDefaultValue(key, options)
  17737. , lngs = languages;
  17738. if (!resStore) { return notFound; } // no resStore to translate from
  17739. // CI mode
  17740. if (lngs[0].toLowerCase() === 'cimode') return notFound;
  17741. // passed in lng
  17742. if (options.lngs) lngs = options.lngs;
  17743. if (options.lng) {
  17744. lngs = f.toLanguages(options.lng, options.fallbackLng);
  17745. if (!resStore[lngs[0]]) {
  17746. var oldAsync = o.getAsync;
  17747. o.getAsync = false;
  17748. i18n.sync.load(lngs, o, function(err, store) {
  17749. f.extend(resStore, store);
  17750. o.getAsync = oldAsync;
  17751. });
  17752. }
  17753. }
  17754. var ns = options.ns || o.ns.defaultNs;
  17755. if (key.indexOf(o.nsseparator) > -1) {
  17756. var parts = key.split(o.nsseparator);
  17757. ns = parts[0];
  17758. key = parts[1];
  17759. }
  17760. if (hasContext(options)) {
  17761. optionWithoutCount = f.extend({}, options);
  17762. delete optionWithoutCount.context;
  17763. optionWithoutCount.defaultValue = o.contextNotFound;
  17764. var contextKey = ns + o.nsseparator + key + '_' + options.context;
  17765. translated = translate(contextKey, optionWithoutCount);
  17766. if (translated != o.contextNotFound) {
  17767. return applyReplacement(translated, { context: options.context }); // apply replacement for context only
  17768. } // else continue translation with original/nonContext key
  17769. }
  17770. if (needsPlural(options, lngs[0])) {
  17771. optionWithoutCount = f.extend({ lngs: [lngs[0]]}, options);
  17772. delete optionWithoutCount.count;
  17773. delete optionWithoutCount.lng;
  17774. optionWithoutCount.defaultValue = o.pluralNotFound;
  17775. var pluralKey;
  17776. if (!pluralExtensions.needsPlural(lngs[0], options.count)) {
  17777. pluralKey = ns + o.nsseparator + key;
  17778. } else {
  17779. pluralKey = ns + o.nsseparator + key + o.pluralSuffix;
  17780. var pluralExtension = pluralExtensions.get(lngs[0], options.count);
  17781. if (pluralExtension >= 0) {
  17782. pluralKey = pluralKey + '_' + pluralExtension;
  17783. } else if (pluralExtension === 1) {
  17784. pluralKey = ns + o.nsseparator + key; // singular
  17785. }
  17786. }
  17787. translated = translate(pluralKey, optionWithoutCount);
  17788. if (translated != o.pluralNotFound) {
  17789. return applyReplacement(translated, {
  17790. count: options.count,
  17791. interpolationPrefix: options.interpolationPrefix,
  17792. interpolationSuffix: options.interpolationSuffix
  17793. }); // apply replacement for count only
  17794. } else if (lngs.length > 1) {
  17795. // remove failed lng
  17796. var clone = lngs.slice();
  17797. clone.shift();
  17798. options = f.extend(options, { lngs: clone });
  17799. delete options.lng;
  17800. // retry with fallbacks
  17801. translated = translate(ns + o.nsseparator + key, options);
  17802. if (translated != o.pluralNotFound) return translated;
  17803. } else {
  17804. return translated;
  17805. }
  17806. }
  17807. if (needsIndefiniteArticle(options)) {
  17808. var optionsWithoutIndef = f.extend({}, options);
  17809. delete optionsWithoutIndef.indefinite_article;
  17810. optionsWithoutIndef.defaultValue = o.indefiniteNotFound;
  17811. // If we don't have a count, we want the indefinite, if we do have a count, and needsPlural is false
  17812. var indefiniteKey = ns + o.nsseparator + key + (((options.count && !needsPlural(options, lngs[0])) || !options.count) ? o.indefiniteSuffix : "");
  17813. translated = translate(indefiniteKey, optionsWithoutIndef);
  17814. if (translated != o.indefiniteNotFound) {
  17815. return translated;
  17816. }
  17817. }
  17818. var found;
  17819. var keys = key.split(o.keyseparator);
  17820. for (var i = 0, len = lngs.length; i < len; i++ ) {
  17821. if (found !== undefined) break;
  17822. var l = lngs[i];
  17823. var x = 0;
  17824. var value = resStore[l] && resStore[l][ns];
  17825. while (keys[x]) {
  17826. value = value && value[keys[x]];
  17827. x++;
  17828. }
  17829. if (value !== undefined) {
  17830. var valueType = Object.prototype.toString.apply(value);
  17831. if (typeof value === 'string') {
  17832. value = applyReplacement(value, options);
  17833. value = applyReuse(value, options);
  17834. } else if (valueType === '[object Array]' && !o.returnObjectTrees && !options.returnObjectTrees) {
  17835. value = value.join('\n');
  17836. value = applyReplacement(value, options);
  17837. value = applyReuse(value, options);
  17838. } else if (value === null && o.fallbackOnNull === true) {
  17839. value = undefined;
  17840. } else if (value !== null) {
  17841. if (!o.returnObjectTrees && !options.returnObjectTrees) {
  17842. if (o.objectTreeKeyHandler && typeof o.objectTreeKeyHandler == 'function') {
  17843. value = o.objectTreeKeyHandler(key, value, l, ns, options);
  17844. } else {
  17845. value = 'key \'' + ns + ':' + key + ' (' + l + ')\' ' +
  17846. 'returned an object instead of string.';
  17847. f.log(value);
  17848. }
  17849. } else if (valueType !== '[object Number]' && valueType !== '[object Function]' && valueType !== '[object RegExp]') {
  17850. var copy = (valueType === '[object Array]') ? [] : {}; // apply child translation on a copy
  17851. f.each(value, function(m) {
  17852. copy[m] = _translate(ns + o.nsseparator + key + o.keyseparator + m, options);
  17853. });
  17854. value = copy;
  17855. }
  17856. }
  17857. if (typeof value === 'string' && value.trim() === '' && o.fallbackOnEmpty === true)
  17858. value = undefined;
  17859. found = value;
  17860. }
  17861. }
  17862. if (found === undefined && !options.isFallbackLookup && (o.fallbackToDefaultNS === true || (o.fallbackNS && o.fallbackNS.length > 0))) {
  17863. // set flag for fallback lookup - avoid recursion
  17864. options.isFallbackLookup = true;
  17865. if (o.fallbackNS.length) {
  17866. for (var y = 0, lenY = o.fallbackNS.length; y < lenY; y++) {
  17867. found = _find(o.fallbackNS[y] + o.nsseparator + key, options);
  17868. if (found || (found==="" && o.fallbackOnEmpty === false)) {
  17869. /* compare value without namespace */
  17870. var foundValue = found.indexOf(o.nsseparator) > -1 ? found.split(o.nsseparator)[1] : found
  17871. , notFoundValue = notFound.indexOf(o.nsseparator) > -1 ? notFound.split(o.nsseparator)[1] : notFound;
  17872. if (foundValue !== notFoundValue) break;
  17873. }
  17874. }
  17875. } else {
  17876. found = _find(key, options); // fallback to default NS
  17877. }
  17878. options.isFallbackLookup = false;
  17879. }
  17880. return found;
  17881. }
  17882. function detectLanguage() {
  17883. var detectedLng;
  17884. var whitelist = o.lngWhitelist || [];
  17885. var userLngChoices = [];
  17886. // get from qs
  17887. var qsParm = [];
  17888. if (typeof window !== 'undefined') {
  17889. (function() {
  17890. var query = window.location.search.substring(1);
  17891. var params = query.split('&');
  17892. for (var i=0; i<params.length; i++) {
  17893. var pos = params[i].indexOf('=');
  17894. if (pos > 0) {
  17895. var key = params[i].substring(0,pos);
  17896. if (key == o.detectLngQS) {
  17897. userLngChoices.push(params[i].substring(pos+1));
  17898. }
  17899. }
  17900. }
  17901. })();
  17902. }
  17903. // get from cookie
  17904. if (o.useCookie && typeof document !== 'undefined') {
  17905. var c = f.cookie.read(o.cookieName);
  17906. if (c) userLngChoices.push(c);
  17907. }
  17908. // get from localStorage
  17909. if (o.detectLngFromLocalStorage && typeof window !== 'undefined' && window.localStorage) {
  17910. userLngChoices.push(window.localStorage.getItem('i18next_lng'));
  17911. }
  17912. // get from navigator
  17913. if (typeof navigator !== 'undefined') {
  17914. if (navigator.languages) { // chrome only; not an array, so can't use .push.apply instead of iterating
  17915. for (var i=0;i<navigator.languages.length;i++) {
  17916. userLngChoices.push(navigator.languages[i]);
  17917. }
  17918. }
  17919. if (navigator.userLanguage) {
  17920. userLngChoices.push(navigator.userLanguage);
  17921. }
  17922. if (navigator.language) {
  17923. userLngChoices.push(navigator.language);
  17924. }
  17925. }
  17926. (function() {
  17927. for (var i=0;i<userLngChoices.length;i++) {
  17928. var lng = userLngChoices[i];
  17929. if (lng.indexOf('-') > -1) {
  17930. var parts = lng.split('-');
  17931. lng = o.lowerCaseLng ?
  17932. parts[0].toLowerCase() + '-' + parts[1].toLowerCase() :
  17933. parts[0].toLowerCase() + '-' + parts[1].toUpperCase();
  17934. }
  17935. if (whitelist.length === 0 || whitelist.indexOf(lng) > -1) {
  17936. detectedLng = lng;
  17937. break;
  17938. }
  17939. }
  17940. })();
  17941. //fallback
  17942. if (!detectedLng){
  17943. detectedLng = o.fallbackLng[0];
  17944. }
  17945. return detectedLng;
  17946. }
  17947. // definition http://translate.sourceforge.net/wiki/l10n/pluralforms
  17948. /* [code, name, numbers, pluralsType] */
  17949. var _rules = [
  17950. ["ach", "Acholi", [1,2], 1],
  17951. ["af", "Afrikaans",[1,2], 2],
  17952. ["ak", "Akan", [1,2], 1],
  17953. ["am", "Amharic", [1,2], 1],
  17954. ["an", "Aragonese",[1,2], 2],
  17955. ["ar", "Arabic", [0,1,2,3,11,100],5],
  17956. ["arn", "Mapudungun",[1,2], 1],
  17957. ["ast", "Asturian", [1,2], 2],
  17958. ["ay", "Aymará", [1], 3],
  17959. ["az", "Azerbaijani",[1,2],2],
  17960. ["be", "Belarusian",[1,2,5],4],
  17961. ["bg", "Bulgarian",[1,2], 2],
  17962. ["bn", "Bengali", [1,2], 2],
  17963. ["bo", "Tibetan", [1], 3],
  17964. ["br", "Breton", [1,2], 1],
  17965. ["bs", "Bosnian", [1,2,5],4],
  17966. ["ca", "Catalan", [1,2], 2],
  17967. ["cgg", "Chiga", [1], 3],
  17968. ["cs", "Czech", [1,2,5],6],
  17969. ["csb", "Kashubian",[1,2,5],7],
  17970. ["cy", "Welsh", [1,2,3,8],8],
  17971. ["da", "Danish", [1,2], 2],
  17972. ["de", "German", [1,2], 2],
  17973. ["dev", "Development Fallback", [1,2], 2],
  17974. ["dz", "Dzongkha", [1], 3],
  17975. ["el", "Greek", [1,2], 2],
  17976. ["en", "English", [1,2], 2],
  17977. ["eo", "Esperanto",[1,2], 2],
  17978. ["es", "Spanish", [1,2], 2],
  17979. ["es_ar","Argentinean Spanish", [1,2], 2],
  17980. ["et", "Estonian", [1,2], 2],
  17981. ["eu", "Basque", [1,2], 2],
  17982. ["fa", "Persian", [1], 3],
  17983. ["fi", "Finnish", [1,2], 2],
  17984. ["fil", "Filipino", [1,2], 1],
  17985. ["fo", "Faroese", [1,2], 2],
  17986. ["fr", "French", [1,2], 9],
  17987. ["fur", "Friulian", [1,2], 2],
  17988. ["fy", "Frisian", [1,2], 2],
  17989. ["ga", "Irish", [1,2,3,7,11],10],
  17990. ["gd", "Scottish Gaelic",[1,2,3,20],11],
  17991. ["gl", "Galician", [1,2], 2],
  17992. ["gu", "Gujarati", [1,2], 2],
  17993. ["gun", "Gun", [1,2], 1],
  17994. ["ha", "Hausa", [1,2], 2],
  17995. ["he", "Hebrew", [1,2], 2],
  17996. ["hi", "Hindi", [1,2], 2],
  17997. ["hr", "Croatian", [1,2,5],4],
  17998. ["hu", "Hungarian",[1,2], 2],
  17999. ["hy", "Armenian", [1,2], 2],
  18000. ["ia", "Interlingua",[1,2],2],
  18001. ["id", "Indonesian",[1], 3],
  18002. ["is", "Icelandic",[1,2], 12],
  18003. ["it", "Italian", [1,2], 2],
  18004. ["ja", "Japanese", [1], 3],
  18005. ["jbo", "Lojban", [1], 3],
  18006. ["jv", "Javanese", [0,1], 13],
  18007. ["ka", "Georgian", [1], 3],
  18008. ["kk", "Kazakh", [1], 3],
  18009. ["km", "Khmer", [1], 3],
  18010. ["kn", "Kannada", [1,2], 2],
  18011. ["ko", "Korean", [1], 3],
  18012. ["ku", "Kurdish", [1,2], 2],
  18013. ["kw", "Cornish", [1,2,3,4],14],
  18014. ["ky", "Kyrgyz", [1], 3],
  18015. ["lb", "Letzeburgesch",[1,2],2],
  18016. ["ln", "Lingala", [1,2], 1],
  18017. ["lo", "Lao", [1], 3],
  18018. ["lt", "Lithuanian",[1,2,10],15],
  18019. ["lv", "Latvian", [1,2,0],16],
  18020. ["mai", "Maithili", [1,2], 2],
  18021. ["mfe", "Mauritian Creole",[1,2],1],
  18022. ["mg", "Malagasy", [1,2], 1],
  18023. ["mi", "Maori", [1,2], 1],
  18024. ["mk", "Macedonian",[1,2],17],
  18025. ["ml", "Malayalam",[1,2], 2],
  18026. ["mn", "Mongolian",[1,2], 2],
  18027. ["mnk", "Mandinka", [0,1,2],18],
  18028. ["mr", "Marathi", [1,2], 2],
  18029. ["ms", "Malay", [1], 3],
  18030. ["mt", "Maltese", [1,2,11,20],19],
  18031. ["nah", "Nahuatl", [1,2], 2],
  18032. ["nap", "Neapolitan",[1,2], 2],
  18033. ["nb", "Norwegian Bokmal",[1,2],2],
  18034. ["ne", "Nepali", [1,2], 2],
  18035. ["nl", "Dutch", [1,2], 2],
  18036. ["nn", "Norwegian Nynorsk",[1,2],2],
  18037. ["no", "Norwegian",[1,2], 2],
  18038. ["nso", "Northern Sotho",[1,2],2],
  18039. ["oc", "Occitan", [1,2], 1],
  18040. ["or", "Oriya", [2,1], 2],
  18041. ["pa", "Punjabi", [1,2], 2],
  18042. ["pap", "Papiamento",[1,2], 2],
  18043. ["pl", "Polish", [1,2,5],7],
  18044. ["pms", "Piemontese",[1,2], 2],
  18045. ["ps", "Pashto", [1,2], 2],
  18046. ["pt", "Portuguese",[1,2], 2],
  18047. ["pt_br","Brazilian Portuguese",[1,2], 2],
  18048. ["rm", "Romansh", [1,2], 2],
  18049. ["ro", "Romanian", [1,2,20],20],
  18050. ["ru", "Russian", [1,2,5],4],
  18051. ["sah", "Yakut", [1], 3],
  18052. ["sco", "Scots", [1,2], 2],
  18053. ["se", "Northern Sami",[1,2], 2],
  18054. ["si", "Sinhala", [1,2], 2],
  18055. ["sk", "Slovak", [1,2,5],6],
  18056. ["sl", "Slovenian",[5,1,2,3],21],
  18057. ["so", "Somali", [1,2], 2],
  18058. ["son", "Songhay", [1,2], 2],
  18059. ["sq", "Albanian", [1,2], 2],
  18060. ["sr", "Serbian", [1,2,5],4],
  18061. ["su", "Sundanese",[1], 3],
  18062. ["sv", "Swedish", [1,2], 2],
  18063. ["sw", "Swahili", [1,2], 2],
  18064. ["ta", "Tamil", [1,2], 2],
  18065. ["te", "Telugu", [1,2], 2],
  18066. ["tg", "Tajik", [1,2], 1],
  18067. ["th", "Thai", [1], 3],
  18068. ["ti", "Tigrinya", [1,2], 1],
  18069. ["tk", "Turkmen", [1,2], 2],
  18070. ["tr", "Turkish", [1,2], 1],
  18071. ["tt", "Tatar", [1], 3],
  18072. ["ug", "Uyghur", [1], 3],
  18073. ["uk", "Ukrainian",[1,2,5],4],
  18074. ["ur", "Urdu", [1,2], 2],
  18075. ["uz", "Uzbek", [1,2], 1],
  18076. ["vi", "Vietnamese",[1], 3],
  18077. ["wa", "Walloon", [1,2], 1],
  18078. ["wo", "Wolof", [1], 3],
  18079. ["yo", "Yoruba", [1,2], 2],
  18080. ["zh", "Chinese", [1], 3]
  18081. ];
  18082. var _rulesPluralsTypes = {
  18083. 1: function(n) {return Number(n > 1);},
  18084. 2: function(n) {return Number(n != 1);},
  18085. 3: function(n) {return 0;},
  18086. 4: function(n) {return Number(n%10==1 && n%100!=11 ? 0 : n%10>=2 && n%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2);},
  18087. 5: function(n) {return Number(n===0 ? 0 : n==1 ? 1 : n==2 ? 2 : n%100>=3 && n%100<=10 ? 3 : n%100>=11 ? 4 : 5);},
  18088. 6: function(n) {return Number((n==1) ? 0 : (n>=2 && n<=4) ? 1 : 2);},
  18089. 7: function(n) {return Number(n==1 ? 0 : n%10>=2 && n%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2);},
  18090. 8: function(n) {return Number((n==1) ? 0 : (n==2) ? 1 : (n != 8 && n != 11) ? 2 : 3);},
  18091. 9: function(n) {return Number(n >= 2);},
  18092. 10: function(n) {return Number(n==1 ? 0 : n==2 ? 1 : n<7 ? 2 : n<11 ? 3 : 4) ;},
  18093. 11: function(n) {return Number((n==1 || n==11) ? 0 : (n==2 || n==12) ? 1 : (n > 2 && n < 20) ? 2 : 3);},
  18094. 12: function(n) {return Number(n%10!=1 || n%100==11);},
  18095. 13: function(n) {return Number(n !== 0);},
  18096. 14: function(n) {return Number((n==1) ? 0 : (n==2) ? 1 : (n == 3) ? 2 : 3);},
  18097. 15: function(n) {return Number(n%10==1 && n%100!=11 ? 0 : n%10>=2 && (n%100<10 || n%100>=20) ? 1 : 2);},
  18098. 16: function(n) {return Number(n%10==1 && n%100!=11 ? 0 : n !== 0 ? 1 : 2);},
  18099. 17: function(n) {return Number(n==1 || n%10==1 ? 0 : 1);},
  18100. 18: function(n) {return Number(0 ? 0 : n==1 ? 1 : 2);},
  18101. 19: function(n) {return Number(n==1 ? 0 : n===0 || ( n%100>1 && n%100<11) ? 1 : (n%100>10 && n%100<20 ) ? 2 : 3);},
  18102. 20: function(n) {return Number(n==1 ? 0 : (n===0 || (n%100 > 0 && n%100 < 20)) ? 1 : 2);},
  18103. 21: function(n) {return Number(n%100==1 ? 1 : n%100==2 ? 2 : n%100==3 || n%100==4 ? 3 : 0); }
  18104. };
  18105. var pluralExtensions = {
  18106. rules: (function () {
  18107. var l, rules = {};
  18108. for (l=_rules.length; l-- ;) {
  18109. rules[_rules[l][0]] = {
  18110. name: _rules[l][1],
  18111. numbers: _rules[l][2],
  18112. plurals: _rulesPluralsTypes[_rules[l][3]]
  18113. }
  18114. }
  18115. return rules;
  18116. }()),
  18117. // you can add your own pluralExtensions
  18118. addRule: function(lng, obj) {
  18119. pluralExtensions.rules[lng] = obj;
  18120. },
  18121. setCurrentLng: function(lng) {
  18122. if (!pluralExtensions.currentRule || pluralExtensions.currentRule.lng !== lng) {
  18123. var parts = lng.split('-');
  18124. pluralExtensions.currentRule = {
  18125. lng: lng,
  18126. rule: pluralExtensions.rules[parts[0]]
  18127. };
  18128. }
  18129. },
  18130. needsPlural: function(lng, count) {
  18131. var parts = lng.split('-');
  18132. var ext;
  18133. if (pluralExtensions.currentRule && pluralExtensions.currentRule.lng === lng) {
  18134. ext = pluralExtensions.currentRule.rule;
  18135. } else {
  18136. ext = pluralExtensions.rules[parts[f.getCountyIndexOfLng(lng)]];
  18137. }
  18138. if (ext && ext.numbers.length <= 1) {
  18139. return false;
  18140. } else {
  18141. return this.get(lng, count) !== 1;
  18142. }
  18143. },
  18144. get: function(lng, count) {
  18145. var parts = lng.split('-');
  18146. function getResult(l, c) {
  18147. var ext;
  18148. if (pluralExtensions.currentRule && pluralExtensions.currentRule.lng === lng) {
  18149. ext = pluralExtensions.currentRule.rule;
  18150. } else {
  18151. ext = pluralExtensions.rules[l];
  18152. }
  18153. if (ext) {
  18154. var i;
  18155. if (ext.noAbs) {
  18156. i = ext.plurals(c);
  18157. } else {
  18158. i = ext.plurals(Math.abs(c));
  18159. }
  18160. var number = ext.numbers[i];
  18161. if (ext.numbers.length === 2 && ext.numbers[0] === 1) {
  18162. if (number === 2) {
  18163. number = -1; // regular plural
  18164. } else if (number === 1) {
  18165. number = 1; // singular
  18166. }
  18167. }//console.log(count + '-' + number);
  18168. return number;
  18169. } else {
  18170. return c === 1 ? '1' : '-1';
  18171. }
  18172. }
  18173. return getResult(parts[f.getCountyIndexOfLng(lng)], count);
  18174. }
  18175. };
  18176. var postProcessors = {};
  18177. var addPostProcessor = function(name, fc) {
  18178. postProcessors[name] = fc;
  18179. };
  18180. // sprintf support
  18181. var sprintf = (function() {
  18182. function get_type(variable) {
  18183. return Object.prototype.toString.call(variable).slice(8, -1).toLowerCase();
  18184. }
  18185. function str_repeat(input, multiplier) {
  18186. for (var output = []; multiplier > 0; output[--multiplier] = input) {/* do nothing */}
  18187. return output.join('');
  18188. }
  18189. var str_format = function() {
  18190. if (!str_format.cache.hasOwnProperty(arguments[0])) {
  18191. str_format.cache[arguments[0]] = str_format.parse(arguments[0]);
  18192. }
  18193. return str_format.format.call(null, str_format.cache[arguments[0]], arguments);
  18194. };
  18195. str_format.format = function(parse_tree, argv) {
  18196. var cursor = 1, tree_length = parse_tree.length, node_type = '', arg, output = [], i, k, match, pad, pad_character, pad_length;
  18197. for (i = 0; i < tree_length; i++) {
  18198. node_type = get_type(parse_tree[i]);
  18199. if (node_type === 'string') {
  18200. output.push(parse_tree[i]);
  18201. }
  18202. else if (node_type === 'array') {
  18203. match = parse_tree[i]; // convenience purposes only
  18204. if (match[2]) { // keyword argument
  18205. arg = argv[cursor];
  18206. for (k = 0; k < match[2].length; k++) {
  18207. if (!arg.hasOwnProperty(match[2][k])) {
  18208. throw(sprintf('[sprintf] property "%s" does not exist', match[2][k]));
  18209. }
  18210. arg = arg[match[2][k]];
  18211. }
  18212. }
  18213. else if (match[1]) { // positional argument (explicit)
  18214. arg = argv[match[1]];
  18215. }
  18216. else { // positional argument (implicit)
  18217. arg = argv[cursor++];
  18218. }
  18219. if (/[^s]/.test(match[8]) && (get_type(arg) != 'number')) {
  18220. throw(sprintf('[sprintf] expecting number but found %s', get_type(arg)));
  18221. }
  18222. switch (match[8]) {
  18223. case 'b': arg = arg.toString(2); break;
  18224. case 'c': arg = String.fromCharCode(arg); break;
  18225. case 'd': arg = parseInt(arg, 10); break;
  18226. case 'e': arg = match[7] ? arg.toExponential(match[7]) : arg.toExponential(); break;
  18227. case 'f': arg = match[7] ? parseFloat(arg).toFixed(match[7]) : parseFloat(arg); break;
  18228. case 'o': arg = arg.toString(8); break;
  18229. case 's': arg = ((arg = String(arg)) && match[7] ? arg.substring(0, match[7]) : arg); break;
  18230. case 'u': arg = Math.abs(arg); break;
  18231. case 'x': arg = arg.toString(16); break;
  18232. case 'X': arg = arg.toString(16).toUpperCase(); break;
  18233. }
  18234. arg = (/[def]/.test(match[8]) && match[3] && arg >= 0 ? '+'+ arg : arg);
  18235. pad_character = match[4] ? match[4] == '0' ? '0' : match[4].charAt(1) : ' ';
  18236. pad_length = match[6] - String(arg).length;
  18237. pad = match[6] ? str_repeat(pad_character, pad_length) : '';
  18238. output.push(match[5] ? arg + pad : pad + arg);
  18239. }
  18240. }
  18241. return output.join('');
  18242. };
  18243. str_format.cache = {};
  18244. str_format.parse = function(fmt) {
  18245. var _fmt = fmt, match = [], parse_tree = [], arg_names = 0;
  18246. while (_fmt) {
  18247. if ((match = /^[^\x25]+/.exec(_fmt)) !== null) {
  18248. parse_tree.push(match[0]);
  18249. }
  18250. else if ((match = /^\x25{2}/.exec(_fmt)) !== null) {
  18251. parse_tree.push('%');
  18252. }
  18253. else if ((match = /^\x25(?:([1-9]\d*)\$|\(([^\)]+)\))?(\+)?(0|'[^$])?(-)?(\d+)?(?:\.(\d+))?([b-fosuxX])/.exec(_fmt)) !== null) {
  18254. if (match[2]) {
  18255. arg_names |= 1;
  18256. var field_list = [], replacement_field = match[2], field_match = [];
  18257. if ((field_match = /^([a-z_][a-z_\d]*)/i.exec(replacement_field)) !== null) {
  18258. field_list.push(field_match[1]);
  18259. while ((replacement_field = replacement_field.substring(field_match[0].length)) !== '') {
  18260. if ((field_match = /^\.([a-z_][a-z_\d]*)/i.exec(replacement_field)) !== null) {
  18261. field_list.push(field_match[1]);
  18262. }
  18263. else if ((field_match = /^\[(\d+)\]/.exec(replacement_field)) !== null) {
  18264. field_list.push(field_match[1]);
  18265. }
  18266. else {
  18267. throw('[sprintf] huh?');
  18268. }
  18269. }
  18270. }
  18271. else {
  18272. throw('[sprintf] huh?');
  18273. }
  18274. match[2] = field_list;
  18275. }
  18276. else {
  18277. arg_names |= 2;
  18278. }
  18279. if (arg_names === 3) {
  18280. throw('[sprintf] mixing positional and named placeholders is not (yet) supported');
  18281. }
  18282. parse_tree.push(match);
  18283. }
  18284. else {
  18285. throw('[sprintf] huh?');
  18286. }
  18287. _fmt = _fmt.substring(match[0].length);
  18288. }
  18289. return parse_tree;
  18290. };
  18291. return str_format;
  18292. })();
  18293. var vsprintf = function(fmt, argv) {
  18294. argv.unshift(fmt);
  18295. return sprintf.apply(null, argv);
  18296. };
  18297. addPostProcessor("sprintf", function(val, key, opts) {
  18298. if (!opts.sprintf) return val;
  18299. if (Object.prototype.toString.apply(opts.sprintf) === '[object Array]') {
  18300. return vsprintf(val, opts.sprintf);
  18301. } else if (typeof opts.sprintf === 'object') {
  18302. return sprintf(val, opts.sprintf);
  18303. }
  18304. return val;
  18305. });
  18306. // public api interface
  18307. i18n.init = init;
  18308. i18n.setLng = setLng;
  18309. i18n.preload = preload;
  18310. i18n.addResourceBundle = addResourceBundle;
  18311. i18n.hasResourceBundle = hasResourceBundle;
  18312. i18n.addResource = addResource;
  18313. i18n.addResources = addResources;
  18314. i18n.removeResourceBundle = removeResourceBundle;
  18315. i18n.loadNamespace = loadNamespace;
  18316. i18n.loadNamespaces = loadNamespaces;
  18317. i18n.setDefaultNamespace = setDefaultNamespace;
  18318. i18n.t = translate;
  18319. i18n.translate = translate;
  18320. i18n.exists = exists;
  18321. i18n.detectLanguage = f.detectLanguage;
  18322. i18n.pluralExtensions = pluralExtensions;
  18323. i18n.sync = sync;
  18324. i18n.functions = f;
  18325. i18n.lng = lng;
  18326. i18n.addPostProcessor = addPostProcessor;
  18327. i18n.options = o;
  18328. })();
  18329. },{"jquery":"jquery"}],66:[function(require,module,exports){
  18330. // Top level file is just a mixin of submodules & constants
  18331. 'use strict';
  18332. var assign = require('./lib/utils/common').assign;
  18333. var deflate = require('./lib/deflate');
  18334. var inflate = require('./lib/inflate');
  18335. var constants = require('./lib/zlib/constants');
  18336. var pako = {};
  18337. assign(pako, deflate, inflate, constants);
  18338. module.exports = pako;
  18339. },{"./lib/deflate":67,"./lib/inflate":68,"./lib/utils/common":69,"./lib/zlib/constants":72}],67:[function(require,module,exports){
  18340. 'use strict';
  18341. var zlib_deflate = require('./zlib/deflate.js');
  18342. var utils = require('./utils/common');
  18343. var strings = require('./utils/strings');
  18344. var msg = require('./zlib/messages');
  18345. var zstream = require('./zlib/zstream');
  18346. var toString = Object.prototype.toString;
  18347. /* Public constants ==========================================================*/
  18348. /* ===========================================================================*/
  18349. var Z_NO_FLUSH = 0;
  18350. var Z_FINISH = 4;
  18351. var Z_OK = 0;
  18352. var Z_STREAM_END = 1;
  18353. var Z_DEFAULT_COMPRESSION = -1;
  18354. var Z_DEFAULT_STRATEGY = 0;
  18355. var Z_DEFLATED = 8;
  18356. /* ===========================================================================*/
  18357. /**
  18358. * class Deflate
  18359. *
  18360. * Generic JS-style wrapper for zlib calls. If you don't need
  18361. * streaming behaviour - use more simple functions: [[deflate]],
  18362. * [[deflateRaw]] and [[gzip]].
  18363. **/
  18364. /* internal
  18365. * Deflate.chunks -> Array
  18366. *
  18367. * Chunks of output data, if [[Deflate#onData]] not overriden.
  18368. **/
  18369. /**
  18370. * Deflate.result -> Uint8Array|Array
  18371. *
  18372. * Compressed result, generated by default [[Deflate#onData]]
  18373. * and [[Deflate#onEnd]] handlers. Filled after you push last chunk
  18374. * (call [[Deflate#push]] with `Z_FINISH` / `true` param).
  18375. **/
  18376. /**
  18377. * Deflate.err -> Number
  18378. *
  18379. * Error code after deflate finished. 0 (Z_OK) on success.
  18380. * You will not need it in real life, because deflate errors
  18381. * are possible only on wrong options or bad `onData` / `onEnd`
  18382. * custom handlers.
  18383. **/
  18384. /**
  18385. * Deflate.msg -> String
  18386. *
  18387. * Error message, if [[Deflate.err]] != 0
  18388. **/
  18389. /**
  18390. * new Deflate(options)
  18391. * - options (Object): zlib deflate options.
  18392. *
  18393. * Creates new deflator instance with specified params. Throws exception
  18394. * on bad params. Supported options:
  18395. *
  18396. * - `level`
  18397. * - `windowBits`
  18398. * - `memLevel`
  18399. * - `strategy`
  18400. *
  18401. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  18402. * for more information on these.
  18403. *
  18404. * Additional options, for internal needs:
  18405. *
  18406. * - `chunkSize` - size of generated data chunks (16K by default)
  18407. * - `raw` (Boolean) - do raw deflate
  18408. * - `gzip` (Boolean) - create gzip wrapper
  18409. * - `to` (String) - if equal to 'string', then result will be "binary string"
  18410. * (each char code [0..255])
  18411. * - `header` (Object) - custom header for gzip
  18412. * - `text` (Boolean) - true if compressed data believed to be text
  18413. * - `time` (Number) - modification time, unix timestamp
  18414. * - `os` (Number) - operation system code
  18415. * - `extra` (Array) - array of bytes with extra data (max 65536)
  18416. * - `name` (String) - file name (binary string)
  18417. * - `comment` (String) - comment (binary string)
  18418. * - `hcrc` (Boolean) - true if header crc should be added
  18419. *
  18420. * ##### Example:
  18421. *
  18422. * ```javascript
  18423. * var pako = require('pako')
  18424. * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
  18425. * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
  18426. *
  18427. * var deflate = new pako.Deflate({ level: 3});
  18428. *
  18429. * deflate.push(chunk1, false);
  18430. * deflate.push(chunk2, true); // true -> last chunk
  18431. *
  18432. * if (deflate.err) { throw new Error(deflate.err); }
  18433. *
  18434. * console.log(deflate.result);
  18435. * ```
  18436. **/
  18437. var Deflate = function(options) {
  18438. this.options = utils.assign({
  18439. level: Z_DEFAULT_COMPRESSION,
  18440. method: Z_DEFLATED,
  18441. chunkSize: 16384,
  18442. windowBits: 15,
  18443. memLevel: 8,
  18444. strategy: Z_DEFAULT_STRATEGY,
  18445. to: ''
  18446. }, options || {});
  18447. var opt = this.options;
  18448. if (opt.raw && (opt.windowBits > 0)) {
  18449. opt.windowBits = -opt.windowBits;
  18450. }
  18451. else if (opt.gzip && (opt.windowBits > 0) && (opt.windowBits < 16)) {
  18452. opt.windowBits += 16;
  18453. }
  18454. this.err = 0; // error code, if happens (0 = Z_OK)
  18455. this.msg = ''; // error message
  18456. this.ended = false; // used to avoid multiple onEnd() calls
  18457. this.chunks = []; // chunks of compressed data
  18458. this.strm = new zstream();
  18459. this.strm.avail_out = 0;
  18460. var status = zlib_deflate.deflateInit2(
  18461. this.strm,
  18462. opt.level,
  18463. opt.method,
  18464. opt.windowBits,
  18465. opt.memLevel,
  18466. opt.strategy
  18467. );
  18468. if (status !== Z_OK) {
  18469. throw new Error(msg[status]);
  18470. }
  18471. if (opt.header) {
  18472. zlib_deflate.deflateSetHeader(this.strm, opt.header);
  18473. }
  18474. };
  18475. /**
  18476. * Deflate#push(data[, mode]) -> Boolean
  18477. * - data (Uint8Array|Array|ArrayBuffer|String): input data. Strings will be
  18478. * converted to utf8 byte sequence.
  18479. * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
  18480. * See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH.
  18481. *
  18482. * Sends input data to deflate pipe, generating [[Deflate#onData]] calls with
  18483. * new compressed chunks. Returns `true` on success. The last data block must have
  18484. * mode Z_FINISH (or `true`). That flush internal pending buffers and call
  18485. * [[Deflate#onEnd]].
  18486. *
  18487. * On fail call [[Deflate#onEnd]] with error code and return false.
  18488. *
  18489. * We strongly recommend to use `Uint8Array` on input for best speed (output
  18490. * array format is detected automatically). Also, don't skip last param and always
  18491. * use the same type in your code (boolean or number). That will improve JS speed.
  18492. *
  18493. * For regular `Array`-s make sure all elements are [0..255].
  18494. *
  18495. * ##### Example
  18496. *
  18497. * ```javascript
  18498. * push(chunk, false); // push one of data chunks
  18499. * ...
  18500. * push(chunk, true); // push last chunk
  18501. * ```
  18502. **/
  18503. Deflate.prototype.push = function(data, mode) {
  18504. var strm = this.strm;
  18505. var chunkSize = this.options.chunkSize;
  18506. var status, _mode;
  18507. if (this.ended) { return false; }
  18508. _mode = (mode === ~~mode) ? mode : ((mode === true) ? Z_FINISH : Z_NO_FLUSH);
  18509. // Convert data if needed
  18510. if (typeof data === 'string') {
  18511. // If we need to compress text, change encoding to utf8.
  18512. strm.input = strings.string2buf(data);
  18513. } else if (toString.call(data) === '[object ArrayBuffer]') {
  18514. strm.input = new Uint8Array(data);
  18515. } else {
  18516. strm.input = data;
  18517. }
  18518. strm.next_in = 0;
  18519. strm.avail_in = strm.input.length;
  18520. do {
  18521. if (strm.avail_out === 0) {
  18522. strm.output = new utils.Buf8(chunkSize);
  18523. strm.next_out = 0;
  18524. strm.avail_out = chunkSize;
  18525. }
  18526. status = zlib_deflate.deflate(strm, _mode); /* no bad return value */
  18527. if (status !== Z_STREAM_END && status !== Z_OK) {
  18528. this.onEnd(status);
  18529. this.ended = true;
  18530. return false;
  18531. }
  18532. if (strm.avail_out === 0 || (strm.avail_in === 0 && _mode === Z_FINISH)) {
  18533. if (this.options.to === 'string') {
  18534. this.onData(strings.buf2binstring(utils.shrinkBuf(strm.output, strm.next_out)));
  18535. } else {
  18536. this.onData(utils.shrinkBuf(strm.output, strm.next_out));
  18537. }
  18538. }
  18539. } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== Z_STREAM_END);
  18540. // Finalize on the last chunk.
  18541. if (_mode === Z_FINISH) {
  18542. status = zlib_deflate.deflateEnd(this.strm);
  18543. this.onEnd(status);
  18544. this.ended = true;
  18545. return status === Z_OK;
  18546. }
  18547. return true;
  18548. };
  18549. /**
  18550. * Deflate#onData(chunk) -> Void
  18551. * - chunk (Uint8Array|Array|String): ouput data. Type of array depends
  18552. * on js engine support. When string output requested, each chunk
  18553. * will be string.
  18554. *
  18555. * By default, stores data blocks in `chunks[]` property and glue
  18556. * those in `onEnd`. Override this handler, if you need another behaviour.
  18557. **/
  18558. Deflate.prototype.onData = function(chunk) {
  18559. this.chunks.push(chunk);
  18560. };
  18561. /**
  18562. * Deflate#onEnd(status) -> Void
  18563. * - status (Number): deflate status. 0 (Z_OK) on success,
  18564. * other if not.
  18565. *
  18566. * Called once after you tell deflate that input stream complete
  18567. * or error happenned. By default - join collected chunks,
  18568. * free memory and fill `results` / `err` properties.
  18569. **/
  18570. Deflate.prototype.onEnd = function(status) {
  18571. // On success - join
  18572. if (status === Z_OK) {
  18573. if (this.options.to === 'string') {
  18574. this.result = this.chunks.join('');
  18575. } else {
  18576. this.result = utils.flattenChunks(this.chunks);
  18577. }
  18578. }
  18579. this.chunks = [];
  18580. this.err = status;
  18581. this.msg = this.strm.msg;
  18582. };
  18583. /**
  18584. * deflate(data[, options]) -> Uint8Array|Array|String
  18585. * - data (Uint8Array|Array|String): input data to compress.
  18586. * - options (Object): zlib deflate options.
  18587. *
  18588. * Compress `data` with deflate alrorythm and `options`.
  18589. *
  18590. * Supported options are:
  18591. *
  18592. * - level
  18593. * - windowBits
  18594. * - memLevel
  18595. * - strategy
  18596. *
  18597. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  18598. * for more information on these.
  18599. *
  18600. * Sugar (options):
  18601. *
  18602. * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
  18603. * negative windowBits implicitly.
  18604. * - `to` (String) - if equal to 'string', then result will be "binary string"
  18605. * (each char code [0..255])
  18606. *
  18607. * ##### Example:
  18608. *
  18609. * ```javascript
  18610. * var pako = require('pako')
  18611. * , data = Uint8Array([1,2,3,4,5,6,7,8,9]);
  18612. *
  18613. * console.log(pako.deflate(data));
  18614. * ```
  18615. **/
  18616. function deflate(input, options) {
  18617. var deflator = new Deflate(options);
  18618. deflator.push(input, true);
  18619. // That will never happens, if you don't cheat with options :)
  18620. if (deflator.err) { throw deflator.msg; }
  18621. return deflator.result;
  18622. }
  18623. /**
  18624. * deflateRaw(data[, options]) -> Uint8Array|Array|String
  18625. * - data (Uint8Array|Array|String): input data to compress.
  18626. * - options (Object): zlib deflate options.
  18627. *
  18628. * The same as [[deflate]], but creates raw data, without wrapper
  18629. * (header and adler32 crc).
  18630. **/
  18631. function deflateRaw(input, options) {
  18632. options = options || {};
  18633. options.raw = true;
  18634. return deflate(input, options);
  18635. }
  18636. /**
  18637. * gzip(data[, options]) -> Uint8Array|Array|String
  18638. * - data (Uint8Array|Array|String): input data to compress.
  18639. * - options (Object): zlib deflate options.
  18640. *
  18641. * The same as [[deflate]], but create gzip wrapper instead of
  18642. * deflate one.
  18643. **/
  18644. function gzip(input, options) {
  18645. options = options || {};
  18646. options.gzip = true;
  18647. return deflate(input, options);
  18648. }
  18649. exports.Deflate = Deflate;
  18650. exports.deflate = deflate;
  18651. exports.deflateRaw = deflateRaw;
  18652. exports.gzip = gzip;
  18653. },{"./utils/common":69,"./utils/strings":70,"./zlib/deflate.js":74,"./zlib/messages":79,"./zlib/zstream":81}],68:[function(require,module,exports){
  18654. 'use strict';
  18655. var zlib_inflate = require('./zlib/inflate.js');
  18656. var utils = require('./utils/common');
  18657. var strings = require('./utils/strings');
  18658. var c = require('./zlib/constants');
  18659. var msg = require('./zlib/messages');
  18660. var zstream = require('./zlib/zstream');
  18661. var gzheader = require('./zlib/gzheader');
  18662. var toString = Object.prototype.toString;
  18663. /**
  18664. * class Inflate
  18665. *
  18666. * Generic JS-style wrapper for zlib calls. If you don't need
  18667. * streaming behaviour - use more simple functions: [[inflate]]
  18668. * and [[inflateRaw]].
  18669. **/
  18670. /* internal
  18671. * inflate.chunks -> Array
  18672. *
  18673. * Chunks of output data, if [[Inflate#onData]] not overriden.
  18674. **/
  18675. /**
  18676. * Inflate.result -> Uint8Array|Array|String
  18677. *
  18678. * Uncompressed result, generated by default [[Inflate#onData]]
  18679. * and [[Inflate#onEnd]] handlers. Filled after you push last chunk
  18680. * (call [[Inflate#push]] with `Z_FINISH` / `true` param).
  18681. **/
  18682. /**
  18683. * Inflate.err -> Number
  18684. *
  18685. * Error code after inflate finished. 0 (Z_OK) on success.
  18686. * Should be checked if broken data possible.
  18687. **/
  18688. /**
  18689. * Inflate.msg -> String
  18690. *
  18691. * Error message, if [[Inflate.err]] != 0
  18692. **/
  18693. /**
  18694. * new Inflate(options)
  18695. * - options (Object): zlib inflate options.
  18696. *
  18697. * Creates new inflator instance with specified params. Throws exception
  18698. * on bad params. Supported options:
  18699. *
  18700. * - `windowBits`
  18701. *
  18702. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  18703. * for more information on these.
  18704. *
  18705. * Additional options, for internal needs:
  18706. *
  18707. * - `chunkSize` - size of generated data chunks (16K by default)
  18708. * - `raw` (Boolean) - do raw inflate
  18709. * - `to` (String) - if equal to 'string', then result will be converted
  18710. * from utf8 to utf16 (javascript) string. When string output requested,
  18711. * chunk length can differ from `chunkSize`, depending on content.
  18712. *
  18713. * By default, when no options set, autodetect deflate/gzip data format via
  18714. * wrapper header.
  18715. *
  18716. * ##### Example:
  18717. *
  18718. * ```javascript
  18719. * var pako = require('pako')
  18720. * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
  18721. * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
  18722. *
  18723. * var inflate = new pako.Inflate({ level: 3});
  18724. *
  18725. * inflate.push(chunk1, false);
  18726. * inflate.push(chunk2, true); // true -> last chunk
  18727. *
  18728. * if (inflate.err) { throw new Error(inflate.err); }
  18729. *
  18730. * console.log(inflate.result);
  18731. * ```
  18732. **/
  18733. var Inflate = function(options) {
  18734. this.options = utils.assign({
  18735. chunkSize: 16384,
  18736. windowBits: 0,
  18737. to: ''
  18738. }, options || {});
  18739. var opt = this.options;
  18740. // Force window size for `raw` data, if not set directly,
  18741. // because we have no header for autodetect.
  18742. if (opt.raw && (opt.windowBits >= 0) && (opt.windowBits < 16)) {
  18743. opt.windowBits = -opt.windowBits;
  18744. if (opt.windowBits === 0) { opt.windowBits = -15; }
  18745. }
  18746. // If `windowBits` not defined (and mode not raw) - set autodetect flag for gzip/deflate
  18747. if ((opt.windowBits >= 0) && (opt.windowBits < 16) &&
  18748. !(options && options.windowBits)) {
  18749. opt.windowBits += 32;
  18750. }
  18751. // Gzip header has no info about windows size, we can do autodetect only
  18752. // for deflate. So, if window size not set, force it to max when gzip possible
  18753. if ((opt.windowBits > 15) && (opt.windowBits < 48)) {
  18754. // bit 3 (16) -> gzipped data
  18755. // bit 4 (32) -> autodetect gzip/deflate
  18756. if ((opt.windowBits & 15) === 0) {
  18757. opt.windowBits |= 15;
  18758. }
  18759. }
  18760. this.err = 0; // error code, if happens (0 = Z_OK)
  18761. this.msg = ''; // error message
  18762. this.ended = false; // used to avoid multiple onEnd() calls
  18763. this.chunks = []; // chunks of compressed data
  18764. this.strm = new zstream();
  18765. this.strm.avail_out = 0;
  18766. var status = zlib_inflate.inflateInit2(
  18767. this.strm,
  18768. opt.windowBits
  18769. );
  18770. if (status !== c.Z_OK) {
  18771. throw new Error(msg[status]);
  18772. }
  18773. this.header = new gzheader();
  18774. zlib_inflate.inflateGetHeader(this.strm, this.header);
  18775. };
  18776. /**
  18777. * Inflate#push(data[, mode]) -> Boolean
  18778. * - data (Uint8Array|Array|ArrayBuffer|String): input data
  18779. * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
  18780. * See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH.
  18781. *
  18782. * Sends input data to inflate pipe, generating [[Inflate#onData]] calls with
  18783. * new output chunks. Returns `true` on success. The last data block must have
  18784. * mode Z_FINISH (or `true`). That flush internal pending buffers and call
  18785. * [[Inflate#onEnd]].
  18786. *
  18787. * On fail call [[Inflate#onEnd]] with error code and return false.
  18788. *
  18789. * We strongly recommend to use `Uint8Array` on input for best speed (output
  18790. * format is detected automatically). Also, don't skip last param and always
  18791. * use the same type in your code (boolean or number). That will improve JS speed.
  18792. *
  18793. * For regular `Array`-s make sure all elements are [0..255].
  18794. *
  18795. * ##### Example
  18796. *
  18797. * ```javascript
  18798. * push(chunk, false); // push one of data chunks
  18799. * ...
  18800. * push(chunk, true); // push last chunk
  18801. * ```
  18802. **/
  18803. Inflate.prototype.push = function(data, mode) {
  18804. var strm = this.strm;
  18805. var chunkSize = this.options.chunkSize;
  18806. var status, _mode;
  18807. var next_out_utf8, tail, utf8str;
  18808. if (this.ended) { return false; }
  18809. _mode = (mode === ~~mode) ? mode : ((mode === true) ? c.Z_FINISH : c.Z_NO_FLUSH);
  18810. // Convert data if needed
  18811. if (typeof data === 'string') {
  18812. // Only binary strings can be decompressed on practice
  18813. strm.input = strings.binstring2buf(data);
  18814. } else if (toString.call(data) === '[object ArrayBuffer]') {
  18815. strm.input = new Uint8Array(data);
  18816. } else {
  18817. strm.input = data;
  18818. }
  18819. strm.next_in = 0;
  18820. strm.avail_in = strm.input.length;
  18821. do {
  18822. if (strm.avail_out === 0) {
  18823. strm.output = new utils.Buf8(chunkSize);
  18824. strm.next_out = 0;
  18825. strm.avail_out = chunkSize;
  18826. }
  18827. status = zlib_inflate.inflate(strm, c.Z_NO_FLUSH); /* no bad return value */
  18828. if (status !== c.Z_STREAM_END && status !== c.Z_OK) {
  18829. this.onEnd(status);
  18830. this.ended = true;
  18831. return false;
  18832. }
  18833. if (strm.next_out) {
  18834. if (strm.avail_out === 0 || status === c.Z_STREAM_END || (strm.avail_in === 0 && _mode === c.Z_FINISH)) {
  18835. if (this.options.to === 'string') {
  18836. next_out_utf8 = strings.utf8border(strm.output, strm.next_out);
  18837. tail = strm.next_out - next_out_utf8;
  18838. utf8str = strings.buf2string(strm.output, next_out_utf8);
  18839. // move tail
  18840. strm.next_out = tail;
  18841. strm.avail_out = chunkSize - tail;
  18842. if (tail) { utils.arraySet(strm.output, strm.output, next_out_utf8, tail, 0); }
  18843. this.onData(utf8str);
  18844. } else {
  18845. this.onData(utils.shrinkBuf(strm.output, strm.next_out));
  18846. }
  18847. }
  18848. }
  18849. } while ((strm.avail_in > 0) && status !== c.Z_STREAM_END);
  18850. if (status === c.Z_STREAM_END) {
  18851. _mode = c.Z_FINISH;
  18852. }
  18853. // Finalize on the last chunk.
  18854. if (_mode === c.Z_FINISH) {
  18855. status = zlib_inflate.inflateEnd(this.strm);
  18856. this.onEnd(status);
  18857. this.ended = true;
  18858. return status === c.Z_OK;
  18859. }
  18860. return true;
  18861. };
  18862. /**
  18863. * Inflate#onData(chunk) -> Void
  18864. * - chunk (Uint8Array|Array|String): ouput data. Type of array depends
  18865. * on js engine support. When string output requested, each chunk
  18866. * will be string.
  18867. *
  18868. * By default, stores data blocks in `chunks[]` property and glue
  18869. * those in `onEnd`. Override this handler, if you need another behaviour.
  18870. **/
  18871. Inflate.prototype.onData = function(chunk) {
  18872. this.chunks.push(chunk);
  18873. };
  18874. /**
  18875. * Inflate#onEnd(status) -> Void
  18876. * - status (Number): inflate status. 0 (Z_OK) on success,
  18877. * other if not.
  18878. *
  18879. * Called once after you tell inflate that input stream complete
  18880. * or error happenned. By default - join collected chunks,
  18881. * free memory and fill `results` / `err` properties.
  18882. **/
  18883. Inflate.prototype.onEnd = function(status) {
  18884. // On success - join
  18885. if (status === c.Z_OK) {
  18886. if (this.options.to === 'string') {
  18887. // Glue & convert here, until we teach pako to send
  18888. // utf8 alligned strings to onData
  18889. this.result = this.chunks.join('');
  18890. } else {
  18891. this.result = utils.flattenChunks(this.chunks);
  18892. }
  18893. }
  18894. this.chunks = [];
  18895. this.err = status;
  18896. this.msg = this.strm.msg;
  18897. };
  18898. /**
  18899. * inflate(data[, options]) -> Uint8Array|Array|String
  18900. * - data (Uint8Array|Array|String): input data to decompress.
  18901. * - options (Object): zlib inflate options.
  18902. *
  18903. * Decompress `data` with inflate/ungzip and `options`. Autodetect
  18904. * format via wrapper header by default. That's why we don't provide
  18905. * separate `ungzip` method.
  18906. *
  18907. * Supported options are:
  18908. *
  18909. * - windowBits
  18910. *
  18911. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  18912. * for more information.
  18913. *
  18914. * Sugar (options):
  18915. *
  18916. * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
  18917. * negative windowBits implicitly.
  18918. * - `to` (String) - if equal to 'string', then result will be converted
  18919. * from utf8 to utf16 (javascript) string. When string output requested,
  18920. * chunk length can differ from `chunkSize`, depending on content.
  18921. *
  18922. *
  18923. * ##### Example:
  18924. *
  18925. * ```javascript
  18926. * var pako = require('pako')
  18927. * , input = pako.deflate([1,2,3,4,5,6,7,8,9])
  18928. * , output;
  18929. *
  18930. * try {
  18931. * output = pako.inflate(input);
  18932. * } catch (err)
  18933. * console.log(err);
  18934. * }
  18935. * ```
  18936. **/
  18937. function inflate(input, options) {
  18938. var inflator = new Inflate(options);
  18939. inflator.push(input, true);
  18940. // That will never happens, if you don't cheat with options :)
  18941. if (inflator.err) { throw inflator.msg; }
  18942. return inflator.result;
  18943. }
  18944. /**
  18945. * inflateRaw(data[, options]) -> Uint8Array|Array|String
  18946. * - data (Uint8Array|Array|String): input data to decompress.
  18947. * - options (Object): zlib inflate options.
  18948. *
  18949. * The same as [[inflate]], but creates raw data, without wrapper
  18950. * (header and adler32 crc).
  18951. **/
  18952. function inflateRaw(input, options) {
  18953. options = options || {};
  18954. options.raw = true;
  18955. return inflate(input, options);
  18956. }
  18957. /**
  18958. * ungzip(data[, options]) -> Uint8Array|Array|String
  18959. * - data (Uint8Array|Array|String): input data to decompress.
  18960. * - options (Object): zlib inflate options.
  18961. *
  18962. * Just shortcut to [[inflate]], because it autodetects format
  18963. * by header.content. Done for convenience.
  18964. **/
  18965. exports.Inflate = Inflate;
  18966. exports.inflate = inflate;
  18967. exports.inflateRaw = inflateRaw;
  18968. exports.ungzip = inflate;
  18969. },{"./utils/common":69,"./utils/strings":70,"./zlib/constants":72,"./zlib/gzheader":75,"./zlib/inflate.js":77,"./zlib/messages":79,"./zlib/zstream":81}],69:[function(require,module,exports){
  18970. 'use strict';
  18971. var TYPED_OK = (typeof Uint8Array !== 'undefined') &&
  18972. (typeof Uint16Array !== 'undefined') &&
  18973. (typeof Int32Array !== 'undefined');
  18974. exports.assign = function (obj /*from1, from2, from3, ...*/) {
  18975. var sources = Array.prototype.slice.call(arguments, 1);
  18976. while (sources.length) {
  18977. var source = sources.shift();
  18978. if (!source) { continue; }
  18979. if (typeof(source) !== 'object') {
  18980. throw new TypeError(source + 'must be non-object');
  18981. }
  18982. for (var p in source) {
  18983. if (source.hasOwnProperty(p)) {
  18984. obj[p] = source[p];
  18985. }
  18986. }
  18987. }
  18988. return obj;
  18989. };
  18990. // reduce buffer size, avoiding mem copy
  18991. exports.shrinkBuf = function (buf, size) {
  18992. if (buf.length === size) { return buf; }
  18993. if (buf.subarray) { return buf.subarray(0, size); }
  18994. buf.length = size;
  18995. return buf;
  18996. };
  18997. var fnTyped = {
  18998. arraySet: function (dest, src, src_offs, len, dest_offs) {
  18999. if (src.subarray && dest.subarray) {
  19000. dest.set(src.subarray(src_offs, src_offs+len), dest_offs);
  19001. return;
  19002. }
  19003. // Fallback to ordinary array
  19004. for(var i=0; i<len; i++) {
  19005. dest[dest_offs + i] = src[src_offs + i];
  19006. }
  19007. },
  19008. // Join array of chunks to single array.
  19009. flattenChunks: function(chunks) {
  19010. var i, l, len, pos, chunk, result;
  19011. // calculate data length
  19012. len = 0;
  19013. for (i=0, l=chunks.length; i<l; i++) {
  19014. len += chunks[i].length;
  19015. }
  19016. // join chunks
  19017. result = new Uint8Array(len);
  19018. pos = 0;
  19019. for (i=0, l=chunks.length; i<l; i++) {
  19020. chunk = chunks[i];
  19021. result.set(chunk, pos);
  19022. pos += chunk.length;
  19023. }
  19024. return result;
  19025. }
  19026. };
  19027. var fnUntyped = {
  19028. arraySet: function (dest, src, src_offs, len, dest_offs) {
  19029. for(var i=0; i<len; i++) {
  19030. dest[dest_offs + i] = src[src_offs + i];
  19031. }
  19032. },
  19033. // Join array of chunks to single array.
  19034. flattenChunks: function(chunks) {
  19035. return [].concat.apply([], chunks);
  19036. }
  19037. };
  19038. // Enable/Disable typed arrays use, for testing
  19039. //
  19040. exports.setTyped = function (on) {
  19041. if (on) {
  19042. exports.Buf8 = Uint8Array;
  19043. exports.Buf16 = Uint16Array;
  19044. exports.Buf32 = Int32Array;
  19045. exports.assign(exports, fnTyped);
  19046. } else {
  19047. exports.Buf8 = Array;
  19048. exports.Buf16 = Array;
  19049. exports.Buf32 = Array;
  19050. exports.assign(exports, fnUntyped);
  19051. }
  19052. };
  19053. exports.setTyped(TYPED_OK);
  19054. },{}],70:[function(require,module,exports){
  19055. // String encode/decode helpers
  19056. 'use strict';
  19057. var utils = require('./common');
  19058. // Quick check if we can use fast array to bin string conversion
  19059. //
  19060. // - apply(Array) can fail on Android 2.2
  19061. // - apply(Uint8Array) can fail on iOS 5.1 Safary
  19062. //
  19063. var STR_APPLY_OK = true;
  19064. var STR_APPLY_UIA_OK = true;
  19065. try { String.fromCharCode.apply(null, [0]); } catch(__) { STR_APPLY_OK = false; }
  19066. try { String.fromCharCode.apply(null, new Uint8Array(1)); } catch(__) { STR_APPLY_UIA_OK = false; }
  19067. // Table with utf8 lengths (calculated by first byte of sequence)
  19068. // Note, that 5 & 6-byte values and some 4-byte values can not be represented in JS,
  19069. // because max possible codepoint is 0x10ffff
  19070. var _utf8len = new utils.Buf8(256);
  19071. for (var i=0; i<256; i++) {
  19072. _utf8len[i] = (i >= 252 ? 6 : i >= 248 ? 5 : i >= 240 ? 4 : i >= 224 ? 3 : i >= 192 ? 2 : 1);
  19073. }
  19074. _utf8len[254]=_utf8len[254]=1; // Invalid sequence start
  19075. // convert string to array (typed, when possible)
  19076. exports.string2buf = function (str) {
  19077. var buf, c, c2, m_pos, i, str_len = str.length, buf_len = 0;
  19078. // count binary size
  19079. for (m_pos = 0; m_pos < str_len; m_pos++) {
  19080. c = str.charCodeAt(m_pos);
  19081. if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) {
  19082. c2 = str.charCodeAt(m_pos+1);
  19083. if ((c2 & 0xfc00) === 0xdc00) {
  19084. c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
  19085. m_pos++;
  19086. }
  19087. }
  19088. buf_len += c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4;
  19089. }
  19090. // allocate buffer
  19091. buf = new utils.Buf8(buf_len);
  19092. // convert
  19093. for (i=0, m_pos = 0; i < buf_len; m_pos++) {
  19094. c = str.charCodeAt(m_pos);
  19095. if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) {
  19096. c2 = str.charCodeAt(m_pos+1);
  19097. if ((c2 & 0xfc00) === 0xdc00) {
  19098. c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
  19099. m_pos++;
  19100. }
  19101. }
  19102. if (c < 0x80) {
  19103. /* one byte */
  19104. buf[i++] = c;
  19105. } else if (c < 0x800) {
  19106. /* two bytes */
  19107. buf[i++] = 0xC0 | (c >>> 6);
  19108. buf[i++] = 0x80 | (c & 0x3f);
  19109. } else if (c < 0x10000) {
  19110. /* three bytes */
  19111. buf[i++] = 0xE0 | (c >>> 12);
  19112. buf[i++] = 0x80 | (c >>> 6 & 0x3f);
  19113. buf[i++] = 0x80 | (c & 0x3f);
  19114. } else {
  19115. /* four bytes */
  19116. buf[i++] = 0xf0 | (c >>> 18);
  19117. buf[i++] = 0x80 | (c >>> 12 & 0x3f);
  19118. buf[i++] = 0x80 | (c >>> 6 & 0x3f);
  19119. buf[i++] = 0x80 | (c & 0x3f);
  19120. }
  19121. }
  19122. return buf;
  19123. };
  19124. // Helper (used in 2 places)
  19125. function buf2binstring(buf, len) {
  19126. // use fallback for big arrays to avoid stack overflow
  19127. if (len < 65537) {
  19128. if ((buf.subarray && STR_APPLY_UIA_OK) || (!buf.subarray && STR_APPLY_OK)) {
  19129. return String.fromCharCode.apply(null, utils.shrinkBuf(buf, len));
  19130. }
  19131. }
  19132. var result = '';
  19133. for(var i=0; i < len; i++) {
  19134. result += String.fromCharCode(buf[i]);
  19135. }
  19136. return result;
  19137. }
  19138. // Convert byte array to binary string
  19139. exports.buf2binstring = function(buf) {
  19140. return buf2binstring(buf, buf.length);
  19141. };
  19142. // Convert binary string (typed, when possible)
  19143. exports.binstring2buf = function(str) {
  19144. var buf = new utils.Buf8(str.length);
  19145. for(var i=0, len=buf.length; i < len; i++) {
  19146. buf[i] = str.charCodeAt(i);
  19147. }
  19148. return buf;
  19149. };
  19150. // convert array to string
  19151. exports.buf2string = function (buf, max) {
  19152. var i, out, c, c_len;
  19153. var len = max || buf.length;
  19154. // Reserve max possible length (2 words per char)
  19155. // NB: by unknown reasons, Array is significantly faster for
  19156. // String.fromCharCode.apply than Uint16Array.
  19157. var utf16buf = new Array(len*2);
  19158. for (out=0, i=0; i<len;) {
  19159. c = buf[i++];
  19160. // quick process ascii
  19161. if (c < 0x80) { utf16buf[out++] = c; continue; }
  19162. c_len = _utf8len[c];
  19163. // skip 5 & 6 byte codes
  19164. if (c_len > 4) { utf16buf[out++] = 0xfffd; i += c_len-1; continue; }
  19165. // apply mask on first byte
  19166. c &= c_len === 2 ? 0x1f : c_len === 3 ? 0x0f : 0x07;
  19167. // join the rest
  19168. while (c_len > 1 && i < len) {
  19169. c = (c << 6) | (buf[i++] & 0x3f);
  19170. c_len--;
  19171. }
  19172. // terminated by end of string?
  19173. if (c_len > 1) { utf16buf[out++] = 0xfffd; continue; }
  19174. if (c < 0x10000) {
  19175. utf16buf[out++] = c;
  19176. } else {
  19177. c -= 0x10000;
  19178. utf16buf[out++] = 0xd800 | ((c >> 10) & 0x3ff);
  19179. utf16buf[out++] = 0xdc00 | (c & 0x3ff);
  19180. }
  19181. }
  19182. return buf2binstring(utf16buf, out);
  19183. };
  19184. // Calculate max possible position in utf8 buffer,
  19185. // that will not break sequence. If that's not possible
  19186. // - (very small limits) return max size as is.
  19187. //
  19188. // buf[] - utf8 bytes array
  19189. // max - length limit (mandatory);
  19190. exports.utf8border = function(buf, max) {
  19191. var pos;
  19192. max = max || buf.length;
  19193. if (max > buf.length) { max = buf.length; }
  19194. // go back from last position, until start of sequence found
  19195. pos = max-1;
  19196. while (pos >= 0 && (buf[pos] & 0xC0) === 0x80) { pos--; }
  19197. // Fuckup - very small and broken sequence,
  19198. // return max, because we should return something anyway.
  19199. if (pos < 0) { return max; }
  19200. // If we came to start of buffer - that means vuffer is too small,
  19201. // return max too.
  19202. if (pos === 0) { return max; }
  19203. return (pos + _utf8len[buf[pos]] > max) ? pos : max;
  19204. };
  19205. },{"./common":69}],71:[function(require,module,exports){
  19206. 'use strict';
  19207. // Note: adler32 takes 12% for level 0 and 2% for level 6.
  19208. // It doesn't worth to make additional optimizationa as in original.
  19209. // Small size is preferable.
  19210. function adler32(adler, buf, len, pos) {
  19211. var s1 = (adler & 0xffff) |0
  19212. , s2 = ((adler >>> 16) & 0xffff) |0
  19213. , n = 0;
  19214. while (len !== 0) {
  19215. // Set limit ~ twice less than 5552, to keep
  19216. // s2 in 31-bits, because we force signed ints.
  19217. // in other case %= will fail.
  19218. n = len > 2000 ? 2000 : len;
  19219. len -= n;
  19220. do {
  19221. s1 = (s1 + buf[pos++]) |0;
  19222. s2 = (s2 + s1) |0;
  19223. } while (--n);
  19224. s1 %= 65521;
  19225. s2 %= 65521;
  19226. }
  19227. return (s1 | (s2 << 16)) |0;
  19228. }
  19229. module.exports = adler32;
  19230. },{}],72:[function(require,module,exports){
  19231. module.exports = {
  19232. /* Allowed flush values; see deflate() and inflate() below for details */
  19233. Z_NO_FLUSH: 0,
  19234. Z_PARTIAL_FLUSH: 1,
  19235. Z_SYNC_FLUSH: 2,
  19236. Z_FULL_FLUSH: 3,
  19237. Z_FINISH: 4,
  19238. Z_BLOCK: 5,
  19239. Z_TREES: 6,
  19240. /* Return codes for the compression/decompression functions. Negative values
  19241. * are errors, positive values are used for special but normal events.
  19242. */
  19243. Z_OK: 0,
  19244. Z_STREAM_END: 1,
  19245. Z_NEED_DICT: 2,
  19246. Z_ERRNO: -1,
  19247. Z_STREAM_ERROR: -2,
  19248. Z_DATA_ERROR: -3,
  19249. //Z_MEM_ERROR: -4,
  19250. Z_BUF_ERROR: -5,
  19251. //Z_VERSION_ERROR: -6,
  19252. /* compression levels */
  19253. Z_NO_COMPRESSION: 0,
  19254. Z_BEST_SPEED: 1,
  19255. Z_BEST_COMPRESSION: 9,
  19256. Z_DEFAULT_COMPRESSION: -1,
  19257. Z_FILTERED: 1,
  19258. Z_HUFFMAN_ONLY: 2,
  19259. Z_RLE: 3,
  19260. Z_FIXED: 4,
  19261. Z_DEFAULT_STRATEGY: 0,
  19262. /* Possible values of the data_type field (though see inflate()) */
  19263. Z_BINARY: 0,
  19264. Z_TEXT: 1,
  19265. //Z_ASCII: 1, // = Z_TEXT (deprecated)
  19266. Z_UNKNOWN: 2,
  19267. /* The deflate compression method */
  19268. Z_DEFLATED: 8
  19269. //Z_NULL: null // Use -1 or null inline, depending on var type
  19270. };
  19271. },{}],73:[function(require,module,exports){
  19272. 'use strict';
  19273. // Note: we can't get significant speed boost here.
  19274. // So write code to minimize size - no pregenerated tables
  19275. // and array tools dependencies.
  19276. // Use ordinary array, since untyped makes no boost here
  19277. function makeTable() {
  19278. var c, table = [];
  19279. for(var n =0; n < 256; n++){
  19280. c = n;
  19281. for(var k =0; k < 8; k++){
  19282. c = ((c&1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1));
  19283. }
  19284. table[n] = c;
  19285. }
  19286. return table;
  19287. }
  19288. // Create table on load. Just 255 signed longs. Not a problem.
  19289. var crcTable = makeTable();
  19290. function crc32(crc, buf, len, pos) {
  19291. var t = crcTable
  19292. , end = pos + len;
  19293. crc = crc ^ (-1);
  19294. for (var i = pos; i < end; i++ ) {
  19295. crc = (crc >>> 8) ^ t[(crc ^ buf[i]) & 0xFF];
  19296. }
  19297. return (crc ^ (-1)); // >>> 0;
  19298. }
  19299. module.exports = crc32;
  19300. },{}],74:[function(require,module,exports){
  19301. 'use strict';
  19302. var utils = require('../utils/common');
  19303. var trees = require('./trees');
  19304. var adler32 = require('./adler32');
  19305. var crc32 = require('./crc32');
  19306. var msg = require('./messages');
  19307. /* Public constants ==========================================================*/
  19308. /* ===========================================================================*/
  19309. /* Allowed flush values; see deflate() and inflate() below for details */
  19310. var Z_NO_FLUSH = 0;
  19311. var Z_PARTIAL_FLUSH = 1;
  19312. //var Z_SYNC_FLUSH = 2;
  19313. var Z_FULL_FLUSH = 3;
  19314. var Z_FINISH = 4;
  19315. var Z_BLOCK = 5;
  19316. //var Z_TREES = 6;
  19317. /* Return codes for the compression/decompression functions. Negative values
  19318. * are errors, positive values are used for special but normal events.
  19319. */
  19320. var Z_OK = 0;
  19321. var Z_STREAM_END = 1;
  19322. //var Z_NEED_DICT = 2;
  19323. //var Z_ERRNO = -1;
  19324. var Z_STREAM_ERROR = -2;
  19325. var Z_DATA_ERROR = -3;
  19326. //var Z_MEM_ERROR = -4;
  19327. var Z_BUF_ERROR = -5;
  19328. //var Z_VERSION_ERROR = -6;
  19329. /* compression levels */
  19330. //var Z_NO_COMPRESSION = 0;
  19331. //var Z_BEST_SPEED = 1;
  19332. //var Z_BEST_COMPRESSION = 9;
  19333. var Z_DEFAULT_COMPRESSION = -1;
  19334. var Z_FILTERED = 1;
  19335. var Z_HUFFMAN_ONLY = 2;
  19336. var Z_RLE = 3;
  19337. var Z_FIXED = 4;
  19338. var Z_DEFAULT_STRATEGY = 0;
  19339. /* Possible values of the data_type field (though see inflate()) */
  19340. //var Z_BINARY = 0;
  19341. //var Z_TEXT = 1;
  19342. //var Z_ASCII = 1; // = Z_TEXT
  19343. var Z_UNKNOWN = 2;
  19344. /* The deflate compression method */
  19345. var Z_DEFLATED = 8;
  19346. /*============================================================================*/
  19347. var MAX_MEM_LEVEL = 9;
  19348. /* Maximum value for memLevel in deflateInit2 */
  19349. var MAX_WBITS = 15;
  19350. /* 32K LZ77 window */
  19351. var DEF_MEM_LEVEL = 8;
  19352. var LENGTH_CODES = 29;
  19353. /* number of length codes, not counting the special END_BLOCK code */
  19354. var LITERALS = 256;
  19355. /* number of literal bytes 0..255 */
  19356. var L_CODES = LITERALS + 1 + LENGTH_CODES;
  19357. /* number of Literal or Length codes, including the END_BLOCK code */
  19358. var D_CODES = 30;
  19359. /* number of distance codes */
  19360. var BL_CODES = 19;
  19361. /* number of codes used to transfer the bit lengths */
  19362. var HEAP_SIZE = 2*L_CODES + 1;
  19363. /* maximum heap size */
  19364. var MAX_BITS = 15;
  19365. /* All codes must not exceed MAX_BITS bits */
  19366. var MIN_MATCH = 3;
  19367. var MAX_MATCH = 258;
  19368. var MIN_LOOKAHEAD = (MAX_MATCH + MIN_MATCH + 1);
  19369. var PRESET_DICT = 0x20;
  19370. var INIT_STATE = 42;
  19371. var EXTRA_STATE = 69;
  19372. var NAME_STATE = 73;
  19373. var COMMENT_STATE = 91;
  19374. var HCRC_STATE = 103;
  19375. var BUSY_STATE = 113;
  19376. var FINISH_STATE = 666;
  19377. var BS_NEED_MORE = 1; /* block not completed, need more input or more output */
  19378. var BS_BLOCK_DONE = 2; /* block flush performed */
  19379. var BS_FINISH_STARTED = 3; /* finish started, need only more output at next deflate */
  19380. var BS_FINISH_DONE = 4; /* finish done, accept no more input or output */
  19381. var OS_CODE = 0x03; // Unix :) . Don't detect, use this default.
  19382. function err(strm, errorCode) {
  19383. strm.msg = msg[errorCode];
  19384. return errorCode;
  19385. }
  19386. function rank(f) {
  19387. return ((f) << 1) - ((f) > 4 ? 9 : 0);
  19388. }
  19389. function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
  19390. /* =========================================================================
  19391. * Flush as much pending output as possible. All deflate() output goes
  19392. * through this function so some applications may wish to modify it
  19393. * to avoid allocating a large strm->output buffer and copying into it.
  19394. * (See also read_buf()).
  19395. */
  19396. function flush_pending(strm) {
  19397. var s = strm.state;
  19398. //_tr_flush_bits(s);
  19399. var len = s.pending;
  19400. if (len > strm.avail_out) {
  19401. len = strm.avail_out;
  19402. }
  19403. if (len === 0) { return; }
  19404. utils.arraySet(strm.output, s.pending_buf, s.pending_out, len, strm.next_out);
  19405. strm.next_out += len;
  19406. s.pending_out += len;
  19407. strm.total_out += len;
  19408. strm.avail_out -= len;
  19409. s.pending -= len;
  19410. if (s.pending === 0) {
  19411. s.pending_out = 0;
  19412. }
  19413. }
  19414. function flush_block_only (s, last) {
  19415. trees._tr_flush_block(s, (s.block_start >= 0 ? s.block_start : -1), s.strstart - s.block_start, last);
  19416. s.block_start = s.strstart;
  19417. flush_pending(s.strm);
  19418. }
  19419. function put_byte(s, b) {
  19420. s.pending_buf[s.pending++] = b;
  19421. }
  19422. /* =========================================================================
  19423. * Put a short in the pending buffer. The 16-bit value is put in MSB order.
  19424. * IN assertion: the stream state is correct and there is enough room in
  19425. * pending_buf.
  19426. */
  19427. function putShortMSB(s, b) {
  19428. // put_byte(s, (Byte)(b >> 8));
  19429. // put_byte(s, (Byte)(b & 0xff));
  19430. s.pending_buf[s.pending++] = (b >>> 8) & 0xff;
  19431. s.pending_buf[s.pending++] = b & 0xff;
  19432. }
  19433. /* ===========================================================================
  19434. * Read a new buffer from the current input stream, update the adler32
  19435. * and total number of bytes read. All deflate() input goes through
  19436. * this function so some applications may wish to modify it to avoid
  19437. * allocating a large strm->input buffer and copying from it.
  19438. * (See also flush_pending()).
  19439. */
  19440. function read_buf(strm, buf, start, size) {
  19441. var len = strm.avail_in;
  19442. if (len > size) { len = size; }
  19443. if (len === 0) { return 0; }
  19444. strm.avail_in -= len;
  19445. utils.arraySet(buf, strm.input, strm.next_in, len, start);
  19446. if (strm.state.wrap === 1) {
  19447. strm.adler = adler32(strm.adler, buf, len, start);
  19448. }
  19449. else if (strm.state.wrap === 2) {
  19450. strm.adler = crc32(strm.adler, buf, len, start);
  19451. }
  19452. strm.next_in += len;
  19453. strm.total_in += len;
  19454. return len;
  19455. }
  19456. /* ===========================================================================
  19457. * Set match_start to the longest match starting at the given string and
  19458. * return its length. Matches shorter or equal to prev_length are discarded,
  19459. * in which case the result is equal to prev_length and match_start is
  19460. * garbage.
  19461. * IN assertions: cur_match is the head of the hash chain for the current
  19462. * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
  19463. * OUT assertion: the match length is not greater than s->lookahead.
  19464. */
  19465. function longest_match(s, cur_match) {
  19466. var chain_length = s.max_chain_length; /* max hash chain length */
  19467. var scan = s.strstart; /* current string */
  19468. var match; /* matched string */
  19469. var len; /* length of current match */
  19470. var best_len = s.prev_length; /* best match length so far */
  19471. var nice_match = s.nice_match; /* stop if match long enough */
  19472. var limit = (s.strstart > (s.w_size - MIN_LOOKAHEAD)) ?
  19473. s.strstart - (s.w_size - MIN_LOOKAHEAD) : 0/*NIL*/;
  19474. var _win = s.window; // shortcut
  19475. var wmask = s.w_mask;
  19476. var prev = s.prev;
  19477. /* Stop when cur_match becomes <= limit. To simplify the code,
  19478. * we prevent matches with the string of window index 0.
  19479. */
  19480. var strend = s.strstart + MAX_MATCH;
  19481. var scan_end1 = _win[scan + best_len - 1];
  19482. var scan_end = _win[scan + best_len];
  19483. /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
  19484. * It is easy to get rid of this optimization if necessary.
  19485. */
  19486. // Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
  19487. /* Do not waste too much time if we already have a good match: */
  19488. if (s.prev_length >= s.good_match) {
  19489. chain_length >>= 2;
  19490. }
  19491. /* Do not look for matches beyond the end of the input. This is necessary
  19492. * to make deflate deterministic.
  19493. */
  19494. if (nice_match > s.lookahead) { nice_match = s.lookahead; }
  19495. // Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
  19496. do {
  19497. // Assert(cur_match < s->strstart, "no future");
  19498. match = cur_match;
  19499. /* Skip to next match if the match length cannot increase
  19500. * or if the match length is less than 2. Note that the checks below
  19501. * for insufficient lookahead only occur occasionally for performance
  19502. * reasons. Therefore uninitialized memory will be accessed, and
  19503. * conditional jumps will be made that depend on those values.
  19504. * However the length of the match is limited to the lookahead, so
  19505. * the output of deflate is not affected by the uninitialized values.
  19506. */
  19507. if (_win[match + best_len] !== scan_end ||
  19508. _win[match + best_len - 1] !== scan_end1 ||
  19509. _win[match] !== _win[scan] ||
  19510. _win[++match] !== _win[scan + 1]) {
  19511. continue;
  19512. }
  19513. /* The check at best_len-1 can be removed because it will be made
  19514. * again later. (This heuristic is not always a win.)
  19515. * It is not necessary to compare scan[2] and match[2] since they
  19516. * are always equal when the other bytes match, given that
  19517. * the hash keys are equal and that HASH_BITS >= 8.
  19518. */
  19519. scan += 2;
  19520. match++;
  19521. // Assert(*scan == *match, "match[2]?");
  19522. /* We check for insufficient lookahead only every 8th comparison;
  19523. * the 256th check will be made at strstart+258.
  19524. */
  19525. do {
  19526. /*jshint noempty:false*/
  19527. } while (_win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  19528. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  19529. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  19530. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  19531. scan < strend);
  19532. // Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  19533. len = MAX_MATCH - (strend - scan);
  19534. scan = strend - MAX_MATCH;
  19535. if (len > best_len) {
  19536. s.match_start = cur_match;
  19537. best_len = len;
  19538. if (len >= nice_match) {
  19539. break;
  19540. }
  19541. scan_end1 = _win[scan + best_len - 1];
  19542. scan_end = _win[scan + best_len];
  19543. }
  19544. } while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length !== 0);
  19545. if (best_len <= s.lookahead) {
  19546. return best_len;
  19547. }
  19548. return s.lookahead;
  19549. }
  19550. /* ===========================================================================
  19551. * Fill the window when the lookahead becomes insufficient.
  19552. * Updates strstart and lookahead.
  19553. *
  19554. * IN assertion: lookahead < MIN_LOOKAHEAD
  19555. * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
  19556. * At least one byte has been read, or avail_in == 0; reads are
  19557. * performed for at least two bytes (required for the zip translate_eol
  19558. * option -- not supported here).
  19559. */
  19560. function fill_window(s) {
  19561. var _w_size = s.w_size;
  19562. var p, n, m, more, str;
  19563. //Assert(s->lookahead < MIN_LOOKAHEAD, "already enough lookahead");
  19564. do {
  19565. more = s.window_size - s.lookahead - s.strstart;
  19566. // JS ints have 32 bit, block below not needed
  19567. /* Deal with !@#$% 64K limit: */
  19568. //if (sizeof(int) <= 2) {
  19569. // if (more == 0 && s->strstart == 0 && s->lookahead == 0) {
  19570. // more = wsize;
  19571. //
  19572. // } else if (more == (unsigned)(-1)) {
  19573. // /* Very unlikely, but possible on 16 bit machine if
  19574. // * strstart == 0 && lookahead == 1 (input done a byte at time)
  19575. // */
  19576. // more--;
  19577. // }
  19578. //}
  19579. /* If the window is almost full and there is insufficient lookahead,
  19580. * move the upper half to the lower one to make room in the upper half.
  19581. */
  19582. if (s.strstart >= _w_size + (_w_size - MIN_LOOKAHEAD)) {
  19583. utils.arraySet(s.window, s.window, _w_size, _w_size, 0);
  19584. s.match_start -= _w_size;
  19585. s.strstart -= _w_size;
  19586. /* we now have strstart >= MAX_DIST */
  19587. s.block_start -= _w_size;
  19588. /* Slide the hash table (could be avoided with 32 bit values
  19589. at the expense of memory usage). We slide even when level == 0
  19590. to keep the hash table consistent if we switch back to level > 0
  19591. later. (Using level 0 permanently is not an optimal usage of
  19592. zlib, so we don't care about this pathological case.)
  19593. */
  19594. n = s.hash_size;
  19595. p = n;
  19596. do {
  19597. m = s.head[--p];
  19598. s.head[p] = (m >= _w_size ? m - _w_size : 0);
  19599. } while (--n);
  19600. n = _w_size;
  19601. p = n;
  19602. do {
  19603. m = s.prev[--p];
  19604. s.prev[p] = (m >= _w_size ? m - _w_size : 0);
  19605. /* If n is not on any hash chain, prev[n] is garbage but
  19606. * its value will never be used.
  19607. */
  19608. } while (--n);
  19609. more += _w_size;
  19610. }
  19611. if (s.strm.avail_in === 0) {
  19612. break;
  19613. }
  19614. /* If there was no sliding:
  19615. * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
  19616. * more == window_size - lookahead - strstart
  19617. * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
  19618. * => more >= window_size - 2*WSIZE + 2
  19619. * In the BIG_MEM or MMAP case (not yet supported),
  19620. * window_size == input_size + MIN_LOOKAHEAD &&
  19621. * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
  19622. * Otherwise, window_size == 2*WSIZE so more >= 2.
  19623. * If there was sliding, more >= WSIZE. So in all cases, more >= 2.
  19624. */
  19625. //Assert(more >= 2, "more < 2");
  19626. n = read_buf(s.strm, s.window, s.strstart + s.lookahead, more);
  19627. s.lookahead += n;
  19628. /* Initialize the hash value now that we have some input: */
  19629. if (s.lookahead + s.insert >= MIN_MATCH) {
  19630. str = s.strstart - s.insert;
  19631. s.ins_h = s.window[str];
  19632. /* UPDATE_HASH(s, s->ins_h, s->window[str + 1]); */
  19633. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + 1]) & s.hash_mask;
  19634. //#if MIN_MATCH != 3
  19635. // Call update_hash() MIN_MATCH-3 more times
  19636. //#endif
  19637. while (s.insert) {
  19638. /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */
  19639. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH-1]) & s.hash_mask;
  19640. s.prev[str & s.w_mask] = s.head[s.ins_h];
  19641. s.head[s.ins_h] = str;
  19642. str++;
  19643. s.insert--;
  19644. if (s.lookahead + s.insert < MIN_MATCH) {
  19645. break;
  19646. }
  19647. }
  19648. }
  19649. /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,
  19650. * but this is not important since only literal bytes will be emitted.
  19651. */
  19652. } while (s.lookahead < MIN_LOOKAHEAD && s.strm.avail_in !== 0);
  19653. /* If the WIN_INIT bytes after the end of the current data have never been
  19654. * written, then zero those bytes in order to avoid memory check reports of
  19655. * the use of uninitialized (or uninitialised as Julian writes) bytes by
  19656. * the longest match routines. Update the high water mark for the next
  19657. * time through here. WIN_INIT is set to MAX_MATCH since the longest match
  19658. * routines allow scanning to strstart + MAX_MATCH, ignoring lookahead.
  19659. */
  19660. // if (s.high_water < s.window_size) {
  19661. // var curr = s.strstart + s.lookahead;
  19662. // var init = 0;
  19663. //
  19664. // if (s.high_water < curr) {
  19665. // /* Previous high water mark below current data -- zero WIN_INIT
  19666. // * bytes or up to end of window, whichever is less.
  19667. // */
  19668. // init = s.window_size - curr;
  19669. // if (init > WIN_INIT)
  19670. // init = WIN_INIT;
  19671. // zmemzero(s->window + curr, (unsigned)init);
  19672. // s->high_water = curr + init;
  19673. // }
  19674. // else if (s->high_water < (ulg)curr + WIN_INIT) {
  19675. // /* High water mark at or above current data, but below current data
  19676. // * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up
  19677. // * to end of window, whichever is less.
  19678. // */
  19679. // init = (ulg)curr + WIN_INIT - s->high_water;
  19680. // if (init > s->window_size - s->high_water)
  19681. // init = s->window_size - s->high_water;
  19682. // zmemzero(s->window + s->high_water, (unsigned)init);
  19683. // s->high_water += init;
  19684. // }
  19685. // }
  19686. //
  19687. // Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD,
  19688. // "not enough room for search");
  19689. }
  19690. /* ===========================================================================
  19691. * Copy without compression as much as possible from the input stream, return
  19692. * the current block state.
  19693. * This function does not insert new strings in the dictionary since
  19694. * uncompressible data is probably not useful. This function is used
  19695. * only for the level=0 compression option.
  19696. * NOTE: this function should be optimized to avoid extra copying from
  19697. * window to pending_buf.
  19698. */
  19699. function deflate_stored(s, flush) {
  19700. /* Stored blocks are limited to 0xffff bytes, pending_buf is limited
  19701. * to pending_buf_size, and each stored block has a 5 byte header:
  19702. */
  19703. var max_block_size = 0xffff;
  19704. if (max_block_size > s.pending_buf_size - 5) {
  19705. max_block_size = s.pending_buf_size - 5;
  19706. }
  19707. /* Copy as much as possible from input to output: */
  19708. for (;;) {
  19709. /* Fill the window as much as possible: */
  19710. if (s.lookahead <= 1) {
  19711. //Assert(s->strstart < s->w_size+MAX_DIST(s) ||
  19712. // s->block_start >= (long)s->w_size, "slide too late");
  19713. // if (!(s.strstart < s.w_size + (s.w_size - MIN_LOOKAHEAD) ||
  19714. // s.block_start >= s.w_size)) {
  19715. // throw new Error("slide too late");
  19716. // }
  19717. fill_window(s);
  19718. if (s.lookahead === 0 && flush === Z_NO_FLUSH) {
  19719. return BS_NEED_MORE;
  19720. }
  19721. if (s.lookahead === 0) {
  19722. break;
  19723. }
  19724. /* flush the current block */
  19725. }
  19726. //Assert(s->block_start >= 0L, "block gone");
  19727. // if (s.block_start < 0) throw new Error("block gone");
  19728. s.strstart += s.lookahead;
  19729. s.lookahead = 0;
  19730. /* Emit a stored block if pending_buf will be full: */
  19731. var max_start = s.block_start + max_block_size;
  19732. if (s.strstart === 0 || s.strstart >= max_start) {
  19733. /* strstart == 0 is possible when wraparound on 16-bit machine */
  19734. s.lookahead = s.strstart - max_start;
  19735. s.strstart = max_start;
  19736. /*** FLUSH_BLOCK(s, 0); ***/
  19737. flush_block_only(s, false);
  19738. if (s.strm.avail_out === 0) {
  19739. return BS_NEED_MORE;
  19740. }
  19741. /***/
  19742. }
  19743. /* Flush if we may have to slide, otherwise block_start may become
  19744. * negative and the data will be gone:
  19745. */
  19746. if (s.strstart - s.block_start >= (s.w_size - MIN_LOOKAHEAD)) {
  19747. /*** FLUSH_BLOCK(s, 0); ***/
  19748. flush_block_only(s, false);
  19749. if (s.strm.avail_out === 0) {
  19750. return BS_NEED_MORE;
  19751. }
  19752. /***/
  19753. }
  19754. }
  19755. s.insert = 0;
  19756. if (flush === Z_FINISH) {
  19757. /*** FLUSH_BLOCK(s, 1); ***/
  19758. flush_block_only(s, true);
  19759. if (s.strm.avail_out === 0) {
  19760. return BS_FINISH_STARTED;
  19761. }
  19762. /***/
  19763. return BS_FINISH_DONE;
  19764. }
  19765. if (s.strstart > s.block_start) {
  19766. /*** FLUSH_BLOCK(s, 0); ***/
  19767. flush_block_only(s, false);
  19768. if (s.strm.avail_out === 0) {
  19769. return BS_NEED_MORE;
  19770. }
  19771. /***/
  19772. }
  19773. return BS_NEED_MORE;
  19774. }
  19775. /* ===========================================================================
  19776. * Compress as much as possible from the input stream, return the current
  19777. * block state.
  19778. * This function does not perform lazy evaluation of matches and inserts
  19779. * new strings in the dictionary only for unmatched strings or for short
  19780. * matches. It is used only for the fast compression options.
  19781. */
  19782. function deflate_fast(s, flush) {
  19783. var hash_head; /* head of the hash chain */
  19784. var bflush; /* set if current block must be flushed */
  19785. for (;;) {
  19786. /* Make sure that we always have enough lookahead, except
  19787. * at the end of the input file. We need MAX_MATCH bytes
  19788. * for the next match, plus MIN_MATCH bytes to insert the
  19789. * string following the next match.
  19790. */
  19791. if (s.lookahead < MIN_LOOKAHEAD) {
  19792. fill_window(s);
  19793. if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
  19794. return BS_NEED_MORE;
  19795. }
  19796. if (s.lookahead === 0) {
  19797. break; /* flush the current block */
  19798. }
  19799. }
  19800. /* Insert the string window[strstart .. strstart+2] in the
  19801. * dictionary, and set hash_head to the head of the hash chain:
  19802. */
  19803. hash_head = 0/*NIL*/;
  19804. if (s.lookahead >= MIN_MATCH) {
  19805. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  19806. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  19807. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  19808. s.head[s.ins_h] = s.strstart;
  19809. /***/
  19810. }
  19811. /* Find the longest match, discarding those <= prev_length.
  19812. * At this point we have always match_length < MIN_MATCH
  19813. */
  19814. if (hash_head !== 0/*NIL*/ && ((s.strstart - hash_head) <= (s.w_size - MIN_LOOKAHEAD))) {
  19815. /* To simplify the code, we prevent matches with the string
  19816. * of window index 0 (in particular we have to avoid a match
  19817. * of the string with itself at the start of the input file).
  19818. */
  19819. s.match_length = longest_match(s, hash_head);
  19820. /* longest_match() sets match_start */
  19821. }
  19822. if (s.match_length >= MIN_MATCH) {
  19823. // check_match(s, s.strstart, s.match_start, s.match_length); // for debug only
  19824. /*** _tr_tally_dist(s, s.strstart - s.match_start,
  19825. s.match_length - MIN_MATCH, bflush); ***/
  19826. bflush = trees._tr_tally(s, s.strstart - s.match_start, s.match_length - MIN_MATCH);
  19827. s.lookahead -= s.match_length;
  19828. /* Insert new strings in the hash table only if the match length
  19829. * is not too large. This saves time but degrades compression.
  19830. */
  19831. if (s.match_length <= s.max_lazy_match/*max_insert_length*/ && s.lookahead >= MIN_MATCH) {
  19832. s.match_length--; /* string at strstart already in table */
  19833. do {
  19834. s.strstart++;
  19835. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  19836. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  19837. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  19838. s.head[s.ins_h] = s.strstart;
  19839. /***/
  19840. /* strstart never exceeds WSIZE-MAX_MATCH, so there are
  19841. * always MIN_MATCH bytes ahead.
  19842. */
  19843. } while (--s.match_length !== 0);
  19844. s.strstart++;
  19845. } else
  19846. {
  19847. s.strstart += s.match_length;
  19848. s.match_length = 0;
  19849. s.ins_h = s.window[s.strstart];
  19850. /* UPDATE_HASH(s, s.ins_h, s.window[s.strstart+1]); */
  19851. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + 1]) & s.hash_mask;
  19852. //#if MIN_MATCH != 3
  19853. // Call UPDATE_HASH() MIN_MATCH-3 more times
  19854. //#endif
  19855. /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not
  19856. * matter since it will be recomputed at next deflate call.
  19857. */
  19858. }
  19859. } else {
  19860. /* No match, output a literal byte */
  19861. //Tracevv((stderr,"%c", s.window[s.strstart]));
  19862. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  19863. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  19864. s.lookahead--;
  19865. s.strstart++;
  19866. }
  19867. if (bflush) {
  19868. /*** FLUSH_BLOCK(s, 0); ***/
  19869. flush_block_only(s, false);
  19870. if (s.strm.avail_out === 0) {
  19871. return BS_NEED_MORE;
  19872. }
  19873. /***/
  19874. }
  19875. }
  19876. s.insert = ((s.strstart < (MIN_MATCH-1)) ? s.strstart : MIN_MATCH-1);
  19877. if (flush === Z_FINISH) {
  19878. /*** FLUSH_BLOCK(s, 1); ***/
  19879. flush_block_only(s, true);
  19880. if (s.strm.avail_out === 0) {
  19881. return BS_FINISH_STARTED;
  19882. }
  19883. /***/
  19884. return BS_FINISH_DONE;
  19885. }
  19886. if (s.last_lit) {
  19887. /*** FLUSH_BLOCK(s, 0); ***/
  19888. flush_block_only(s, false);
  19889. if (s.strm.avail_out === 0) {
  19890. return BS_NEED_MORE;
  19891. }
  19892. /***/
  19893. }
  19894. return BS_BLOCK_DONE;
  19895. }
  19896. /* ===========================================================================
  19897. * Same as above, but achieves better compression. We use a lazy
  19898. * evaluation for matches: a match is finally adopted only if there is
  19899. * no better match at the next window position.
  19900. */
  19901. function deflate_slow(s, flush) {
  19902. var hash_head; /* head of hash chain */
  19903. var bflush; /* set if current block must be flushed */
  19904. var max_insert;
  19905. /* Process the input block. */
  19906. for (;;) {
  19907. /* Make sure that we always have enough lookahead, except
  19908. * at the end of the input file. We need MAX_MATCH bytes
  19909. * for the next match, plus MIN_MATCH bytes to insert the
  19910. * string following the next match.
  19911. */
  19912. if (s.lookahead < MIN_LOOKAHEAD) {
  19913. fill_window(s);
  19914. if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
  19915. return BS_NEED_MORE;
  19916. }
  19917. if (s.lookahead === 0) { break; } /* flush the current block */
  19918. }
  19919. /* Insert the string window[strstart .. strstart+2] in the
  19920. * dictionary, and set hash_head to the head of the hash chain:
  19921. */
  19922. hash_head = 0/*NIL*/;
  19923. if (s.lookahead >= MIN_MATCH) {
  19924. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  19925. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  19926. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  19927. s.head[s.ins_h] = s.strstart;
  19928. /***/
  19929. }
  19930. /* Find the longest match, discarding those <= prev_length.
  19931. */
  19932. s.prev_length = s.match_length;
  19933. s.prev_match = s.match_start;
  19934. s.match_length = MIN_MATCH-1;
  19935. if (hash_head !== 0/*NIL*/ && s.prev_length < s.max_lazy_match &&
  19936. s.strstart - hash_head <= (s.w_size-MIN_LOOKAHEAD)/*MAX_DIST(s)*/) {
  19937. /* To simplify the code, we prevent matches with the string
  19938. * of window index 0 (in particular we have to avoid a match
  19939. * of the string with itself at the start of the input file).
  19940. */
  19941. s.match_length = longest_match(s, hash_head);
  19942. /* longest_match() sets match_start */
  19943. if (s.match_length <= 5 &&
  19944. (s.strategy === Z_FILTERED || (s.match_length === MIN_MATCH && s.strstart - s.match_start > 4096/*TOO_FAR*/))) {
  19945. /* If prev_match is also MIN_MATCH, match_start is garbage
  19946. * but we will ignore the current match anyway.
  19947. */
  19948. s.match_length = MIN_MATCH-1;
  19949. }
  19950. }
  19951. /* If there was a match at the previous step and the current
  19952. * match is not better, output the previous match:
  19953. */
  19954. if (s.prev_length >= MIN_MATCH && s.match_length <= s.prev_length) {
  19955. max_insert = s.strstart + s.lookahead - MIN_MATCH;
  19956. /* Do not insert strings in hash table beyond this. */
  19957. //check_match(s, s.strstart-1, s.prev_match, s.prev_length);
  19958. /***_tr_tally_dist(s, s.strstart - 1 - s.prev_match,
  19959. s.prev_length - MIN_MATCH, bflush);***/
  19960. bflush = trees._tr_tally(s, s.strstart - 1- s.prev_match, s.prev_length - MIN_MATCH);
  19961. /* Insert in hash table all strings up to the end of the match.
  19962. * strstart-1 and strstart are already inserted. If there is not
  19963. * enough lookahead, the last two strings are not inserted in
  19964. * the hash table.
  19965. */
  19966. s.lookahead -= s.prev_length-1;
  19967. s.prev_length -= 2;
  19968. do {
  19969. if (++s.strstart <= max_insert) {
  19970. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  19971. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  19972. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  19973. s.head[s.ins_h] = s.strstart;
  19974. /***/
  19975. }
  19976. } while (--s.prev_length !== 0);
  19977. s.match_available = 0;
  19978. s.match_length = MIN_MATCH-1;
  19979. s.strstart++;
  19980. if (bflush) {
  19981. /*** FLUSH_BLOCK(s, 0); ***/
  19982. flush_block_only(s, false);
  19983. if (s.strm.avail_out === 0) {
  19984. return BS_NEED_MORE;
  19985. }
  19986. /***/
  19987. }
  19988. } else if (s.match_available) {
  19989. /* If there was no match at the previous position, output a
  19990. * single literal. If there was a match but the current match
  19991. * is longer, truncate the previous match to a single literal.
  19992. */
  19993. //Tracevv((stderr,"%c", s->window[s->strstart-1]));
  19994. /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
  19995. bflush = trees._tr_tally(s, 0, s.window[s.strstart-1]);
  19996. if (bflush) {
  19997. /*** FLUSH_BLOCK_ONLY(s, 0) ***/
  19998. flush_block_only(s, false);
  19999. /***/
  20000. }
  20001. s.strstart++;
  20002. s.lookahead--;
  20003. if (s.strm.avail_out === 0) {
  20004. return BS_NEED_MORE;
  20005. }
  20006. } else {
  20007. /* There is no previous match to compare with, wait for
  20008. * the next step to decide.
  20009. */
  20010. s.match_available = 1;
  20011. s.strstart++;
  20012. s.lookahead--;
  20013. }
  20014. }
  20015. //Assert (flush != Z_NO_FLUSH, "no flush?");
  20016. if (s.match_available) {
  20017. //Tracevv((stderr,"%c", s->window[s->strstart-1]));
  20018. /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
  20019. bflush = trees._tr_tally(s, 0, s.window[s.strstart-1]);
  20020. s.match_available = 0;
  20021. }
  20022. s.insert = s.strstart < MIN_MATCH-1 ? s.strstart : MIN_MATCH-1;
  20023. if (flush === Z_FINISH) {
  20024. /*** FLUSH_BLOCK(s, 1); ***/
  20025. flush_block_only(s, true);
  20026. if (s.strm.avail_out === 0) {
  20027. return BS_FINISH_STARTED;
  20028. }
  20029. /***/
  20030. return BS_FINISH_DONE;
  20031. }
  20032. if (s.last_lit) {
  20033. /*** FLUSH_BLOCK(s, 0); ***/
  20034. flush_block_only(s, false);
  20035. if (s.strm.avail_out === 0) {
  20036. return BS_NEED_MORE;
  20037. }
  20038. /***/
  20039. }
  20040. return BS_BLOCK_DONE;
  20041. }
  20042. /* ===========================================================================
  20043. * For Z_RLE, simply look for runs of bytes, generate matches only of distance
  20044. * one. Do not maintain a hash table. (It will be regenerated if this run of
  20045. * deflate switches away from Z_RLE.)
  20046. */
  20047. function deflate_rle(s, flush) {
  20048. var bflush; /* set if current block must be flushed */
  20049. var prev; /* byte at distance one to match */
  20050. var scan, strend; /* scan goes up to strend for length of run */
  20051. var _win = s.window;
  20052. for (;;) {
  20053. /* Make sure that we always have enough lookahead, except
  20054. * at the end of the input file. We need MAX_MATCH bytes
  20055. * for the longest run, plus one for the unrolled loop.
  20056. */
  20057. if (s.lookahead <= MAX_MATCH) {
  20058. fill_window(s);
  20059. if (s.lookahead <= MAX_MATCH && flush === Z_NO_FLUSH) {
  20060. return BS_NEED_MORE;
  20061. }
  20062. if (s.lookahead === 0) { break; } /* flush the current block */
  20063. }
  20064. /* See how many times the previous byte repeats */
  20065. s.match_length = 0;
  20066. if (s.lookahead >= MIN_MATCH && s.strstart > 0) {
  20067. scan = s.strstart - 1;
  20068. prev = _win[scan];
  20069. if (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan]) {
  20070. strend = s.strstart + MAX_MATCH;
  20071. do {
  20072. /*jshint noempty:false*/
  20073. } while (prev === _win[++scan] && prev === _win[++scan] &&
  20074. prev === _win[++scan] && prev === _win[++scan] &&
  20075. prev === _win[++scan] && prev === _win[++scan] &&
  20076. prev === _win[++scan] && prev === _win[++scan] &&
  20077. scan < strend);
  20078. s.match_length = MAX_MATCH - (strend - scan);
  20079. if (s.match_length > s.lookahead) {
  20080. s.match_length = s.lookahead;
  20081. }
  20082. }
  20083. //Assert(scan <= s->window+(uInt)(s->window_size-1), "wild scan");
  20084. }
  20085. /* Emit match if have run of MIN_MATCH or longer, else emit literal */
  20086. if (s.match_length >= MIN_MATCH) {
  20087. //check_match(s, s.strstart, s.strstart - 1, s.match_length);
  20088. /*** _tr_tally_dist(s, 1, s.match_length - MIN_MATCH, bflush); ***/
  20089. bflush = trees._tr_tally(s, 1, s.match_length - MIN_MATCH);
  20090. s.lookahead -= s.match_length;
  20091. s.strstart += s.match_length;
  20092. s.match_length = 0;
  20093. } else {
  20094. /* No match, output a literal byte */
  20095. //Tracevv((stderr,"%c", s->window[s->strstart]));
  20096. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  20097. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  20098. s.lookahead--;
  20099. s.strstart++;
  20100. }
  20101. if (bflush) {
  20102. /*** FLUSH_BLOCK(s, 0); ***/
  20103. flush_block_only(s, false);
  20104. if (s.strm.avail_out === 0) {
  20105. return BS_NEED_MORE;
  20106. }
  20107. /***/
  20108. }
  20109. }
  20110. s.insert = 0;
  20111. if (flush === Z_FINISH) {
  20112. /*** FLUSH_BLOCK(s, 1); ***/
  20113. flush_block_only(s, true);
  20114. if (s.strm.avail_out === 0) {
  20115. return BS_FINISH_STARTED;
  20116. }
  20117. /***/
  20118. return BS_FINISH_DONE;
  20119. }
  20120. if (s.last_lit) {
  20121. /*** FLUSH_BLOCK(s, 0); ***/
  20122. flush_block_only(s, false);
  20123. if (s.strm.avail_out === 0) {
  20124. return BS_NEED_MORE;
  20125. }
  20126. /***/
  20127. }
  20128. return BS_BLOCK_DONE;
  20129. }
  20130. /* ===========================================================================
  20131. * For Z_HUFFMAN_ONLY, do not look for matches. Do not maintain a hash table.
  20132. * (It will be regenerated if this run of deflate switches away from Huffman.)
  20133. */
  20134. function deflate_huff(s, flush) {
  20135. var bflush; /* set if current block must be flushed */
  20136. for (;;) {
  20137. /* Make sure that we have a literal to write. */
  20138. if (s.lookahead === 0) {
  20139. fill_window(s);
  20140. if (s.lookahead === 0) {
  20141. if (flush === Z_NO_FLUSH) {
  20142. return BS_NEED_MORE;
  20143. }
  20144. break; /* flush the current block */
  20145. }
  20146. }
  20147. /* Output a literal byte */
  20148. s.match_length = 0;
  20149. //Tracevv((stderr,"%c", s->window[s->strstart]));
  20150. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  20151. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  20152. s.lookahead--;
  20153. s.strstart++;
  20154. if (bflush) {
  20155. /*** FLUSH_BLOCK(s, 0); ***/
  20156. flush_block_only(s, false);
  20157. if (s.strm.avail_out === 0) {
  20158. return BS_NEED_MORE;
  20159. }
  20160. /***/
  20161. }
  20162. }
  20163. s.insert = 0;
  20164. if (flush === Z_FINISH) {
  20165. /*** FLUSH_BLOCK(s, 1); ***/
  20166. flush_block_only(s, true);
  20167. if (s.strm.avail_out === 0) {
  20168. return BS_FINISH_STARTED;
  20169. }
  20170. /***/
  20171. return BS_FINISH_DONE;
  20172. }
  20173. if (s.last_lit) {
  20174. /*** FLUSH_BLOCK(s, 0); ***/
  20175. flush_block_only(s, false);
  20176. if (s.strm.avail_out === 0) {
  20177. return BS_NEED_MORE;
  20178. }
  20179. /***/
  20180. }
  20181. return BS_BLOCK_DONE;
  20182. }
  20183. /* Values for max_lazy_match, good_match and max_chain_length, depending on
  20184. * the desired pack level (0..9). The values given below have been tuned to
  20185. * exclude worst case performance for pathological files. Better values may be
  20186. * found for specific files.
  20187. */
  20188. var Config = function (good_length, max_lazy, nice_length, max_chain, func) {
  20189. this.good_length = good_length;
  20190. this.max_lazy = max_lazy;
  20191. this.nice_length = nice_length;
  20192. this.max_chain = max_chain;
  20193. this.func = func;
  20194. };
  20195. var configuration_table;
  20196. configuration_table = [
  20197. /* good lazy nice chain */
  20198. new Config(0, 0, 0, 0, deflate_stored), /* 0 store only */
  20199. new Config(4, 4, 8, 4, deflate_fast), /* 1 max speed, no lazy matches */
  20200. new Config(4, 5, 16, 8, deflate_fast), /* 2 */
  20201. new Config(4, 6, 32, 32, deflate_fast), /* 3 */
  20202. new Config(4, 4, 16, 16, deflate_slow), /* 4 lazy matches */
  20203. new Config(8, 16, 32, 32, deflate_slow), /* 5 */
  20204. new Config(8, 16, 128, 128, deflate_slow), /* 6 */
  20205. new Config(8, 32, 128, 256, deflate_slow), /* 7 */
  20206. new Config(32, 128, 258, 1024, deflate_slow), /* 8 */
  20207. new Config(32, 258, 258, 4096, deflate_slow) /* 9 max compression */
  20208. ];
  20209. /* ===========================================================================
  20210. * Initialize the "longest match" routines for a new zlib stream
  20211. */
  20212. function lm_init(s) {
  20213. s.window_size = 2 * s.w_size;
  20214. /*** CLEAR_HASH(s); ***/
  20215. zero(s.head); // Fill with NIL (= 0);
  20216. /* Set the default configuration parameters:
  20217. */
  20218. s.max_lazy_match = configuration_table[s.level].max_lazy;
  20219. s.good_match = configuration_table[s.level].good_length;
  20220. s.nice_match = configuration_table[s.level].nice_length;
  20221. s.max_chain_length = configuration_table[s.level].max_chain;
  20222. s.strstart = 0;
  20223. s.block_start = 0;
  20224. s.lookahead = 0;
  20225. s.insert = 0;
  20226. s.match_length = s.prev_length = MIN_MATCH - 1;
  20227. s.match_available = 0;
  20228. s.ins_h = 0;
  20229. }
  20230. function DeflateState() {
  20231. this.strm = null; /* pointer back to this zlib stream */
  20232. this.status = 0; /* as the name implies */
  20233. this.pending_buf = null; /* output still pending */
  20234. this.pending_buf_size = 0; /* size of pending_buf */
  20235. this.pending_out = 0; /* next pending byte to output to the stream */
  20236. this.pending = 0; /* nb of bytes in the pending buffer */
  20237. this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
  20238. this.gzhead = null; /* gzip header information to write */
  20239. this.gzindex = 0; /* where in extra, name, or comment */
  20240. this.method = Z_DEFLATED; /* can only be DEFLATED */
  20241. this.last_flush = -1; /* value of flush param for previous deflate call */
  20242. this.w_size = 0; /* LZ77 window size (32K by default) */
  20243. this.w_bits = 0; /* log2(w_size) (8..16) */
  20244. this.w_mask = 0; /* w_size - 1 */
  20245. this.window = null;
  20246. /* Sliding window. Input bytes are read into the second half of the window,
  20247. * and move to the first half later to keep a dictionary of at least wSize
  20248. * bytes. With this organization, matches are limited to a distance of
  20249. * wSize-MAX_MATCH bytes, but this ensures that IO is always
  20250. * performed with a length multiple of the block size.
  20251. */
  20252. this.window_size = 0;
  20253. /* Actual size of window: 2*wSize, except when the user input buffer
  20254. * is directly used as sliding window.
  20255. */
  20256. this.prev = null;
  20257. /* Link to older string with same hash index. To limit the size of this
  20258. * array to 64K, this link is maintained only for the last 32K strings.
  20259. * An index in this array is thus a window index modulo 32K.
  20260. */
  20261. this.head = null; /* Heads of the hash chains or NIL. */
  20262. this.ins_h = 0; /* hash index of string to be inserted */
  20263. this.hash_size = 0; /* number of elements in hash table */
  20264. this.hash_bits = 0; /* log2(hash_size) */
  20265. this.hash_mask = 0; /* hash_size-1 */
  20266. this.hash_shift = 0;
  20267. /* Number of bits by which ins_h must be shifted at each input
  20268. * step. It must be such that after MIN_MATCH steps, the oldest
  20269. * byte no longer takes part in the hash key, that is:
  20270. * hash_shift * MIN_MATCH >= hash_bits
  20271. */
  20272. this.block_start = 0;
  20273. /* Window position at the beginning of the current output block. Gets
  20274. * negative when the window is moved backwards.
  20275. */
  20276. this.match_length = 0; /* length of best match */
  20277. this.prev_match = 0; /* previous match */
  20278. this.match_available = 0; /* set if previous match exists */
  20279. this.strstart = 0; /* start of string to insert */
  20280. this.match_start = 0; /* start of matching string */
  20281. this.lookahead = 0; /* number of valid bytes ahead in window */
  20282. this.prev_length = 0;
  20283. /* Length of the best match at previous step. Matches not greater than this
  20284. * are discarded. This is used in the lazy match evaluation.
  20285. */
  20286. this.max_chain_length = 0;
  20287. /* To speed up deflation, hash chains are never searched beyond this
  20288. * length. A higher limit improves compression ratio but degrades the
  20289. * speed.
  20290. */
  20291. this.max_lazy_match = 0;
  20292. /* Attempt to find a better match only when the current match is strictly
  20293. * smaller than this value. This mechanism is used only for compression
  20294. * levels >= 4.
  20295. */
  20296. // That's alias to max_lazy_match, don't use directly
  20297. //this.max_insert_length = 0;
  20298. /* Insert new strings in the hash table only if the match length is not
  20299. * greater than this length. This saves time but degrades compression.
  20300. * max_insert_length is used only for compression levels <= 3.
  20301. */
  20302. this.level = 0; /* compression level (1..9) */
  20303. this.strategy = 0; /* favor or force Huffman coding*/
  20304. this.good_match = 0;
  20305. /* Use a faster search when the previous match is longer than this */
  20306. this.nice_match = 0; /* Stop searching when current match exceeds this */
  20307. /* used by trees.c: */
  20308. /* Didn't use ct_data typedef below to suppress compiler warning */
  20309. // struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */
  20310. // struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */
  20311. // struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */
  20312. // Use flat array of DOUBLE size, with interleaved fata,
  20313. // because JS does not support effective
  20314. this.dyn_ltree = new utils.Buf16(HEAP_SIZE * 2);
  20315. this.dyn_dtree = new utils.Buf16((2*D_CODES+1) * 2);
  20316. this.bl_tree = new utils.Buf16((2*BL_CODES+1) * 2);
  20317. zero(this.dyn_ltree);
  20318. zero(this.dyn_dtree);
  20319. zero(this.bl_tree);
  20320. this.l_desc = null; /* desc. for literal tree */
  20321. this.d_desc = null; /* desc. for distance tree */
  20322. this.bl_desc = null; /* desc. for bit length tree */
  20323. //ush bl_count[MAX_BITS+1];
  20324. this.bl_count = new utils.Buf16(MAX_BITS+1);
  20325. /* number of codes at each bit length for an optimal tree */
  20326. //int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */
  20327. this.heap = new utils.Buf16(2*L_CODES+1); /* heap used to build the Huffman trees */
  20328. zero(this.heap);
  20329. this.heap_len = 0; /* number of elements in the heap */
  20330. this.heap_max = 0; /* element of largest frequency */
  20331. /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.
  20332. * The same heap array is used to build all trees.
  20333. */
  20334. this.depth = new utils.Buf16(2*L_CODES+1); //uch depth[2*L_CODES+1];
  20335. zero(this.depth);
  20336. /* Depth of each subtree used as tie breaker for trees of equal frequency
  20337. */
  20338. this.l_buf = 0; /* buffer index for literals or lengths */
  20339. this.lit_bufsize = 0;
  20340. /* Size of match buffer for literals/lengths. There are 4 reasons for
  20341. * limiting lit_bufsize to 64K:
  20342. * - frequencies can be kept in 16 bit counters
  20343. * - if compression is not successful for the first block, all input
  20344. * data is still in the window so we can still emit a stored block even
  20345. * when input comes from standard input. (This can also be done for
  20346. * all blocks if lit_bufsize is not greater than 32K.)
  20347. * - if compression is not successful for a file smaller than 64K, we can
  20348. * even emit a stored file instead of a stored block (saving 5 bytes).
  20349. * This is applicable only for zip (not gzip or zlib).
  20350. * - creating new Huffman trees less frequently may not provide fast
  20351. * adaptation to changes in the input data statistics. (Take for
  20352. * example a binary file with poorly compressible code followed by
  20353. * a highly compressible string table.) Smaller buffer sizes give
  20354. * fast adaptation but have of course the overhead of transmitting
  20355. * trees more frequently.
  20356. * - I can't count above 4
  20357. */
  20358. this.last_lit = 0; /* running index in l_buf */
  20359. this.d_buf = 0;
  20360. /* Buffer index for distances. To simplify the code, d_buf and l_buf have
  20361. * the same number of elements. To use different lengths, an extra flag
  20362. * array would be necessary.
  20363. */
  20364. this.opt_len = 0; /* bit length of current block with optimal trees */
  20365. this.static_len = 0; /* bit length of current block with static trees */
  20366. this.matches = 0; /* number of string matches in current block */
  20367. this.insert = 0; /* bytes at end of window left to insert */
  20368. this.bi_buf = 0;
  20369. /* Output buffer. bits are inserted starting at the bottom (least
  20370. * significant bits).
  20371. */
  20372. this.bi_valid = 0;
  20373. /* Number of valid bits in bi_buf. All bits above the last valid bit
  20374. * are always zero.
  20375. */
  20376. // Used for window memory init. We safely ignore it for JS. That makes
  20377. // sense only for pointers and memory check tools.
  20378. //this.high_water = 0;
  20379. /* High water mark offset in window for initialized bytes -- bytes above
  20380. * this are set to zero in order to avoid memory check warnings when
  20381. * longest match routines access bytes past the input. This is then
  20382. * updated to the new high water mark.
  20383. */
  20384. }
  20385. function deflateResetKeep(strm) {
  20386. var s;
  20387. if (!strm || !strm.state) {
  20388. return err(strm, Z_STREAM_ERROR);
  20389. }
  20390. strm.total_in = strm.total_out = 0;
  20391. strm.data_type = Z_UNKNOWN;
  20392. s = strm.state;
  20393. s.pending = 0;
  20394. s.pending_out = 0;
  20395. if (s.wrap < 0) {
  20396. s.wrap = -s.wrap;
  20397. /* was made negative by deflate(..., Z_FINISH); */
  20398. }
  20399. s.status = (s.wrap ? INIT_STATE : BUSY_STATE);
  20400. strm.adler = (s.wrap === 2) ?
  20401. 0 // crc32(0, Z_NULL, 0)
  20402. :
  20403. 1; // adler32(0, Z_NULL, 0)
  20404. s.last_flush = Z_NO_FLUSH;
  20405. trees._tr_init(s);
  20406. return Z_OK;
  20407. }
  20408. function deflateReset(strm) {
  20409. var ret = deflateResetKeep(strm);
  20410. if (ret === Z_OK) {
  20411. lm_init(strm.state);
  20412. }
  20413. return ret;
  20414. }
  20415. function deflateSetHeader(strm, head) {
  20416. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  20417. if (strm.state.wrap !== 2) { return Z_STREAM_ERROR; }
  20418. strm.state.gzhead = head;
  20419. return Z_OK;
  20420. }
  20421. function deflateInit2(strm, level, method, windowBits, memLevel, strategy) {
  20422. if (!strm) { // === Z_NULL
  20423. return Z_STREAM_ERROR;
  20424. }
  20425. var wrap = 1;
  20426. if (level === Z_DEFAULT_COMPRESSION) {
  20427. level = 6;
  20428. }
  20429. if (windowBits < 0) { /* suppress zlib wrapper */
  20430. wrap = 0;
  20431. windowBits = -windowBits;
  20432. }
  20433. else if (windowBits > 15) {
  20434. wrap = 2; /* write gzip wrapper instead */
  20435. windowBits -= 16;
  20436. }
  20437. if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method !== Z_DEFLATED ||
  20438. windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||
  20439. strategy < 0 || strategy > Z_FIXED) {
  20440. return err(strm, Z_STREAM_ERROR);
  20441. }
  20442. if (windowBits === 8) {
  20443. windowBits = 9;
  20444. }
  20445. /* until 256-byte window bug fixed */
  20446. var s = new DeflateState();
  20447. strm.state = s;
  20448. s.strm = strm;
  20449. s.wrap = wrap;
  20450. s.gzhead = null;
  20451. s.w_bits = windowBits;
  20452. s.w_size = 1 << s.w_bits;
  20453. s.w_mask = s.w_size - 1;
  20454. s.hash_bits = memLevel + 7;
  20455. s.hash_size = 1 << s.hash_bits;
  20456. s.hash_mask = s.hash_size - 1;
  20457. s.hash_shift = ~~((s.hash_bits + MIN_MATCH - 1) / MIN_MATCH);
  20458. s.window = new utils.Buf8(s.w_size * 2);
  20459. s.head = new utils.Buf16(s.hash_size);
  20460. s.prev = new utils.Buf16(s.w_size);
  20461. // Don't need mem init magic for JS.
  20462. //s.high_water = 0; /* nothing written to s->window yet */
  20463. s.lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */
  20464. s.pending_buf_size = s.lit_bufsize * 4;
  20465. s.pending_buf = new utils.Buf8(s.pending_buf_size);
  20466. s.d_buf = s.lit_bufsize >> 1;
  20467. s.l_buf = (1 + 2) * s.lit_bufsize;
  20468. s.level = level;
  20469. s.strategy = strategy;
  20470. s.method = method;
  20471. return deflateReset(strm);
  20472. }
  20473. function deflateInit(strm, level) {
  20474. return deflateInit2(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY);
  20475. }
  20476. function deflate(strm, flush) {
  20477. var old_flush, s;
  20478. var beg, val; // for gzip header write only
  20479. if (!strm || !strm.state ||
  20480. flush > Z_BLOCK || flush < 0) {
  20481. return strm ? err(strm, Z_STREAM_ERROR) : Z_STREAM_ERROR;
  20482. }
  20483. s = strm.state;
  20484. if (!strm.output ||
  20485. (!strm.input && strm.avail_in !== 0) ||
  20486. (s.status === FINISH_STATE && flush !== Z_FINISH)) {
  20487. return err(strm, (strm.avail_out === 0) ? Z_BUF_ERROR : Z_STREAM_ERROR);
  20488. }
  20489. s.strm = strm; /* just in case */
  20490. old_flush = s.last_flush;
  20491. s.last_flush = flush;
  20492. /* Write the header */
  20493. if (s.status === INIT_STATE) {
  20494. if (s.wrap === 2) { // GZIP header
  20495. strm.adler = 0; //crc32(0L, Z_NULL, 0);
  20496. put_byte(s, 31);
  20497. put_byte(s, 139);
  20498. put_byte(s, 8);
  20499. if (!s.gzhead) { // s->gzhead == Z_NULL
  20500. put_byte(s, 0);
  20501. put_byte(s, 0);
  20502. put_byte(s, 0);
  20503. put_byte(s, 0);
  20504. put_byte(s, 0);
  20505. put_byte(s, s.level === 9 ? 2 :
  20506. (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
  20507. 4 : 0));
  20508. put_byte(s, OS_CODE);
  20509. s.status = BUSY_STATE;
  20510. }
  20511. else {
  20512. put_byte(s, (s.gzhead.text ? 1 : 0) +
  20513. (s.gzhead.hcrc ? 2 : 0) +
  20514. (!s.gzhead.extra ? 0 : 4) +
  20515. (!s.gzhead.name ? 0 : 8) +
  20516. (!s.gzhead.comment ? 0 : 16)
  20517. );
  20518. put_byte(s, s.gzhead.time & 0xff);
  20519. put_byte(s, (s.gzhead.time >> 8) & 0xff);
  20520. put_byte(s, (s.gzhead.time >> 16) & 0xff);
  20521. put_byte(s, (s.gzhead.time >> 24) & 0xff);
  20522. put_byte(s, s.level === 9 ? 2 :
  20523. (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
  20524. 4 : 0));
  20525. put_byte(s, s.gzhead.os & 0xff);
  20526. if (s.gzhead.extra && s.gzhead.extra.length) {
  20527. put_byte(s, s.gzhead.extra.length & 0xff);
  20528. put_byte(s, (s.gzhead.extra.length >> 8) & 0xff);
  20529. }
  20530. if (s.gzhead.hcrc) {
  20531. strm.adler = crc32(strm.adler, s.pending_buf, s.pending, 0);
  20532. }
  20533. s.gzindex = 0;
  20534. s.status = EXTRA_STATE;
  20535. }
  20536. }
  20537. else // DEFLATE header
  20538. {
  20539. var header = (Z_DEFLATED + ((s.w_bits - 8) << 4)) << 8;
  20540. var level_flags = -1;
  20541. if (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2) {
  20542. level_flags = 0;
  20543. } else if (s.level < 6) {
  20544. level_flags = 1;
  20545. } else if (s.level === 6) {
  20546. level_flags = 2;
  20547. } else {
  20548. level_flags = 3;
  20549. }
  20550. header |= (level_flags << 6);
  20551. if (s.strstart !== 0) { header |= PRESET_DICT; }
  20552. header += 31 - (header % 31);
  20553. s.status = BUSY_STATE;
  20554. putShortMSB(s, header);
  20555. /* Save the adler32 of the preset dictionary: */
  20556. if (s.strstart !== 0) {
  20557. putShortMSB(s, strm.adler >>> 16);
  20558. putShortMSB(s, strm.adler & 0xffff);
  20559. }
  20560. strm.adler = 1; // adler32(0L, Z_NULL, 0);
  20561. }
  20562. }
  20563. //#ifdef GZIP
  20564. if (s.status === EXTRA_STATE) {
  20565. if (s.gzhead.extra/* != Z_NULL*/) {
  20566. beg = s.pending; /* start of bytes to update crc */
  20567. while (s.gzindex < (s.gzhead.extra.length & 0xffff)) {
  20568. if (s.pending === s.pending_buf_size) {
  20569. if (s.gzhead.hcrc && s.pending > beg) {
  20570. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  20571. }
  20572. flush_pending(strm);
  20573. beg = s.pending;
  20574. if (s.pending === s.pending_buf_size) {
  20575. break;
  20576. }
  20577. }
  20578. put_byte(s, s.gzhead.extra[s.gzindex] & 0xff);
  20579. s.gzindex++;
  20580. }
  20581. if (s.gzhead.hcrc && s.pending > beg) {
  20582. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  20583. }
  20584. if (s.gzindex === s.gzhead.extra.length) {
  20585. s.gzindex = 0;
  20586. s.status = NAME_STATE;
  20587. }
  20588. }
  20589. else {
  20590. s.status = NAME_STATE;
  20591. }
  20592. }
  20593. if (s.status === NAME_STATE) {
  20594. if (s.gzhead.name/* != Z_NULL*/) {
  20595. beg = s.pending; /* start of bytes to update crc */
  20596. //int val;
  20597. do {
  20598. if (s.pending === s.pending_buf_size) {
  20599. if (s.gzhead.hcrc && s.pending > beg) {
  20600. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  20601. }
  20602. flush_pending(strm);
  20603. beg = s.pending;
  20604. if (s.pending === s.pending_buf_size) {
  20605. val = 1;
  20606. break;
  20607. }
  20608. }
  20609. // JS specific: little magic to add zero terminator to end of string
  20610. if (s.gzindex < s.gzhead.name.length) {
  20611. val = s.gzhead.name.charCodeAt(s.gzindex++) & 0xff;
  20612. } else {
  20613. val = 0;
  20614. }
  20615. put_byte(s, val);
  20616. } while (val !== 0);
  20617. if (s.gzhead.hcrc && s.pending > beg){
  20618. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  20619. }
  20620. if (val === 0) {
  20621. s.gzindex = 0;
  20622. s.status = COMMENT_STATE;
  20623. }
  20624. }
  20625. else {
  20626. s.status = COMMENT_STATE;
  20627. }
  20628. }
  20629. if (s.status === COMMENT_STATE) {
  20630. if (s.gzhead.comment/* != Z_NULL*/) {
  20631. beg = s.pending; /* start of bytes to update crc */
  20632. //int val;
  20633. do {
  20634. if (s.pending === s.pending_buf_size) {
  20635. if (s.gzhead.hcrc && s.pending > beg) {
  20636. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  20637. }
  20638. flush_pending(strm);
  20639. beg = s.pending;
  20640. if (s.pending === s.pending_buf_size) {
  20641. val = 1;
  20642. break;
  20643. }
  20644. }
  20645. // JS specific: little magic to add zero terminator to end of string
  20646. if (s.gzindex < s.gzhead.comment.length) {
  20647. val = s.gzhead.comment.charCodeAt(s.gzindex++) & 0xff;
  20648. } else {
  20649. val = 0;
  20650. }
  20651. put_byte(s, val);
  20652. } while (val !== 0);
  20653. if (s.gzhead.hcrc && s.pending > beg) {
  20654. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  20655. }
  20656. if (val === 0) {
  20657. s.status = HCRC_STATE;
  20658. }
  20659. }
  20660. else {
  20661. s.status = HCRC_STATE;
  20662. }
  20663. }
  20664. if (s.status === HCRC_STATE) {
  20665. if (s.gzhead.hcrc) {
  20666. if (s.pending + 2 > s.pending_buf_size) {
  20667. flush_pending(strm);
  20668. }
  20669. if (s.pending + 2 <= s.pending_buf_size) {
  20670. put_byte(s, strm.adler & 0xff);
  20671. put_byte(s, (strm.adler >> 8) & 0xff);
  20672. strm.adler = 0; //crc32(0L, Z_NULL, 0);
  20673. s.status = BUSY_STATE;
  20674. }
  20675. }
  20676. else {
  20677. s.status = BUSY_STATE;
  20678. }
  20679. }
  20680. //#endif
  20681. /* Flush as much pending output as possible */
  20682. if (s.pending !== 0) {
  20683. flush_pending(strm);
  20684. if (strm.avail_out === 0) {
  20685. /* Since avail_out is 0, deflate will be called again with
  20686. * more output space, but possibly with both pending and
  20687. * avail_in equal to zero. There won't be anything to do,
  20688. * but this is not an error situation so make sure we
  20689. * return OK instead of BUF_ERROR at next call of deflate:
  20690. */
  20691. s.last_flush = -1;
  20692. return Z_OK;
  20693. }
  20694. /* Make sure there is something to do and avoid duplicate consecutive
  20695. * flushes. For repeated and useless calls with Z_FINISH, we keep
  20696. * returning Z_STREAM_END instead of Z_BUF_ERROR.
  20697. */
  20698. } else if (strm.avail_in === 0 && rank(flush) <= rank(old_flush) &&
  20699. flush !== Z_FINISH) {
  20700. return err(strm, Z_BUF_ERROR);
  20701. }
  20702. /* User must not provide more input after the first FINISH: */
  20703. if (s.status === FINISH_STATE && strm.avail_in !== 0) {
  20704. return err(strm, Z_BUF_ERROR);
  20705. }
  20706. /* Start a new block or continue the current one.
  20707. */
  20708. if (strm.avail_in !== 0 || s.lookahead !== 0 ||
  20709. (flush !== Z_NO_FLUSH && s.status !== FINISH_STATE)) {
  20710. var bstate = (s.strategy === Z_HUFFMAN_ONLY) ? deflate_huff(s, flush) :
  20711. (s.strategy === Z_RLE ? deflate_rle(s, flush) :
  20712. configuration_table[s.level].func(s, flush));
  20713. if (bstate === BS_FINISH_STARTED || bstate === BS_FINISH_DONE) {
  20714. s.status = FINISH_STATE;
  20715. }
  20716. if (bstate === BS_NEED_MORE || bstate === BS_FINISH_STARTED) {
  20717. if (strm.avail_out === 0) {
  20718. s.last_flush = -1;
  20719. /* avoid BUF_ERROR next call, see above */
  20720. }
  20721. return Z_OK;
  20722. /* If flush != Z_NO_FLUSH && avail_out == 0, the next call
  20723. * of deflate should use the same flush parameter to make sure
  20724. * that the flush is complete. So we don't have to output an
  20725. * empty block here, this will be done at next call. This also
  20726. * ensures that for a very small output buffer, we emit at most
  20727. * one empty block.
  20728. */
  20729. }
  20730. if (bstate === BS_BLOCK_DONE) {
  20731. if (flush === Z_PARTIAL_FLUSH) {
  20732. trees._tr_align(s);
  20733. }
  20734. else if (flush !== Z_BLOCK) { /* FULL_FLUSH or SYNC_FLUSH */
  20735. trees._tr_stored_block(s, 0, 0, false);
  20736. /* For a full flush, this empty block will be recognized
  20737. * as a special marker by inflate_sync().
  20738. */
  20739. if (flush === Z_FULL_FLUSH) {
  20740. /*** CLEAR_HASH(s); ***/ /* forget history */
  20741. zero(s.head); // Fill with NIL (= 0);
  20742. if (s.lookahead === 0) {
  20743. s.strstart = 0;
  20744. s.block_start = 0;
  20745. s.insert = 0;
  20746. }
  20747. }
  20748. }
  20749. flush_pending(strm);
  20750. if (strm.avail_out === 0) {
  20751. s.last_flush = -1; /* avoid BUF_ERROR at next call, see above */
  20752. return Z_OK;
  20753. }
  20754. }
  20755. }
  20756. //Assert(strm->avail_out > 0, "bug2");
  20757. //if (strm.avail_out <= 0) { throw new Error("bug2");}
  20758. if (flush !== Z_FINISH) { return Z_OK; }
  20759. if (s.wrap <= 0) { return Z_STREAM_END; }
  20760. /* Write the trailer */
  20761. if (s.wrap === 2) {
  20762. put_byte(s, strm.adler & 0xff);
  20763. put_byte(s, (strm.adler >> 8) & 0xff);
  20764. put_byte(s, (strm.adler >> 16) & 0xff);
  20765. put_byte(s, (strm.adler >> 24) & 0xff);
  20766. put_byte(s, strm.total_in & 0xff);
  20767. put_byte(s, (strm.total_in >> 8) & 0xff);
  20768. put_byte(s, (strm.total_in >> 16) & 0xff);
  20769. put_byte(s, (strm.total_in >> 24) & 0xff);
  20770. }
  20771. else
  20772. {
  20773. putShortMSB(s, strm.adler >>> 16);
  20774. putShortMSB(s, strm.adler & 0xffff);
  20775. }
  20776. flush_pending(strm);
  20777. /* If avail_out is zero, the application will call deflate again
  20778. * to flush the rest.
  20779. */
  20780. if (s.wrap > 0) { s.wrap = -s.wrap; }
  20781. /* write the trailer only once! */
  20782. return s.pending !== 0 ? Z_OK : Z_STREAM_END;
  20783. }
  20784. function deflateEnd(strm) {
  20785. var status;
  20786. if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) {
  20787. return Z_STREAM_ERROR;
  20788. }
  20789. status = strm.state.status;
  20790. if (status !== INIT_STATE &&
  20791. status !== EXTRA_STATE &&
  20792. status !== NAME_STATE &&
  20793. status !== COMMENT_STATE &&
  20794. status !== HCRC_STATE &&
  20795. status !== BUSY_STATE &&
  20796. status !== FINISH_STATE
  20797. ) {
  20798. return err(strm, Z_STREAM_ERROR);
  20799. }
  20800. strm.state = null;
  20801. return status === BUSY_STATE ? err(strm, Z_DATA_ERROR) : Z_OK;
  20802. }
  20803. /* =========================================================================
  20804. * Copy the source state to the destination state
  20805. */
  20806. //function deflateCopy(dest, source) {
  20807. //
  20808. //}
  20809. exports.deflateInit = deflateInit;
  20810. exports.deflateInit2 = deflateInit2;
  20811. exports.deflateReset = deflateReset;
  20812. exports.deflateResetKeep = deflateResetKeep;
  20813. exports.deflateSetHeader = deflateSetHeader;
  20814. exports.deflate = deflate;
  20815. exports.deflateEnd = deflateEnd;
  20816. exports.deflateInfo = 'pako deflate (from Nodeca project)';
  20817. /* Not implemented
  20818. exports.deflateBound = deflateBound;
  20819. exports.deflateCopy = deflateCopy;
  20820. exports.deflateSetDictionary = deflateSetDictionary;
  20821. exports.deflateParams = deflateParams;
  20822. exports.deflatePending = deflatePending;
  20823. exports.deflatePrime = deflatePrime;
  20824. exports.deflateTune = deflateTune;
  20825. */
  20826. },{"../utils/common":69,"./adler32":71,"./crc32":73,"./messages":79,"./trees":80}],75:[function(require,module,exports){
  20827. 'use strict';
  20828. function GZheader() {
  20829. /* true if compressed data believed to be text */
  20830. this.text = 0;
  20831. /* modification time */
  20832. this.time = 0;
  20833. /* extra flags (not used when writing a gzip file) */
  20834. this.xflags = 0;
  20835. /* operating system */
  20836. this.os = 0;
  20837. /* pointer to extra field or Z_NULL if none */
  20838. this.extra = null;
  20839. /* extra field length (valid if extra != Z_NULL) */
  20840. this.extra_len = 0; // Actually, we don't need it in JS,
  20841. // but leave for few code modifications
  20842. //
  20843. // Setup limits is not necessary because in js we should not preallocate memory
  20844. // for inflate use constant limit in 65536 bytes
  20845. //
  20846. /* space at extra (only when reading header) */
  20847. // this.extra_max = 0;
  20848. /* pointer to zero-terminated file name or Z_NULL */
  20849. this.name = '';
  20850. /* space at name (only when reading header) */
  20851. // this.name_max = 0;
  20852. /* pointer to zero-terminated comment or Z_NULL */
  20853. this.comment = '';
  20854. /* space at comment (only when reading header) */
  20855. // this.comm_max = 0;
  20856. /* true if there was or will be a header crc */
  20857. this.hcrc = 0;
  20858. /* true when done reading gzip header (not used when writing a gzip file) */
  20859. this.done = false;
  20860. }
  20861. module.exports = GZheader;
  20862. },{}],76:[function(require,module,exports){
  20863. 'use strict';
  20864. // See state defs from inflate.js
  20865. var BAD = 30; /* got a data error -- remain here until reset */
  20866. var TYPE = 12; /* i: waiting for type bits, including last-flag bit */
  20867. /*
  20868. Decode literal, length, and distance codes and write out the resulting
  20869. literal and match bytes until either not enough input or output is
  20870. available, an end-of-block is encountered, or a data error is encountered.
  20871. When large enough input and output buffers are supplied to inflate(), for
  20872. example, a 16K input buffer and a 64K output buffer, more than 95% of the
  20873. inflate execution time is spent in this routine.
  20874. Entry assumptions:
  20875. state.mode === LEN
  20876. strm.avail_in >= 6
  20877. strm.avail_out >= 258
  20878. start >= strm.avail_out
  20879. state.bits < 8
  20880. On return, state.mode is one of:
  20881. LEN -- ran out of enough output space or enough available input
  20882. TYPE -- reached end of block code, inflate() to interpret next block
  20883. BAD -- error in block data
  20884. Notes:
  20885. - The maximum input bits used by a length/distance pair is 15 bits for the
  20886. length code, 5 bits for the length extra, 15 bits for the distance code,
  20887. and 13 bits for the distance extra. This totals 48 bits, or six bytes.
  20888. Therefore if strm.avail_in >= 6, then there is enough input to avoid
  20889. checking for available input while decoding.
  20890. - The maximum bytes that a single length/distance pair can output is 258
  20891. bytes, which is the maximum length that can be coded. inflate_fast()
  20892. requires strm.avail_out >= 258 for each loop to avoid checking for
  20893. output space.
  20894. */
  20895. module.exports = function inflate_fast(strm, start) {
  20896. var state;
  20897. var _in; /* local strm.input */
  20898. var last; /* have enough input while in < last */
  20899. var _out; /* local strm.output */
  20900. var beg; /* inflate()'s initial strm.output */
  20901. var end; /* while out < end, enough space available */
  20902. //#ifdef INFLATE_STRICT
  20903. var dmax; /* maximum distance from zlib header */
  20904. //#endif
  20905. var wsize; /* window size or zero if not using window */
  20906. var whave; /* valid bytes in the window */
  20907. var wnext; /* window write index */
  20908. var window; /* allocated sliding window, if wsize != 0 */
  20909. var hold; /* local strm.hold */
  20910. var bits; /* local strm.bits */
  20911. var lcode; /* local strm.lencode */
  20912. var dcode; /* local strm.distcode */
  20913. var lmask; /* mask for first level of length codes */
  20914. var dmask; /* mask for first level of distance codes */
  20915. var here; /* retrieved table entry */
  20916. var op; /* code bits, operation, extra bits, or */
  20917. /* window position, window bytes to copy */
  20918. var len; /* match length, unused bytes */
  20919. var dist; /* match distance */
  20920. var from; /* where to copy match from */
  20921. var from_source;
  20922. var input, output; // JS specific, because we have no pointers
  20923. /* copy state to local variables */
  20924. state = strm.state;
  20925. //here = state.here;
  20926. _in = strm.next_in;
  20927. input = strm.input;
  20928. last = _in + (strm.avail_in - 5);
  20929. _out = strm.next_out;
  20930. output = strm.output;
  20931. beg = _out - (start - strm.avail_out);
  20932. end = _out + (strm.avail_out - 257);
  20933. //#ifdef INFLATE_STRICT
  20934. dmax = state.dmax;
  20935. //#endif
  20936. wsize = state.wsize;
  20937. whave = state.whave;
  20938. wnext = state.wnext;
  20939. window = state.window;
  20940. hold = state.hold;
  20941. bits = state.bits;
  20942. lcode = state.lencode;
  20943. dcode = state.distcode;
  20944. lmask = (1 << state.lenbits) - 1;
  20945. dmask = (1 << state.distbits) - 1;
  20946. /* decode literals and length/distances until end-of-block or not enough
  20947. input data or output space */
  20948. top:
  20949. do {
  20950. if (bits < 15) {
  20951. hold += input[_in++] << bits;
  20952. bits += 8;
  20953. hold += input[_in++] << bits;
  20954. bits += 8;
  20955. }
  20956. here = lcode[hold & lmask];
  20957. dolen:
  20958. for (;;) { // Goto emulation
  20959. op = here >>> 24/*here.bits*/;
  20960. hold >>>= op;
  20961. bits -= op;
  20962. op = (here >>> 16) & 0xff/*here.op*/;
  20963. if (op === 0) { /* literal */
  20964. //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
  20965. // "inflate: literal '%c'\n" :
  20966. // "inflate: literal 0x%02x\n", here.val));
  20967. output[_out++] = here & 0xffff/*here.val*/;
  20968. }
  20969. else if (op & 16) { /* length base */
  20970. len = here & 0xffff/*here.val*/;
  20971. op &= 15; /* number of extra bits */
  20972. if (op) {
  20973. if (bits < op) {
  20974. hold += input[_in++] << bits;
  20975. bits += 8;
  20976. }
  20977. len += hold & ((1 << op) - 1);
  20978. hold >>>= op;
  20979. bits -= op;
  20980. }
  20981. //Tracevv((stderr, "inflate: length %u\n", len));
  20982. if (bits < 15) {
  20983. hold += input[_in++] << bits;
  20984. bits += 8;
  20985. hold += input[_in++] << bits;
  20986. bits += 8;
  20987. }
  20988. here = dcode[hold & dmask];
  20989. dodist:
  20990. for (;;) { // goto emulation
  20991. op = here >>> 24/*here.bits*/;
  20992. hold >>>= op;
  20993. bits -= op;
  20994. op = (here >>> 16) & 0xff/*here.op*/;
  20995. if (op & 16) { /* distance base */
  20996. dist = here & 0xffff/*here.val*/;
  20997. op &= 15; /* number of extra bits */
  20998. if (bits < op) {
  20999. hold += input[_in++] << bits;
  21000. bits += 8;
  21001. if (bits < op) {
  21002. hold += input[_in++] << bits;
  21003. bits += 8;
  21004. }
  21005. }
  21006. dist += hold & ((1 << op) - 1);
  21007. //#ifdef INFLATE_STRICT
  21008. if (dist > dmax) {
  21009. strm.msg = 'invalid distance too far back';
  21010. state.mode = BAD;
  21011. break top;
  21012. }
  21013. //#endif
  21014. hold >>>= op;
  21015. bits -= op;
  21016. //Tracevv((stderr, "inflate: distance %u\n", dist));
  21017. op = _out - beg; /* max distance in output */
  21018. if (dist > op) { /* see if copy from window */
  21019. op = dist - op; /* distance back in window */
  21020. if (op > whave) {
  21021. if (state.sane) {
  21022. strm.msg = 'invalid distance too far back';
  21023. state.mode = BAD;
  21024. break top;
  21025. }
  21026. // (!) This block is disabled in zlib defailts,
  21027. // don't enable it for binary compatibility
  21028. //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
  21029. // if (len <= op - whave) {
  21030. // do {
  21031. // output[_out++] = 0;
  21032. // } while (--len);
  21033. // continue top;
  21034. // }
  21035. // len -= op - whave;
  21036. // do {
  21037. // output[_out++] = 0;
  21038. // } while (--op > whave);
  21039. // if (op === 0) {
  21040. // from = _out - dist;
  21041. // do {
  21042. // output[_out++] = output[from++];
  21043. // } while (--len);
  21044. // continue top;
  21045. // }
  21046. //#endif
  21047. }
  21048. from = 0; // window index
  21049. from_source = window;
  21050. if (wnext === 0) { /* very common case */
  21051. from += wsize - op;
  21052. if (op < len) { /* some from window */
  21053. len -= op;
  21054. do {
  21055. output[_out++] = window[from++];
  21056. } while (--op);
  21057. from = _out - dist; /* rest from output */
  21058. from_source = output;
  21059. }
  21060. }
  21061. else if (wnext < op) { /* wrap around window */
  21062. from += wsize + wnext - op;
  21063. op -= wnext;
  21064. if (op < len) { /* some from end of window */
  21065. len -= op;
  21066. do {
  21067. output[_out++] = window[from++];
  21068. } while (--op);
  21069. from = 0;
  21070. if (wnext < len) { /* some from start of window */
  21071. op = wnext;
  21072. len -= op;
  21073. do {
  21074. output[_out++] = window[from++];
  21075. } while (--op);
  21076. from = _out - dist; /* rest from output */
  21077. from_source = output;
  21078. }
  21079. }
  21080. }
  21081. else { /* contiguous in window */
  21082. from += wnext - op;
  21083. if (op < len) { /* some from window */
  21084. len -= op;
  21085. do {
  21086. output[_out++] = window[from++];
  21087. } while (--op);
  21088. from = _out - dist; /* rest from output */
  21089. from_source = output;
  21090. }
  21091. }
  21092. while (len > 2) {
  21093. output[_out++] = from_source[from++];
  21094. output[_out++] = from_source[from++];
  21095. output[_out++] = from_source[from++];
  21096. len -= 3;
  21097. }
  21098. if (len) {
  21099. output[_out++] = from_source[from++];
  21100. if (len > 1) {
  21101. output[_out++] = from_source[from++];
  21102. }
  21103. }
  21104. }
  21105. else {
  21106. from = _out - dist; /* copy direct from output */
  21107. do { /* minimum length is three */
  21108. output[_out++] = output[from++];
  21109. output[_out++] = output[from++];
  21110. output[_out++] = output[from++];
  21111. len -= 3;
  21112. } while (len > 2);
  21113. if (len) {
  21114. output[_out++] = output[from++];
  21115. if (len > 1) {
  21116. output[_out++] = output[from++];
  21117. }
  21118. }
  21119. }
  21120. }
  21121. else if ((op & 64) === 0) { /* 2nd level distance code */
  21122. here = dcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
  21123. continue dodist;
  21124. }
  21125. else {
  21126. strm.msg = 'invalid distance code';
  21127. state.mode = BAD;
  21128. break top;
  21129. }
  21130. break; // need to emulate goto via "continue"
  21131. }
  21132. }
  21133. else if ((op & 64) === 0) { /* 2nd level length code */
  21134. here = lcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
  21135. continue dolen;
  21136. }
  21137. else if (op & 32) { /* end-of-block */
  21138. //Tracevv((stderr, "inflate: end of block\n"));
  21139. state.mode = TYPE;
  21140. break top;
  21141. }
  21142. else {
  21143. strm.msg = 'invalid literal/length code';
  21144. state.mode = BAD;
  21145. break top;
  21146. }
  21147. break; // need to emulate goto via "continue"
  21148. }
  21149. } while (_in < last && _out < end);
  21150. /* return unused bytes (on entry, bits < 8, so in won't go too far back) */
  21151. len = bits >> 3;
  21152. _in -= len;
  21153. bits -= len << 3;
  21154. hold &= (1 << bits) - 1;
  21155. /* update state and return */
  21156. strm.next_in = _in;
  21157. strm.next_out = _out;
  21158. strm.avail_in = (_in < last ? 5 + (last - _in) : 5 - (_in - last));
  21159. strm.avail_out = (_out < end ? 257 + (end - _out) : 257 - (_out - end));
  21160. state.hold = hold;
  21161. state.bits = bits;
  21162. return;
  21163. };
  21164. },{}],77:[function(require,module,exports){
  21165. 'use strict';
  21166. var utils = require('../utils/common');
  21167. var adler32 = require('./adler32');
  21168. var crc32 = require('./crc32');
  21169. var inflate_fast = require('./inffast');
  21170. var inflate_table = require('./inftrees');
  21171. var CODES = 0;
  21172. var LENS = 1;
  21173. var DISTS = 2;
  21174. /* Public constants ==========================================================*/
  21175. /* ===========================================================================*/
  21176. /* Allowed flush values; see deflate() and inflate() below for details */
  21177. //var Z_NO_FLUSH = 0;
  21178. //var Z_PARTIAL_FLUSH = 1;
  21179. //var Z_SYNC_FLUSH = 2;
  21180. //var Z_FULL_FLUSH = 3;
  21181. var Z_FINISH = 4;
  21182. var Z_BLOCK = 5;
  21183. var Z_TREES = 6;
  21184. /* Return codes for the compression/decompression functions. Negative values
  21185. * are errors, positive values are used for special but normal events.
  21186. */
  21187. var Z_OK = 0;
  21188. var Z_STREAM_END = 1;
  21189. var Z_NEED_DICT = 2;
  21190. //var Z_ERRNO = -1;
  21191. var Z_STREAM_ERROR = -2;
  21192. var Z_DATA_ERROR = -3;
  21193. var Z_MEM_ERROR = -4;
  21194. var Z_BUF_ERROR = -5;
  21195. //var Z_VERSION_ERROR = -6;
  21196. /* The deflate compression method */
  21197. var Z_DEFLATED = 8;
  21198. /* STATES ====================================================================*/
  21199. /* ===========================================================================*/
  21200. var HEAD = 1; /* i: waiting for magic header */
  21201. var FLAGS = 2; /* i: waiting for method and flags (gzip) */
  21202. var TIME = 3; /* i: waiting for modification time (gzip) */
  21203. var OS = 4; /* i: waiting for extra flags and operating system (gzip) */
  21204. var EXLEN = 5; /* i: waiting for extra length (gzip) */
  21205. var EXTRA = 6; /* i: waiting for extra bytes (gzip) */
  21206. var NAME = 7; /* i: waiting for end of file name (gzip) */
  21207. var COMMENT = 8; /* i: waiting for end of comment (gzip) */
  21208. var HCRC = 9; /* i: waiting for header crc (gzip) */
  21209. var DICTID = 10; /* i: waiting for dictionary check value */
  21210. var DICT = 11; /* waiting for inflateSetDictionary() call */
  21211. var TYPE = 12; /* i: waiting for type bits, including last-flag bit */
  21212. var TYPEDO = 13; /* i: same, but skip check to exit inflate on new block */
  21213. var STORED = 14; /* i: waiting for stored size (length and complement) */
  21214. var COPY_ = 15; /* i/o: same as COPY below, but only first time in */
  21215. var COPY = 16; /* i/o: waiting for input or output to copy stored block */
  21216. var TABLE = 17; /* i: waiting for dynamic block table lengths */
  21217. var LENLENS = 18; /* i: waiting for code length code lengths */
  21218. var CODELENS = 19; /* i: waiting for length/lit and distance code lengths */
  21219. var LEN_ = 20; /* i: same as LEN below, but only first time in */
  21220. var LEN = 21; /* i: waiting for length/lit/eob code */
  21221. var LENEXT = 22; /* i: waiting for length extra bits */
  21222. var DIST = 23; /* i: waiting for distance code */
  21223. var DISTEXT = 24; /* i: waiting for distance extra bits */
  21224. var MATCH = 25; /* o: waiting for output space to copy string */
  21225. var LIT = 26; /* o: waiting for output space to write literal */
  21226. var CHECK = 27; /* i: waiting for 32-bit check value */
  21227. var LENGTH = 28; /* i: waiting for 32-bit length (gzip) */
  21228. var DONE = 29; /* finished check, done -- remain here until reset */
  21229. var BAD = 30; /* got a data error -- remain here until reset */
  21230. var MEM = 31; /* got an inflate() memory error -- remain here until reset */
  21231. var SYNC = 32; /* looking for synchronization bytes to restart inflate() */
  21232. /* ===========================================================================*/
  21233. var ENOUGH_LENS = 852;
  21234. var ENOUGH_DISTS = 592;
  21235. //var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
  21236. var MAX_WBITS = 15;
  21237. /* 32K LZ77 window */
  21238. var DEF_WBITS = MAX_WBITS;
  21239. function ZSWAP32(q) {
  21240. return (((q >>> 24) & 0xff) +
  21241. ((q >>> 8) & 0xff00) +
  21242. ((q & 0xff00) << 8) +
  21243. ((q & 0xff) << 24));
  21244. }
  21245. function InflateState() {
  21246. this.mode = 0; /* current inflate mode */
  21247. this.last = false; /* true if processing last block */
  21248. this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
  21249. this.havedict = false; /* true if dictionary provided */
  21250. this.flags = 0; /* gzip header method and flags (0 if zlib) */
  21251. this.dmax = 0; /* zlib header max distance (INFLATE_STRICT) */
  21252. this.check = 0; /* protected copy of check value */
  21253. this.total = 0; /* protected copy of output count */
  21254. // TODO: may be {}
  21255. this.head = null; /* where to save gzip header information */
  21256. /* sliding window */
  21257. this.wbits = 0; /* log base 2 of requested window size */
  21258. this.wsize = 0; /* window size or zero if not using window */
  21259. this.whave = 0; /* valid bytes in the window */
  21260. this.wnext = 0; /* window write index */
  21261. this.window = null; /* allocated sliding window, if needed */
  21262. /* bit accumulator */
  21263. this.hold = 0; /* input bit accumulator */
  21264. this.bits = 0; /* number of bits in "in" */
  21265. /* for string and stored block copying */
  21266. this.length = 0; /* literal or length of data to copy */
  21267. this.offset = 0; /* distance back to copy string from */
  21268. /* for table and code decoding */
  21269. this.extra = 0; /* extra bits needed */
  21270. /* fixed and dynamic code tables */
  21271. this.lencode = null; /* starting table for length/literal codes */
  21272. this.distcode = null; /* starting table for distance codes */
  21273. this.lenbits = 0; /* index bits for lencode */
  21274. this.distbits = 0; /* index bits for distcode */
  21275. /* dynamic table building */
  21276. this.ncode = 0; /* number of code length code lengths */
  21277. this.nlen = 0; /* number of length code lengths */
  21278. this.ndist = 0; /* number of distance code lengths */
  21279. this.have = 0; /* number of code lengths in lens[] */
  21280. this.next = null; /* next available space in codes[] */
  21281. this.lens = new utils.Buf16(320); /* temporary storage for code lengths */
  21282. this.work = new utils.Buf16(288); /* work area for code table building */
  21283. /*
  21284. because we don't have pointers in js, we use lencode and distcode directly
  21285. as buffers so we don't need codes
  21286. */
  21287. //this.codes = new utils.Buf32(ENOUGH); /* space for code tables */
  21288. this.lendyn = null; /* dynamic table for length/literal codes (JS specific) */
  21289. this.distdyn = null; /* dynamic table for distance codes (JS specific) */
  21290. this.sane = 0; /* if false, allow invalid distance too far */
  21291. this.back = 0; /* bits back of last unprocessed length/lit */
  21292. this.was = 0; /* initial length of match */
  21293. }
  21294. function inflateResetKeep(strm) {
  21295. var state;
  21296. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  21297. state = strm.state;
  21298. strm.total_in = strm.total_out = state.total = 0;
  21299. strm.msg = ''; /*Z_NULL*/
  21300. if (state.wrap) { /* to support ill-conceived Java test suite */
  21301. strm.adler = state.wrap & 1;
  21302. }
  21303. state.mode = HEAD;
  21304. state.last = 0;
  21305. state.havedict = 0;
  21306. state.dmax = 32768;
  21307. state.head = null/*Z_NULL*/;
  21308. state.hold = 0;
  21309. state.bits = 0;
  21310. //state.lencode = state.distcode = state.next = state.codes;
  21311. state.lencode = state.lendyn = new utils.Buf32(ENOUGH_LENS);
  21312. state.distcode = state.distdyn = new utils.Buf32(ENOUGH_DISTS);
  21313. state.sane = 1;
  21314. state.back = -1;
  21315. //Tracev((stderr, "inflate: reset\n"));
  21316. return Z_OK;
  21317. }
  21318. function inflateReset(strm) {
  21319. var state;
  21320. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  21321. state = strm.state;
  21322. state.wsize = 0;
  21323. state.whave = 0;
  21324. state.wnext = 0;
  21325. return inflateResetKeep(strm);
  21326. }
  21327. function inflateReset2(strm, windowBits) {
  21328. var wrap;
  21329. var state;
  21330. /* get the state */
  21331. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  21332. state = strm.state;
  21333. /* extract wrap request from windowBits parameter */
  21334. if (windowBits < 0) {
  21335. wrap = 0;
  21336. windowBits = -windowBits;
  21337. }
  21338. else {
  21339. wrap = (windowBits >> 4) + 1;
  21340. if (windowBits < 48) {
  21341. windowBits &= 15;
  21342. }
  21343. }
  21344. /* set number of window bits, free window if different */
  21345. if (windowBits && (windowBits < 8 || windowBits > 15)) {
  21346. return Z_STREAM_ERROR;
  21347. }
  21348. if (state.window !== null && state.wbits !== windowBits) {
  21349. state.window = null;
  21350. }
  21351. /* update state and reset the rest of it */
  21352. state.wrap = wrap;
  21353. state.wbits = windowBits;
  21354. return inflateReset(strm);
  21355. }
  21356. function inflateInit2(strm, windowBits) {
  21357. var ret;
  21358. var state;
  21359. if (!strm) { return Z_STREAM_ERROR; }
  21360. //strm.msg = Z_NULL; /* in case we return an error */
  21361. state = new InflateState();
  21362. //if (state === Z_NULL) return Z_MEM_ERROR;
  21363. //Tracev((stderr, "inflate: allocated\n"));
  21364. strm.state = state;
  21365. state.window = null/*Z_NULL*/;
  21366. ret = inflateReset2(strm, windowBits);
  21367. if (ret !== Z_OK) {
  21368. strm.state = null/*Z_NULL*/;
  21369. }
  21370. return ret;
  21371. }
  21372. function inflateInit(strm) {
  21373. return inflateInit2(strm, DEF_WBITS);
  21374. }
  21375. /*
  21376. Return state with length and distance decoding tables and index sizes set to
  21377. fixed code decoding. Normally this returns fixed tables from inffixed.h.
  21378. If BUILDFIXED is defined, then instead this routine builds the tables the
  21379. first time it's called, and returns those tables the first time and
  21380. thereafter. This reduces the size of the code by about 2K bytes, in
  21381. exchange for a little execution time. However, BUILDFIXED should not be
  21382. used for threaded applications, since the rewriting of the tables and virgin
  21383. may not be thread-safe.
  21384. */
  21385. var virgin = true;
  21386. var lenfix, distfix; // We have no pointers in JS, so keep tables separate
  21387. function fixedtables(state) {
  21388. /* build fixed huffman tables if first call (may not be thread safe) */
  21389. if (virgin) {
  21390. var sym;
  21391. lenfix = new utils.Buf32(512);
  21392. distfix = new utils.Buf32(32);
  21393. /* literal/length table */
  21394. sym = 0;
  21395. while (sym < 144) { state.lens[sym++] = 8; }
  21396. while (sym < 256) { state.lens[sym++] = 9; }
  21397. while (sym < 280) { state.lens[sym++] = 7; }
  21398. while (sym < 288) { state.lens[sym++] = 8; }
  21399. inflate_table(LENS, state.lens, 0, 288, lenfix, 0, state.work, {bits: 9});
  21400. /* distance table */
  21401. sym = 0;
  21402. while (sym < 32) { state.lens[sym++] = 5; }
  21403. inflate_table(DISTS, state.lens, 0, 32, distfix, 0, state.work, {bits: 5});
  21404. /* do this just once */
  21405. virgin = false;
  21406. }
  21407. state.lencode = lenfix;
  21408. state.lenbits = 9;
  21409. state.distcode = distfix;
  21410. state.distbits = 5;
  21411. }
  21412. /*
  21413. Update the window with the last wsize (normally 32K) bytes written before
  21414. returning. If window does not exist yet, create it. This is only called
  21415. when a window is already in use, or when output has been written during this
  21416. inflate call, but the end of the deflate stream has not been reached yet.
  21417. It is also called to create a window for dictionary data when a dictionary
  21418. is loaded.
  21419. Providing output buffers larger than 32K to inflate() should provide a speed
  21420. advantage, since only the last 32K of output is copied to the sliding window
  21421. upon return from inflate(), and since all distances after the first 32K of
  21422. output will fall in the output data, making match copies simpler and faster.
  21423. The advantage may be dependent on the size of the processor's data caches.
  21424. */
  21425. function updatewindow(strm, src, end, copy) {
  21426. var dist;
  21427. var state = strm.state;
  21428. /* if it hasn't been done already, allocate space for the window */
  21429. if (state.window === null) {
  21430. state.wsize = 1 << state.wbits;
  21431. state.wnext = 0;
  21432. state.whave = 0;
  21433. state.window = new utils.Buf8(state.wsize);
  21434. }
  21435. /* copy state->wsize or less output bytes into the circular window */
  21436. if (copy >= state.wsize) {
  21437. utils.arraySet(state.window,src, end - state.wsize, state.wsize, 0);
  21438. state.wnext = 0;
  21439. state.whave = state.wsize;
  21440. }
  21441. else {
  21442. dist = state.wsize - state.wnext;
  21443. if (dist > copy) {
  21444. dist = copy;
  21445. }
  21446. //zmemcpy(state->window + state->wnext, end - copy, dist);
  21447. utils.arraySet(state.window,src, end - copy, dist, state.wnext);
  21448. copy -= dist;
  21449. if (copy) {
  21450. //zmemcpy(state->window, end - copy, copy);
  21451. utils.arraySet(state.window,src, end - copy, copy, 0);
  21452. state.wnext = copy;
  21453. state.whave = state.wsize;
  21454. }
  21455. else {
  21456. state.wnext += dist;
  21457. if (state.wnext === state.wsize) { state.wnext = 0; }
  21458. if (state.whave < state.wsize) { state.whave += dist; }
  21459. }
  21460. }
  21461. return 0;
  21462. }
  21463. function inflate(strm, flush) {
  21464. var state;
  21465. var input, output; // input/output buffers
  21466. var next; /* next input INDEX */
  21467. var put; /* next output INDEX */
  21468. var have, left; /* available input and output */
  21469. var hold; /* bit buffer */
  21470. var bits; /* bits in bit buffer */
  21471. var _in, _out; /* save starting available input and output */
  21472. var copy; /* number of stored or match bytes to copy */
  21473. var from; /* where to copy match bytes from */
  21474. var from_source;
  21475. var here = 0; /* current decoding table entry */
  21476. var here_bits, here_op, here_val; // paked "here" denormalized (JS specific)
  21477. //var last; /* parent table entry */
  21478. var last_bits, last_op, last_val; // paked "last" denormalized (JS specific)
  21479. var len; /* length to copy for repeats, bits to drop */
  21480. var ret; /* return code */
  21481. var hbuf = new utils.Buf8(4); /* buffer for gzip header crc calculation */
  21482. var opts;
  21483. var n; // temporary var for NEED_BITS
  21484. var order = /* permutation of code lengths */
  21485. [16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15];
  21486. if (!strm || !strm.state || !strm.output ||
  21487. (!strm.input && strm.avail_in !== 0)) {
  21488. return Z_STREAM_ERROR;
  21489. }
  21490. state = strm.state;
  21491. if (state.mode === TYPE) { state.mode = TYPEDO; } /* skip check */
  21492. //--- LOAD() ---
  21493. put = strm.next_out;
  21494. output = strm.output;
  21495. left = strm.avail_out;
  21496. next = strm.next_in;
  21497. input = strm.input;
  21498. have = strm.avail_in;
  21499. hold = state.hold;
  21500. bits = state.bits;
  21501. //---
  21502. _in = have;
  21503. _out = left;
  21504. ret = Z_OK;
  21505. inf_leave: // goto emulation
  21506. for (;;) {
  21507. switch (state.mode) {
  21508. case HEAD:
  21509. if (state.wrap === 0) {
  21510. state.mode = TYPEDO;
  21511. break;
  21512. }
  21513. //=== NEEDBITS(16);
  21514. while (bits < 16) {
  21515. if (have === 0) { break inf_leave; }
  21516. have--;
  21517. hold += input[next++] << bits;
  21518. bits += 8;
  21519. }
  21520. //===//
  21521. if ((state.wrap & 2) && hold === 0x8b1f) { /* gzip header */
  21522. state.check = 0/*crc32(0L, Z_NULL, 0)*/;
  21523. //=== CRC2(state.check, hold);
  21524. hbuf[0] = hold & 0xff;
  21525. hbuf[1] = (hold >>> 8) & 0xff;
  21526. state.check = crc32(state.check, hbuf, 2, 0);
  21527. //===//
  21528. //=== INITBITS();
  21529. hold = 0;
  21530. bits = 0;
  21531. //===//
  21532. state.mode = FLAGS;
  21533. break;
  21534. }
  21535. state.flags = 0; /* expect zlib header */
  21536. if (state.head) {
  21537. state.head.done = false;
  21538. }
  21539. if (!(state.wrap & 1) || /* check if zlib header allowed */
  21540. (((hold & 0xff)/*BITS(8)*/ << 8) + (hold >> 8)) % 31) {
  21541. strm.msg = 'incorrect header check';
  21542. state.mode = BAD;
  21543. break;
  21544. }
  21545. if ((hold & 0x0f)/*BITS(4)*/ !== Z_DEFLATED) {
  21546. strm.msg = 'unknown compression method';
  21547. state.mode = BAD;
  21548. break;
  21549. }
  21550. //--- DROPBITS(4) ---//
  21551. hold >>>= 4;
  21552. bits -= 4;
  21553. //---//
  21554. len = (hold & 0x0f)/*BITS(4)*/ + 8;
  21555. if (state.wbits === 0) {
  21556. state.wbits = len;
  21557. }
  21558. else if (len > state.wbits) {
  21559. strm.msg = 'invalid window size';
  21560. state.mode = BAD;
  21561. break;
  21562. }
  21563. state.dmax = 1 << len;
  21564. //Tracev((stderr, "inflate: zlib header ok\n"));
  21565. strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
  21566. state.mode = hold & 0x200 ? DICTID : TYPE;
  21567. //=== INITBITS();
  21568. hold = 0;
  21569. bits = 0;
  21570. //===//
  21571. break;
  21572. case FLAGS:
  21573. //=== NEEDBITS(16); */
  21574. while (bits < 16) {
  21575. if (have === 0) { break inf_leave; }
  21576. have--;
  21577. hold += input[next++] << bits;
  21578. bits += 8;
  21579. }
  21580. //===//
  21581. state.flags = hold;
  21582. if ((state.flags & 0xff) !== Z_DEFLATED) {
  21583. strm.msg = 'unknown compression method';
  21584. state.mode = BAD;
  21585. break;
  21586. }
  21587. if (state.flags & 0xe000) {
  21588. strm.msg = 'unknown header flags set';
  21589. state.mode = BAD;
  21590. break;
  21591. }
  21592. if (state.head) {
  21593. state.head.text = ((hold >> 8) & 1);
  21594. }
  21595. if (state.flags & 0x0200) {
  21596. //=== CRC2(state.check, hold);
  21597. hbuf[0] = hold & 0xff;
  21598. hbuf[1] = (hold >>> 8) & 0xff;
  21599. state.check = crc32(state.check, hbuf, 2, 0);
  21600. //===//
  21601. }
  21602. //=== INITBITS();
  21603. hold = 0;
  21604. bits = 0;
  21605. //===//
  21606. state.mode = TIME;
  21607. /* falls through */
  21608. case TIME:
  21609. //=== NEEDBITS(32); */
  21610. while (bits < 32) {
  21611. if (have === 0) { break inf_leave; }
  21612. have--;
  21613. hold += input[next++] << bits;
  21614. bits += 8;
  21615. }
  21616. //===//
  21617. if (state.head) {
  21618. state.head.time = hold;
  21619. }
  21620. if (state.flags & 0x0200) {
  21621. //=== CRC4(state.check, hold)
  21622. hbuf[0] = hold & 0xff;
  21623. hbuf[1] = (hold >>> 8) & 0xff;
  21624. hbuf[2] = (hold >>> 16) & 0xff;
  21625. hbuf[3] = (hold >>> 24) & 0xff;
  21626. state.check = crc32(state.check, hbuf, 4, 0);
  21627. //===
  21628. }
  21629. //=== INITBITS();
  21630. hold = 0;
  21631. bits = 0;
  21632. //===//
  21633. state.mode = OS;
  21634. /* falls through */
  21635. case OS:
  21636. //=== NEEDBITS(16); */
  21637. while (bits < 16) {
  21638. if (have === 0) { break inf_leave; }
  21639. have--;
  21640. hold += input[next++] << bits;
  21641. bits += 8;
  21642. }
  21643. //===//
  21644. if (state.head) {
  21645. state.head.xflags = (hold & 0xff);
  21646. state.head.os = (hold >> 8);
  21647. }
  21648. if (state.flags & 0x0200) {
  21649. //=== CRC2(state.check, hold);
  21650. hbuf[0] = hold & 0xff;
  21651. hbuf[1] = (hold >>> 8) & 0xff;
  21652. state.check = crc32(state.check, hbuf, 2, 0);
  21653. //===//
  21654. }
  21655. //=== INITBITS();
  21656. hold = 0;
  21657. bits = 0;
  21658. //===//
  21659. state.mode = EXLEN;
  21660. /* falls through */
  21661. case EXLEN:
  21662. if (state.flags & 0x0400) {
  21663. //=== NEEDBITS(16); */
  21664. while (bits < 16) {
  21665. if (have === 0) { break inf_leave; }
  21666. have--;
  21667. hold += input[next++] << bits;
  21668. bits += 8;
  21669. }
  21670. //===//
  21671. state.length = hold;
  21672. if (state.head) {
  21673. state.head.extra_len = hold;
  21674. }
  21675. if (state.flags & 0x0200) {
  21676. //=== CRC2(state.check, hold);
  21677. hbuf[0] = hold & 0xff;
  21678. hbuf[1] = (hold >>> 8) & 0xff;
  21679. state.check = crc32(state.check, hbuf, 2, 0);
  21680. //===//
  21681. }
  21682. //=== INITBITS();
  21683. hold = 0;
  21684. bits = 0;
  21685. //===//
  21686. }
  21687. else if (state.head) {
  21688. state.head.extra = null/*Z_NULL*/;
  21689. }
  21690. state.mode = EXTRA;
  21691. /* falls through */
  21692. case EXTRA:
  21693. if (state.flags & 0x0400) {
  21694. copy = state.length;
  21695. if (copy > have) { copy = have; }
  21696. if (copy) {
  21697. if (state.head) {
  21698. len = state.head.extra_len - state.length;
  21699. if (!state.head.extra) {
  21700. // Use untyped array for more conveniend processing later
  21701. state.head.extra = new Array(state.head.extra_len);
  21702. }
  21703. utils.arraySet(
  21704. state.head.extra,
  21705. input,
  21706. next,
  21707. // extra field is limited to 65536 bytes
  21708. // - no need for additional size check
  21709. copy,
  21710. /*len + copy > state.head.extra_max - len ? state.head.extra_max : copy,*/
  21711. len
  21712. );
  21713. //zmemcpy(state.head.extra + len, next,
  21714. // len + copy > state.head.extra_max ?
  21715. // state.head.extra_max - len : copy);
  21716. }
  21717. if (state.flags & 0x0200) {
  21718. state.check = crc32(state.check, input, copy, next);
  21719. }
  21720. have -= copy;
  21721. next += copy;
  21722. state.length -= copy;
  21723. }
  21724. if (state.length) { break inf_leave; }
  21725. }
  21726. state.length = 0;
  21727. state.mode = NAME;
  21728. /* falls through */
  21729. case NAME:
  21730. if (state.flags & 0x0800) {
  21731. if (have === 0) { break inf_leave; }
  21732. copy = 0;
  21733. do {
  21734. // TODO: 2 or 1 bytes?
  21735. len = input[next + copy++];
  21736. /* use constant limit because in js we should not preallocate memory */
  21737. if (state.head && len &&
  21738. (state.length < 65536 /*state.head.name_max*/)) {
  21739. state.head.name += String.fromCharCode(len);
  21740. }
  21741. } while (len && copy < have);
  21742. if (state.flags & 0x0200) {
  21743. state.check = crc32(state.check, input, copy, next);
  21744. }
  21745. have -= copy;
  21746. next += copy;
  21747. if (len) { break inf_leave; }
  21748. }
  21749. else if (state.head) {
  21750. state.head.name = null;
  21751. }
  21752. state.length = 0;
  21753. state.mode = COMMENT;
  21754. /* falls through */
  21755. case COMMENT:
  21756. if (state.flags & 0x1000) {
  21757. if (have === 0) { break inf_leave; }
  21758. copy = 0;
  21759. do {
  21760. len = input[next + copy++];
  21761. /* use constant limit because in js we should not preallocate memory */
  21762. if (state.head && len &&
  21763. (state.length < 65536 /*state.head.comm_max*/)) {
  21764. state.head.comment += String.fromCharCode(len);
  21765. }
  21766. } while (len && copy < have);
  21767. if (state.flags & 0x0200) {
  21768. state.check = crc32(state.check, input, copy, next);
  21769. }
  21770. have -= copy;
  21771. next += copy;
  21772. if (len) { break inf_leave; }
  21773. }
  21774. else if (state.head) {
  21775. state.head.comment = null;
  21776. }
  21777. state.mode = HCRC;
  21778. /* falls through */
  21779. case HCRC:
  21780. if (state.flags & 0x0200) {
  21781. //=== NEEDBITS(16); */
  21782. while (bits < 16) {
  21783. if (have === 0) { break inf_leave; }
  21784. have--;
  21785. hold += input[next++] << bits;
  21786. bits += 8;
  21787. }
  21788. //===//
  21789. if (hold !== (state.check & 0xffff)) {
  21790. strm.msg = 'header crc mismatch';
  21791. state.mode = BAD;
  21792. break;
  21793. }
  21794. //=== INITBITS();
  21795. hold = 0;
  21796. bits = 0;
  21797. //===//
  21798. }
  21799. if (state.head) {
  21800. state.head.hcrc = ((state.flags >> 9) & 1);
  21801. state.head.done = true;
  21802. }
  21803. strm.adler = state.check = 0 /*crc32(0L, Z_NULL, 0)*/;
  21804. state.mode = TYPE;
  21805. break;
  21806. case DICTID:
  21807. //=== NEEDBITS(32); */
  21808. while (bits < 32) {
  21809. if (have === 0) { break inf_leave; }
  21810. have--;
  21811. hold += input[next++] << bits;
  21812. bits += 8;
  21813. }
  21814. //===//
  21815. strm.adler = state.check = ZSWAP32(hold);
  21816. //=== INITBITS();
  21817. hold = 0;
  21818. bits = 0;
  21819. //===//
  21820. state.mode = DICT;
  21821. /* falls through */
  21822. case DICT:
  21823. if (state.havedict === 0) {
  21824. //--- RESTORE() ---
  21825. strm.next_out = put;
  21826. strm.avail_out = left;
  21827. strm.next_in = next;
  21828. strm.avail_in = have;
  21829. state.hold = hold;
  21830. state.bits = bits;
  21831. //---
  21832. return Z_NEED_DICT;
  21833. }
  21834. strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
  21835. state.mode = TYPE;
  21836. /* falls through */
  21837. case TYPE:
  21838. if (flush === Z_BLOCK || flush === Z_TREES) { break inf_leave; }
  21839. /* falls through */
  21840. case TYPEDO:
  21841. if (state.last) {
  21842. //--- BYTEBITS() ---//
  21843. hold >>>= bits & 7;
  21844. bits -= bits & 7;
  21845. //---//
  21846. state.mode = CHECK;
  21847. break;
  21848. }
  21849. //=== NEEDBITS(3); */
  21850. while (bits < 3) {
  21851. if (have === 0) { break inf_leave; }
  21852. have--;
  21853. hold += input[next++] << bits;
  21854. bits += 8;
  21855. }
  21856. //===//
  21857. state.last = (hold & 0x01)/*BITS(1)*/;
  21858. //--- DROPBITS(1) ---//
  21859. hold >>>= 1;
  21860. bits -= 1;
  21861. //---//
  21862. switch ((hold & 0x03)/*BITS(2)*/) {
  21863. case 0: /* stored block */
  21864. //Tracev((stderr, "inflate: stored block%s\n",
  21865. // state.last ? " (last)" : ""));
  21866. state.mode = STORED;
  21867. break;
  21868. case 1: /* fixed block */
  21869. fixedtables(state);
  21870. //Tracev((stderr, "inflate: fixed codes block%s\n",
  21871. // state.last ? " (last)" : ""));
  21872. state.mode = LEN_; /* decode codes */
  21873. if (flush === Z_TREES) {
  21874. //--- DROPBITS(2) ---//
  21875. hold >>>= 2;
  21876. bits -= 2;
  21877. //---//
  21878. break inf_leave;
  21879. }
  21880. break;
  21881. case 2: /* dynamic block */
  21882. //Tracev((stderr, "inflate: dynamic codes block%s\n",
  21883. // state.last ? " (last)" : ""));
  21884. state.mode = TABLE;
  21885. break;
  21886. case 3:
  21887. strm.msg = 'invalid block type';
  21888. state.mode = BAD;
  21889. }
  21890. //--- DROPBITS(2) ---//
  21891. hold >>>= 2;
  21892. bits -= 2;
  21893. //---//
  21894. break;
  21895. case STORED:
  21896. //--- BYTEBITS() ---// /* go to byte boundary */
  21897. hold >>>= bits & 7;
  21898. bits -= bits & 7;
  21899. //---//
  21900. //=== NEEDBITS(32); */
  21901. while (bits < 32) {
  21902. if (have === 0) { break inf_leave; }
  21903. have--;
  21904. hold += input[next++] << bits;
  21905. bits += 8;
  21906. }
  21907. //===//
  21908. if ((hold & 0xffff) !== ((hold >>> 16) ^ 0xffff)) {
  21909. strm.msg = 'invalid stored block lengths';
  21910. state.mode = BAD;
  21911. break;
  21912. }
  21913. state.length = hold & 0xffff;
  21914. //Tracev((stderr, "inflate: stored length %u\n",
  21915. // state.length));
  21916. //=== INITBITS();
  21917. hold = 0;
  21918. bits = 0;
  21919. //===//
  21920. state.mode = COPY_;
  21921. if (flush === Z_TREES) { break inf_leave; }
  21922. /* falls through */
  21923. case COPY_:
  21924. state.mode = COPY;
  21925. /* falls through */
  21926. case COPY:
  21927. copy = state.length;
  21928. if (copy) {
  21929. if (copy > have) { copy = have; }
  21930. if (copy > left) { copy = left; }
  21931. if (copy === 0) { break inf_leave; }
  21932. //--- zmemcpy(put, next, copy); ---
  21933. utils.arraySet(output, input, next, copy, put);
  21934. //---//
  21935. have -= copy;
  21936. next += copy;
  21937. left -= copy;
  21938. put += copy;
  21939. state.length -= copy;
  21940. break;
  21941. }
  21942. //Tracev((stderr, "inflate: stored end\n"));
  21943. state.mode = TYPE;
  21944. break;
  21945. case TABLE:
  21946. //=== NEEDBITS(14); */
  21947. while (bits < 14) {
  21948. if (have === 0) { break inf_leave; }
  21949. have--;
  21950. hold += input[next++] << bits;
  21951. bits += 8;
  21952. }
  21953. //===//
  21954. state.nlen = (hold & 0x1f)/*BITS(5)*/ + 257;
  21955. //--- DROPBITS(5) ---//
  21956. hold >>>= 5;
  21957. bits -= 5;
  21958. //---//
  21959. state.ndist = (hold & 0x1f)/*BITS(5)*/ + 1;
  21960. //--- DROPBITS(5) ---//
  21961. hold >>>= 5;
  21962. bits -= 5;
  21963. //---//
  21964. state.ncode = (hold & 0x0f)/*BITS(4)*/ + 4;
  21965. //--- DROPBITS(4) ---//
  21966. hold >>>= 4;
  21967. bits -= 4;
  21968. //---//
  21969. //#ifndef PKZIP_BUG_WORKAROUND
  21970. if (state.nlen > 286 || state.ndist > 30) {
  21971. strm.msg = 'too many length or distance symbols';
  21972. state.mode = BAD;
  21973. break;
  21974. }
  21975. //#endif
  21976. //Tracev((stderr, "inflate: table sizes ok\n"));
  21977. state.have = 0;
  21978. state.mode = LENLENS;
  21979. /* falls through */
  21980. case LENLENS:
  21981. while (state.have < state.ncode) {
  21982. //=== NEEDBITS(3);
  21983. while (bits < 3) {
  21984. if (have === 0) { break inf_leave; }
  21985. have--;
  21986. hold += input[next++] << bits;
  21987. bits += 8;
  21988. }
  21989. //===//
  21990. state.lens[order[state.have++]] = (hold & 0x07);//BITS(3);
  21991. //--- DROPBITS(3) ---//
  21992. hold >>>= 3;
  21993. bits -= 3;
  21994. //---//
  21995. }
  21996. while (state.have < 19) {
  21997. state.lens[order[state.have++]] = 0;
  21998. }
  21999. // We have separate tables & no pointers. 2 commented lines below not needed.
  22000. //state.next = state.codes;
  22001. //state.lencode = state.next;
  22002. // Switch to use dynamic table
  22003. state.lencode = state.lendyn;
  22004. state.lenbits = 7;
  22005. opts = {bits: state.lenbits};
  22006. ret = inflate_table(CODES, state.lens, 0, 19, state.lencode, 0, state.work, opts);
  22007. state.lenbits = opts.bits;
  22008. if (ret) {
  22009. strm.msg = 'invalid code lengths set';
  22010. state.mode = BAD;
  22011. break;
  22012. }
  22013. //Tracev((stderr, "inflate: code lengths ok\n"));
  22014. state.have = 0;
  22015. state.mode = CODELENS;
  22016. /* falls through */
  22017. case CODELENS:
  22018. while (state.have < state.nlen + state.ndist) {
  22019. for (;;) {
  22020. here = state.lencode[hold & ((1 << state.lenbits) - 1)];/*BITS(state.lenbits)*/
  22021. here_bits = here >>> 24;
  22022. here_op = (here >>> 16) & 0xff;
  22023. here_val = here & 0xffff;
  22024. if ((here_bits) <= bits) { break; }
  22025. //--- PULLBYTE() ---//
  22026. if (have === 0) { break inf_leave; }
  22027. have--;
  22028. hold += input[next++] << bits;
  22029. bits += 8;
  22030. //---//
  22031. }
  22032. if (here_val < 16) {
  22033. //--- DROPBITS(here.bits) ---//
  22034. hold >>>= here_bits;
  22035. bits -= here_bits;
  22036. //---//
  22037. state.lens[state.have++] = here_val;
  22038. }
  22039. else {
  22040. if (here_val === 16) {
  22041. //=== NEEDBITS(here.bits + 2);
  22042. n = here_bits + 2;
  22043. while (bits < n) {
  22044. if (have === 0) { break inf_leave; }
  22045. have--;
  22046. hold += input[next++] << bits;
  22047. bits += 8;
  22048. }
  22049. //===//
  22050. //--- DROPBITS(here.bits) ---//
  22051. hold >>>= here_bits;
  22052. bits -= here_bits;
  22053. //---//
  22054. if (state.have === 0) {
  22055. strm.msg = 'invalid bit length repeat';
  22056. state.mode = BAD;
  22057. break;
  22058. }
  22059. len = state.lens[state.have - 1];
  22060. copy = 3 + (hold & 0x03);//BITS(2);
  22061. //--- DROPBITS(2) ---//
  22062. hold >>>= 2;
  22063. bits -= 2;
  22064. //---//
  22065. }
  22066. else if (here_val === 17) {
  22067. //=== NEEDBITS(here.bits + 3);
  22068. n = here_bits + 3;
  22069. while (bits < n) {
  22070. if (have === 0) { break inf_leave; }
  22071. have--;
  22072. hold += input[next++] << bits;
  22073. bits += 8;
  22074. }
  22075. //===//
  22076. //--- DROPBITS(here.bits) ---//
  22077. hold >>>= here_bits;
  22078. bits -= here_bits;
  22079. //---//
  22080. len = 0;
  22081. copy = 3 + (hold & 0x07);//BITS(3);
  22082. //--- DROPBITS(3) ---//
  22083. hold >>>= 3;
  22084. bits -= 3;
  22085. //---//
  22086. }
  22087. else {
  22088. //=== NEEDBITS(here.bits + 7);
  22089. n = here_bits + 7;
  22090. while (bits < n) {
  22091. if (have === 0) { break inf_leave; }
  22092. have--;
  22093. hold += input[next++] << bits;
  22094. bits += 8;
  22095. }
  22096. //===//
  22097. //--- DROPBITS(here.bits) ---//
  22098. hold >>>= here_bits;
  22099. bits -= here_bits;
  22100. //---//
  22101. len = 0;
  22102. copy = 11 + (hold & 0x7f);//BITS(7);
  22103. //--- DROPBITS(7) ---//
  22104. hold >>>= 7;
  22105. bits -= 7;
  22106. //---//
  22107. }
  22108. if (state.have + copy > state.nlen + state.ndist) {
  22109. strm.msg = 'invalid bit length repeat';
  22110. state.mode = BAD;
  22111. break;
  22112. }
  22113. while (copy--) {
  22114. state.lens[state.have++] = len;
  22115. }
  22116. }
  22117. }
  22118. /* handle error breaks in while */
  22119. if (state.mode === BAD) { break; }
  22120. /* check for end-of-block code (better have one) */
  22121. if (state.lens[256] === 0) {
  22122. strm.msg = 'invalid code -- missing end-of-block';
  22123. state.mode = BAD;
  22124. break;
  22125. }
  22126. /* build code tables -- note: do not change the lenbits or distbits
  22127. values here (9 and 6) without reading the comments in inftrees.h
  22128. concerning the ENOUGH constants, which depend on those values */
  22129. state.lenbits = 9;
  22130. opts = {bits: state.lenbits};
  22131. ret = inflate_table(LENS, state.lens, 0, state.nlen, state.lencode, 0, state.work, opts);
  22132. // We have separate tables & no pointers. 2 commented lines below not needed.
  22133. // state.next_index = opts.table_index;
  22134. state.lenbits = opts.bits;
  22135. // state.lencode = state.next;
  22136. if (ret) {
  22137. strm.msg = 'invalid literal/lengths set';
  22138. state.mode = BAD;
  22139. break;
  22140. }
  22141. state.distbits = 6;
  22142. //state.distcode.copy(state.codes);
  22143. // Switch to use dynamic table
  22144. state.distcode = state.distdyn;
  22145. opts = {bits: state.distbits};
  22146. ret = inflate_table(DISTS, state.lens, state.nlen, state.ndist, state.distcode, 0, state.work, opts);
  22147. // We have separate tables & no pointers. 2 commented lines below not needed.
  22148. // state.next_index = opts.table_index;
  22149. state.distbits = opts.bits;
  22150. // state.distcode = state.next;
  22151. if (ret) {
  22152. strm.msg = 'invalid distances set';
  22153. state.mode = BAD;
  22154. break;
  22155. }
  22156. //Tracev((stderr, 'inflate: codes ok\n'));
  22157. state.mode = LEN_;
  22158. if (flush === Z_TREES) { break inf_leave; }
  22159. /* falls through */
  22160. case LEN_:
  22161. state.mode = LEN;
  22162. /* falls through */
  22163. case LEN:
  22164. if (have >= 6 && left >= 258) {
  22165. //--- RESTORE() ---
  22166. strm.next_out = put;
  22167. strm.avail_out = left;
  22168. strm.next_in = next;
  22169. strm.avail_in = have;
  22170. state.hold = hold;
  22171. state.bits = bits;
  22172. //---
  22173. inflate_fast(strm, _out);
  22174. //--- LOAD() ---
  22175. put = strm.next_out;
  22176. output = strm.output;
  22177. left = strm.avail_out;
  22178. next = strm.next_in;
  22179. input = strm.input;
  22180. have = strm.avail_in;
  22181. hold = state.hold;
  22182. bits = state.bits;
  22183. //---
  22184. if (state.mode === TYPE) {
  22185. state.back = -1;
  22186. }
  22187. break;
  22188. }
  22189. state.back = 0;
  22190. for (;;) {
  22191. here = state.lencode[hold & ((1 << state.lenbits) -1)]; /*BITS(state.lenbits)*/
  22192. here_bits = here >>> 24;
  22193. here_op = (here >>> 16) & 0xff;
  22194. here_val = here & 0xffff;
  22195. if (here_bits <= bits) { break; }
  22196. //--- PULLBYTE() ---//
  22197. if (have === 0) { break inf_leave; }
  22198. have--;
  22199. hold += input[next++] << bits;
  22200. bits += 8;
  22201. //---//
  22202. }
  22203. if (here_op && (here_op & 0xf0) === 0) {
  22204. last_bits = here_bits;
  22205. last_op = here_op;
  22206. last_val = here_val;
  22207. for (;;) {
  22208. here = state.lencode[last_val +
  22209. ((hold & ((1 << (last_bits + last_op)) -1))/*BITS(last.bits + last.op)*/ >> last_bits)];
  22210. here_bits = here >>> 24;
  22211. here_op = (here >>> 16) & 0xff;
  22212. here_val = here & 0xffff;
  22213. if ((last_bits + here_bits) <= bits) { break; }
  22214. //--- PULLBYTE() ---//
  22215. if (have === 0) { break inf_leave; }
  22216. have--;
  22217. hold += input[next++] << bits;
  22218. bits += 8;
  22219. //---//
  22220. }
  22221. //--- DROPBITS(last.bits) ---//
  22222. hold >>>= last_bits;
  22223. bits -= last_bits;
  22224. //---//
  22225. state.back += last_bits;
  22226. }
  22227. //--- DROPBITS(here.bits) ---//
  22228. hold >>>= here_bits;
  22229. bits -= here_bits;
  22230. //---//
  22231. state.back += here_bits;
  22232. state.length = here_val;
  22233. if (here_op === 0) {
  22234. //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
  22235. // "inflate: literal '%c'\n" :
  22236. // "inflate: literal 0x%02x\n", here.val));
  22237. state.mode = LIT;
  22238. break;
  22239. }
  22240. if (here_op & 32) {
  22241. //Tracevv((stderr, "inflate: end of block\n"));
  22242. state.back = -1;
  22243. state.mode = TYPE;
  22244. break;
  22245. }
  22246. if (here_op & 64) {
  22247. strm.msg = 'invalid literal/length code';
  22248. state.mode = BAD;
  22249. break;
  22250. }
  22251. state.extra = here_op & 15;
  22252. state.mode = LENEXT;
  22253. /* falls through */
  22254. case LENEXT:
  22255. if (state.extra) {
  22256. //=== NEEDBITS(state.extra);
  22257. n = state.extra;
  22258. while (bits < n) {
  22259. if (have === 0) { break inf_leave; }
  22260. have--;
  22261. hold += input[next++] << bits;
  22262. bits += 8;
  22263. }
  22264. //===//
  22265. state.length += hold & ((1 << state.extra) -1)/*BITS(state.extra)*/;
  22266. //--- DROPBITS(state.extra) ---//
  22267. hold >>>= state.extra;
  22268. bits -= state.extra;
  22269. //---//
  22270. state.back += state.extra;
  22271. }
  22272. //Tracevv((stderr, "inflate: length %u\n", state.length));
  22273. state.was = state.length;
  22274. state.mode = DIST;
  22275. /* falls through */
  22276. case DIST:
  22277. for (;;) {
  22278. here = state.distcode[hold & ((1 << state.distbits) -1)];/*BITS(state.distbits)*/
  22279. here_bits = here >>> 24;
  22280. here_op = (here >>> 16) & 0xff;
  22281. here_val = here & 0xffff;
  22282. if ((here_bits) <= bits) { break; }
  22283. //--- PULLBYTE() ---//
  22284. if (have === 0) { break inf_leave; }
  22285. have--;
  22286. hold += input[next++] << bits;
  22287. bits += 8;
  22288. //---//
  22289. }
  22290. if ((here_op & 0xf0) === 0) {
  22291. last_bits = here_bits;
  22292. last_op = here_op;
  22293. last_val = here_val;
  22294. for (;;) {
  22295. here = state.distcode[last_val +
  22296. ((hold & ((1 << (last_bits + last_op)) -1))/*BITS(last.bits + last.op)*/ >> last_bits)];
  22297. here_bits = here >>> 24;
  22298. here_op = (here >>> 16) & 0xff;
  22299. here_val = here & 0xffff;
  22300. if ((last_bits + here_bits) <= bits) { break; }
  22301. //--- PULLBYTE() ---//
  22302. if (have === 0) { break inf_leave; }
  22303. have--;
  22304. hold += input[next++] << bits;
  22305. bits += 8;
  22306. //---//
  22307. }
  22308. //--- DROPBITS(last.bits) ---//
  22309. hold >>>= last_bits;
  22310. bits -= last_bits;
  22311. //---//
  22312. state.back += last_bits;
  22313. }
  22314. //--- DROPBITS(here.bits) ---//
  22315. hold >>>= here_bits;
  22316. bits -= here_bits;
  22317. //---//
  22318. state.back += here_bits;
  22319. if (here_op & 64) {
  22320. strm.msg = 'invalid distance code';
  22321. state.mode = BAD;
  22322. break;
  22323. }
  22324. state.offset = here_val;
  22325. state.extra = (here_op) & 15;
  22326. state.mode = DISTEXT;
  22327. /* falls through */
  22328. case DISTEXT:
  22329. if (state.extra) {
  22330. //=== NEEDBITS(state.extra);
  22331. n = state.extra;
  22332. while (bits < n) {
  22333. if (have === 0) { break inf_leave; }
  22334. have--;
  22335. hold += input[next++] << bits;
  22336. bits += 8;
  22337. }
  22338. //===//
  22339. state.offset += hold & ((1 << state.extra) -1)/*BITS(state.extra)*/;
  22340. //--- DROPBITS(state.extra) ---//
  22341. hold >>>= state.extra;
  22342. bits -= state.extra;
  22343. //---//
  22344. state.back += state.extra;
  22345. }
  22346. //#ifdef INFLATE_STRICT
  22347. if (state.offset > state.dmax) {
  22348. strm.msg = 'invalid distance too far back';
  22349. state.mode = BAD;
  22350. break;
  22351. }
  22352. //#endif
  22353. //Tracevv((stderr, "inflate: distance %u\n", state.offset));
  22354. state.mode = MATCH;
  22355. /* falls through */
  22356. case MATCH:
  22357. if (left === 0) { break inf_leave; }
  22358. copy = _out - left;
  22359. if (state.offset > copy) { /* copy from window */
  22360. copy = state.offset - copy;
  22361. if (copy > state.whave) {
  22362. if (state.sane) {
  22363. strm.msg = 'invalid distance too far back';
  22364. state.mode = BAD;
  22365. break;
  22366. }
  22367. // (!) This block is disabled in zlib defailts,
  22368. // don't enable it for binary compatibility
  22369. //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
  22370. // Trace((stderr, "inflate.c too far\n"));
  22371. // copy -= state.whave;
  22372. // if (copy > state.length) { copy = state.length; }
  22373. // if (copy > left) { copy = left; }
  22374. // left -= copy;
  22375. // state.length -= copy;
  22376. // do {
  22377. // output[put++] = 0;
  22378. // } while (--copy);
  22379. // if (state.length === 0) { state.mode = LEN; }
  22380. // break;
  22381. //#endif
  22382. }
  22383. if (copy > state.wnext) {
  22384. copy -= state.wnext;
  22385. from = state.wsize - copy;
  22386. }
  22387. else {
  22388. from = state.wnext - copy;
  22389. }
  22390. if (copy > state.length) { copy = state.length; }
  22391. from_source = state.window;
  22392. }
  22393. else { /* copy from output */
  22394. from_source = output;
  22395. from = put - state.offset;
  22396. copy = state.length;
  22397. }
  22398. if (copy > left) { copy = left; }
  22399. left -= copy;
  22400. state.length -= copy;
  22401. do {
  22402. output[put++] = from_source[from++];
  22403. } while (--copy);
  22404. if (state.length === 0) { state.mode = LEN; }
  22405. break;
  22406. case LIT:
  22407. if (left === 0) { break inf_leave; }
  22408. output[put++] = state.length;
  22409. left--;
  22410. state.mode = LEN;
  22411. break;
  22412. case CHECK:
  22413. if (state.wrap) {
  22414. //=== NEEDBITS(32);
  22415. while (bits < 32) {
  22416. if (have === 0) { break inf_leave; }
  22417. have--;
  22418. // Use '|' insdead of '+' to make sure that result is signed
  22419. hold |= input[next++] << bits;
  22420. bits += 8;
  22421. }
  22422. //===//
  22423. _out -= left;
  22424. strm.total_out += _out;
  22425. state.total += _out;
  22426. if (_out) {
  22427. strm.adler = state.check =
  22428. /*UPDATE(state.check, put - _out, _out);*/
  22429. (state.flags ? crc32(state.check, output, _out, put - _out) : adler32(state.check, output, _out, put - _out));
  22430. }
  22431. _out = left;
  22432. // NB: crc32 stored as signed 32-bit int, ZSWAP32 returns signed too
  22433. if ((state.flags ? hold : ZSWAP32(hold)) !== state.check) {
  22434. strm.msg = 'incorrect data check';
  22435. state.mode = BAD;
  22436. break;
  22437. }
  22438. //=== INITBITS();
  22439. hold = 0;
  22440. bits = 0;
  22441. //===//
  22442. //Tracev((stderr, "inflate: check matches trailer\n"));
  22443. }
  22444. state.mode = LENGTH;
  22445. /* falls through */
  22446. case LENGTH:
  22447. if (state.wrap && state.flags) {
  22448. //=== NEEDBITS(32);
  22449. while (bits < 32) {
  22450. if (have === 0) { break inf_leave; }
  22451. have--;
  22452. hold += input[next++] << bits;
  22453. bits += 8;
  22454. }
  22455. //===//
  22456. if (hold !== (state.total & 0xffffffff)) {
  22457. strm.msg = 'incorrect length check';
  22458. state.mode = BAD;
  22459. break;
  22460. }
  22461. //=== INITBITS();
  22462. hold = 0;
  22463. bits = 0;
  22464. //===//
  22465. //Tracev((stderr, "inflate: length matches trailer\n"));
  22466. }
  22467. state.mode = DONE;
  22468. /* falls through */
  22469. case DONE:
  22470. ret = Z_STREAM_END;
  22471. break inf_leave;
  22472. case BAD:
  22473. ret = Z_DATA_ERROR;
  22474. break inf_leave;
  22475. case MEM:
  22476. return Z_MEM_ERROR;
  22477. case SYNC:
  22478. /* falls through */
  22479. default:
  22480. return Z_STREAM_ERROR;
  22481. }
  22482. }
  22483. // inf_leave <- here is real place for "goto inf_leave", emulated via "break inf_leave"
  22484. /*
  22485. Return from inflate(), updating the total counts and the check value.
  22486. If there was no progress during the inflate() call, return a buffer
  22487. error. Call updatewindow() to create and/or update the window state.
  22488. Note: a memory error from inflate() is non-recoverable.
  22489. */
  22490. //--- RESTORE() ---
  22491. strm.next_out = put;
  22492. strm.avail_out = left;
  22493. strm.next_in = next;
  22494. strm.avail_in = have;
  22495. state.hold = hold;
  22496. state.bits = bits;
  22497. //---
  22498. if (state.wsize || (_out !== strm.avail_out && state.mode < BAD &&
  22499. (state.mode < CHECK || flush !== Z_FINISH))) {
  22500. if (updatewindow(strm, strm.output, strm.next_out, _out - strm.avail_out)) {
  22501. state.mode = MEM;
  22502. return Z_MEM_ERROR;
  22503. }
  22504. }
  22505. _in -= strm.avail_in;
  22506. _out -= strm.avail_out;
  22507. strm.total_in += _in;
  22508. strm.total_out += _out;
  22509. state.total += _out;
  22510. if (state.wrap && _out) {
  22511. strm.adler = state.check = /*UPDATE(state.check, strm.next_out - _out, _out);*/
  22512. (state.flags ? crc32(state.check, output, _out, strm.next_out - _out) : adler32(state.check, output, _out, strm.next_out - _out));
  22513. }
  22514. strm.data_type = state.bits + (state.last ? 64 : 0) +
  22515. (state.mode === TYPE ? 128 : 0) +
  22516. (state.mode === LEN_ || state.mode === COPY_ ? 256 : 0);
  22517. if (((_in === 0 && _out === 0) || flush === Z_FINISH) && ret === Z_OK) {
  22518. ret = Z_BUF_ERROR;
  22519. }
  22520. return ret;
  22521. }
  22522. function inflateEnd(strm) {
  22523. if (!strm || !strm.state /*|| strm->zfree == (free_func)0*/) {
  22524. return Z_STREAM_ERROR;
  22525. }
  22526. var state = strm.state;
  22527. if (state.window) {
  22528. state.window = null;
  22529. }
  22530. strm.state = null;
  22531. return Z_OK;
  22532. }
  22533. function inflateGetHeader(strm, head) {
  22534. var state;
  22535. /* check state */
  22536. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  22537. state = strm.state;
  22538. if ((state.wrap & 2) === 0) { return Z_STREAM_ERROR; }
  22539. /* save header structure */
  22540. state.head = head;
  22541. head.done = false;
  22542. return Z_OK;
  22543. }
  22544. exports.inflateReset = inflateReset;
  22545. exports.inflateReset2 = inflateReset2;
  22546. exports.inflateResetKeep = inflateResetKeep;
  22547. exports.inflateInit = inflateInit;
  22548. exports.inflateInit2 = inflateInit2;
  22549. exports.inflate = inflate;
  22550. exports.inflateEnd = inflateEnd;
  22551. exports.inflateGetHeader = inflateGetHeader;
  22552. exports.inflateInfo = 'pako inflate (from Nodeca project)';
  22553. /* Not implemented
  22554. exports.inflateCopy = inflateCopy;
  22555. exports.inflateGetDictionary = inflateGetDictionary;
  22556. exports.inflateMark = inflateMark;
  22557. exports.inflatePrime = inflatePrime;
  22558. exports.inflateSetDictionary = inflateSetDictionary;
  22559. exports.inflateSync = inflateSync;
  22560. exports.inflateSyncPoint = inflateSyncPoint;
  22561. exports.inflateUndermine = inflateUndermine;
  22562. */
  22563. },{"../utils/common":69,"./adler32":71,"./crc32":73,"./inffast":76,"./inftrees":78}],78:[function(require,module,exports){
  22564. 'use strict';
  22565. var utils = require('../utils/common');
  22566. var MAXBITS = 15;
  22567. var ENOUGH_LENS = 852;
  22568. var ENOUGH_DISTS = 592;
  22569. //var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
  22570. var CODES = 0;
  22571. var LENS = 1;
  22572. var DISTS = 2;
  22573. var lbase = [ /* Length codes 257..285 base */
  22574. 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
  22575. 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0
  22576. ];
  22577. var lext = [ /* Length codes 257..285 extra */
  22578. 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,
  22579. 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 72, 78
  22580. ];
  22581. var dbase = [ /* Distance codes 0..29 base */
  22582. 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
  22583. 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
  22584. 8193, 12289, 16385, 24577, 0, 0
  22585. ];
  22586. var dext = [ /* Distance codes 0..29 extra */
  22587. 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,
  22588. 23, 23, 24, 24, 25, 25, 26, 26, 27, 27,
  22589. 28, 28, 29, 29, 64, 64
  22590. ];
  22591. module.exports = function inflate_table(type, lens, lens_index, codes, table, table_index, work, opts)
  22592. {
  22593. var bits = opts.bits;
  22594. //here = opts.here; /* table entry for duplication */
  22595. var len = 0; /* a code's length in bits */
  22596. var sym = 0; /* index of code symbols */
  22597. var min = 0, max = 0; /* minimum and maximum code lengths */
  22598. var root = 0; /* number of index bits for root table */
  22599. var curr = 0; /* number of index bits for current table */
  22600. var drop = 0; /* code bits to drop for sub-table */
  22601. var left = 0; /* number of prefix codes available */
  22602. var used = 0; /* code entries in table used */
  22603. var huff = 0; /* Huffman code */
  22604. var incr; /* for incrementing code, index */
  22605. var fill; /* index for replicating entries */
  22606. var low; /* low bits for current root entry */
  22607. var mask; /* mask for low root bits */
  22608. var next; /* next available space in table */
  22609. var base = null; /* base value table to use */
  22610. var base_index = 0;
  22611. // var shoextra; /* extra bits table to use */
  22612. var end; /* use base and extra for symbol > end */
  22613. var count = new utils.Buf16(MAXBITS+1); //[MAXBITS+1]; /* number of codes of each length */
  22614. var offs = new utils.Buf16(MAXBITS+1); //[MAXBITS+1]; /* offsets in table for each length */
  22615. var extra = null;
  22616. var extra_index = 0;
  22617. var here_bits, here_op, here_val;
  22618. /*
  22619. Process a set of code lengths to create a canonical Huffman code. The
  22620. code lengths are lens[0..codes-1]. Each length corresponds to the
  22621. symbols 0..codes-1. The Huffman code is generated by first sorting the
  22622. symbols by length from short to long, and retaining the symbol order
  22623. for codes with equal lengths. Then the code starts with all zero bits
  22624. for the first code of the shortest length, and the codes are integer
  22625. increments for the same length, and zeros are appended as the length
  22626. increases. For the deflate format, these bits are stored backwards
  22627. from their more natural integer increment ordering, and so when the
  22628. decoding tables are built in the large loop below, the integer codes
  22629. are incremented backwards.
  22630. This routine assumes, but does not check, that all of the entries in
  22631. lens[] are in the range 0..MAXBITS. The caller must assure this.
  22632. 1..MAXBITS is interpreted as that code length. zero means that that
  22633. symbol does not occur in this code.
  22634. The codes are sorted by computing a count of codes for each length,
  22635. creating from that a table of starting indices for each length in the
  22636. sorted table, and then entering the symbols in order in the sorted
  22637. table. The sorted table is work[], with that space being provided by
  22638. the caller.
  22639. The length counts are used for other purposes as well, i.e. finding
  22640. the minimum and maximum length codes, determining if there are any
  22641. codes at all, checking for a valid set of lengths, and looking ahead
  22642. at length counts to determine sub-table sizes when building the
  22643. decoding tables.
  22644. */
  22645. /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */
  22646. for (len = 0; len <= MAXBITS; len++) {
  22647. count[len] = 0;
  22648. }
  22649. for (sym = 0; sym < codes; sym++) {
  22650. count[lens[lens_index + sym]]++;
  22651. }
  22652. /* bound code lengths, force root to be within code lengths */
  22653. root = bits;
  22654. for (max = MAXBITS; max >= 1; max--) {
  22655. if (count[max] !== 0) { break; }
  22656. }
  22657. if (root > max) {
  22658. root = max;
  22659. }
  22660. if (max === 0) { /* no symbols to code at all */
  22661. //table.op[opts.table_index] = 64; //here.op = (var char)64; /* invalid code marker */
  22662. //table.bits[opts.table_index] = 1; //here.bits = (var char)1;
  22663. //table.val[opts.table_index++] = 0; //here.val = (var short)0;
  22664. table[table_index++] = (1 << 24) | (64 << 16) | 0;
  22665. //table.op[opts.table_index] = 64;
  22666. //table.bits[opts.table_index] = 1;
  22667. //table.val[opts.table_index++] = 0;
  22668. table[table_index++] = (1 << 24) | (64 << 16) | 0;
  22669. opts.bits = 1;
  22670. return 0; /* no symbols, but wait for decoding to report error */
  22671. }
  22672. for (min = 1; min < max; min++) {
  22673. if (count[min] !== 0) { break; }
  22674. }
  22675. if (root < min) {
  22676. root = min;
  22677. }
  22678. /* check for an over-subscribed or incomplete set of lengths */
  22679. left = 1;
  22680. for (len = 1; len <= MAXBITS; len++) {
  22681. left <<= 1;
  22682. left -= count[len];
  22683. if (left < 0) {
  22684. return -1;
  22685. } /* over-subscribed */
  22686. }
  22687. if (left > 0 && (type === CODES || max !== 1)) {
  22688. return -1; /* incomplete set */
  22689. }
  22690. /* generate offsets into symbol table for each length for sorting */
  22691. offs[1] = 0;
  22692. for (len = 1; len < MAXBITS; len++) {
  22693. offs[len + 1] = offs[len] + count[len];
  22694. }
  22695. /* sort symbols by length, by symbol order within each length */
  22696. for (sym = 0; sym < codes; sym++) {
  22697. if (lens[lens_index + sym] !== 0) {
  22698. work[offs[lens[lens_index + sym]]++] = sym;
  22699. }
  22700. }
  22701. /*
  22702. Create and fill in decoding tables. In this loop, the table being
  22703. filled is at next and has curr index bits. The code being used is huff
  22704. with length len. That code is converted to an index by dropping drop
  22705. bits off of the bottom. For codes where len is less than drop + curr,
  22706. those top drop + curr - len bits are incremented through all values to
  22707. fill the table with replicated entries.
  22708. root is the number of index bits for the root table. When len exceeds
  22709. root, sub-tables are created pointed to by the root entry with an index
  22710. of the low root bits of huff. This is saved in low to check for when a
  22711. new sub-table should be started. drop is zero when the root table is
  22712. being filled, and drop is root when sub-tables are being filled.
  22713. When a new sub-table is needed, it is necessary to look ahead in the
  22714. code lengths to determine what size sub-table is needed. The length
  22715. counts are used for this, and so count[] is decremented as codes are
  22716. entered in the tables.
  22717. used keeps track of how many table entries have been allocated from the
  22718. provided *table space. It is checked for LENS and DIST tables against
  22719. the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in
  22720. the initial root table size constants. See the comments in inftrees.h
  22721. for more information.
  22722. sym increments through all symbols, and the loop terminates when
  22723. all codes of length max, i.e. all codes, have been processed. This
  22724. routine permits incomplete codes, so another loop after this one fills
  22725. in the rest of the decoding tables with invalid code markers.
  22726. */
  22727. /* set up for code type */
  22728. // poor man optimization - use if-else instead of switch,
  22729. // to avoid deopts in old v8
  22730. if (type === CODES) {
  22731. base = extra = work; /* dummy value--not used */
  22732. end = 19;
  22733. } else if (type === LENS) {
  22734. base = lbase;
  22735. base_index -= 257;
  22736. extra = lext;
  22737. extra_index -= 257;
  22738. end = 256;
  22739. } else { /* DISTS */
  22740. base = dbase;
  22741. extra = dext;
  22742. end = -1;
  22743. }
  22744. /* initialize opts for loop */
  22745. huff = 0; /* starting code */
  22746. sym = 0; /* starting code symbol */
  22747. len = min; /* starting code length */
  22748. next = table_index; /* current table to fill in */
  22749. curr = root; /* current table index bits */
  22750. drop = 0; /* current bits to drop from code for index */
  22751. low = -1; /* trigger new sub-table when len > root */
  22752. used = 1 << root; /* use root table entries */
  22753. mask = used - 1; /* mask for comparing low */
  22754. /* check available table space */
  22755. if ((type === LENS && used > ENOUGH_LENS) ||
  22756. (type === DISTS && used > ENOUGH_DISTS)) {
  22757. return 1;
  22758. }
  22759. var i=0;
  22760. /* process all codes and make table entries */
  22761. for (;;) {
  22762. i++;
  22763. /* create table entry */
  22764. here_bits = len - drop;
  22765. if (work[sym] < end) {
  22766. here_op = 0;
  22767. here_val = work[sym];
  22768. }
  22769. else if (work[sym] > end) {
  22770. here_op = extra[extra_index + work[sym]];
  22771. here_val = base[base_index + work[sym]];
  22772. }
  22773. else {
  22774. here_op = 32 + 64; /* end of block */
  22775. here_val = 0;
  22776. }
  22777. /* replicate for those indices with low len bits equal to huff */
  22778. incr = 1 << (len - drop);
  22779. fill = 1 << curr;
  22780. min = fill; /* save offset to next table */
  22781. do {
  22782. fill -= incr;
  22783. table[next + (huff >> drop) + fill] = (here_bits << 24) | (here_op << 16) | here_val |0;
  22784. } while (fill !== 0);
  22785. /* backwards increment the len-bit code huff */
  22786. incr = 1 << (len - 1);
  22787. while (huff & incr) {
  22788. incr >>= 1;
  22789. }
  22790. if (incr !== 0) {
  22791. huff &= incr - 1;
  22792. huff += incr;
  22793. } else {
  22794. huff = 0;
  22795. }
  22796. /* go to next symbol, update count, len */
  22797. sym++;
  22798. if (--count[len] === 0) {
  22799. if (len === max) { break; }
  22800. len = lens[lens_index + work[sym]];
  22801. }
  22802. /* create new sub-table if needed */
  22803. if (len > root && (huff & mask) !== low) {
  22804. /* if first time, transition to sub-tables */
  22805. if (drop === 0) {
  22806. drop = root;
  22807. }
  22808. /* increment past last table */
  22809. next += min; /* here min is 1 << curr */
  22810. /* determine length of next table */
  22811. curr = len - drop;
  22812. left = 1 << curr;
  22813. while (curr + drop < max) {
  22814. left -= count[curr + drop];
  22815. if (left <= 0) { break; }
  22816. curr++;
  22817. left <<= 1;
  22818. }
  22819. /* check for enough space */
  22820. used += 1 << curr;
  22821. if ((type === LENS && used > ENOUGH_LENS) ||
  22822. (type === DISTS && used > ENOUGH_DISTS)) {
  22823. return 1;
  22824. }
  22825. /* point entry in root table to sub-table */
  22826. low = huff & mask;
  22827. /*table.op[low] = curr;
  22828. table.bits[low] = root;
  22829. table.val[low] = next - opts.table_index;*/
  22830. table[low] = (root << 24) | (curr << 16) | (next - table_index) |0;
  22831. }
  22832. }
  22833. /* fill in remaining table entry if code is incomplete (guaranteed to have
  22834. at most one remaining entry, since if the code is incomplete, the
  22835. maximum code length that was allowed to get this far is one bit) */
  22836. if (huff !== 0) {
  22837. //table.op[next + huff] = 64; /* invalid code marker */
  22838. //table.bits[next + huff] = len - drop;
  22839. //table.val[next + huff] = 0;
  22840. table[next + huff] = ((len - drop) << 24) | (64 << 16) |0;
  22841. }
  22842. /* set return parameters */
  22843. //opts.table_index += used;
  22844. opts.bits = root;
  22845. return 0;
  22846. };
  22847. },{"../utils/common":69}],79:[function(require,module,exports){
  22848. 'use strict';
  22849. module.exports = {
  22850. '2': 'need dictionary', /* Z_NEED_DICT 2 */
  22851. '1': 'stream end', /* Z_STREAM_END 1 */
  22852. '0': '', /* Z_OK 0 */
  22853. '-1': 'file error', /* Z_ERRNO (-1) */
  22854. '-2': 'stream error', /* Z_STREAM_ERROR (-2) */
  22855. '-3': 'data error', /* Z_DATA_ERROR (-3) */
  22856. '-4': 'insufficient memory', /* Z_MEM_ERROR (-4) */
  22857. '-5': 'buffer error', /* Z_BUF_ERROR (-5) */
  22858. '-6': 'incompatible version' /* Z_VERSION_ERROR (-6) */
  22859. };
  22860. },{}],80:[function(require,module,exports){
  22861. 'use strict';
  22862. var utils = require('../utils/common');
  22863. /* Public constants ==========================================================*/
  22864. /* ===========================================================================*/
  22865. //var Z_FILTERED = 1;
  22866. //var Z_HUFFMAN_ONLY = 2;
  22867. //var Z_RLE = 3;
  22868. var Z_FIXED = 4;
  22869. //var Z_DEFAULT_STRATEGY = 0;
  22870. /* Possible values of the data_type field (though see inflate()) */
  22871. var Z_BINARY = 0;
  22872. var Z_TEXT = 1;
  22873. //var Z_ASCII = 1; // = Z_TEXT
  22874. var Z_UNKNOWN = 2;
  22875. /*============================================================================*/
  22876. function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
  22877. // From zutil.h
  22878. var STORED_BLOCK = 0;
  22879. var STATIC_TREES = 1;
  22880. var DYN_TREES = 2;
  22881. /* The three kinds of block type */
  22882. var MIN_MATCH = 3;
  22883. var MAX_MATCH = 258;
  22884. /* The minimum and maximum match lengths */
  22885. // From deflate.h
  22886. /* ===========================================================================
  22887. * Internal compression state.
  22888. */
  22889. var LENGTH_CODES = 29;
  22890. /* number of length codes, not counting the special END_BLOCK code */
  22891. var LITERALS = 256;
  22892. /* number of literal bytes 0..255 */
  22893. var L_CODES = LITERALS + 1 + LENGTH_CODES;
  22894. /* number of Literal or Length codes, including the END_BLOCK code */
  22895. var D_CODES = 30;
  22896. /* number of distance codes */
  22897. var BL_CODES = 19;
  22898. /* number of codes used to transfer the bit lengths */
  22899. var HEAP_SIZE = 2*L_CODES + 1;
  22900. /* maximum heap size */
  22901. var MAX_BITS = 15;
  22902. /* All codes must not exceed MAX_BITS bits */
  22903. var Buf_size = 16;
  22904. /* size of bit buffer in bi_buf */
  22905. /* ===========================================================================
  22906. * Constants
  22907. */
  22908. var MAX_BL_BITS = 7;
  22909. /* Bit length codes must not exceed MAX_BL_BITS bits */
  22910. var END_BLOCK = 256;
  22911. /* end of block literal code */
  22912. var REP_3_6 = 16;
  22913. /* repeat previous bit length 3-6 times (2 bits of repeat count) */
  22914. var REPZ_3_10 = 17;
  22915. /* repeat a zero length 3-10 times (3 bits of repeat count) */
  22916. var REPZ_11_138 = 18;
  22917. /* repeat a zero length 11-138 times (7 bits of repeat count) */
  22918. var extra_lbits = /* extra bits for each length code */
  22919. [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];
  22920. var extra_dbits = /* extra bits for each distance code */
  22921. [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];
  22922. var extra_blbits = /* extra bits for each bit length code */
  22923. [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7];
  22924. var bl_order =
  22925. [16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];
  22926. /* The lengths of the bit length codes are sent in order of decreasing
  22927. * probability, to avoid transmitting the lengths for unused bit length codes.
  22928. */
  22929. /* ===========================================================================
  22930. * Local data. These are initialized only once.
  22931. */
  22932. // We pre-fill arrays with 0 to avoid uninitialized gaps
  22933. var DIST_CODE_LEN = 512; /* see definition of array dist_code below */
  22934. // !!!! Use flat array insdead of structure, Freq = i*2, Len = i*2+1
  22935. var static_ltree = new Array((L_CODES+2) * 2);
  22936. zero(static_ltree);
  22937. /* The static literal tree. Since the bit lengths are imposed, there is no
  22938. * need for the L_CODES extra codes used during heap construction. However
  22939. * The codes 286 and 287 are needed to build a canonical tree (see _tr_init
  22940. * below).
  22941. */
  22942. var static_dtree = new Array(D_CODES * 2);
  22943. zero(static_dtree);
  22944. /* The static distance tree. (Actually a trivial tree since all codes use
  22945. * 5 bits.)
  22946. */
  22947. var _dist_code = new Array(DIST_CODE_LEN);
  22948. zero(_dist_code);
  22949. /* Distance codes. The first 256 values correspond to the distances
  22950. * 3 .. 258, the last 256 values correspond to the top 8 bits of
  22951. * the 15 bit distances.
  22952. */
  22953. var _length_code = new Array(MAX_MATCH-MIN_MATCH+1);
  22954. zero(_length_code);
  22955. /* length code for each normalized match length (0 == MIN_MATCH) */
  22956. var base_length = new Array(LENGTH_CODES);
  22957. zero(base_length);
  22958. /* First normalized length for each code (0 = MIN_MATCH) */
  22959. var base_dist = new Array(D_CODES);
  22960. zero(base_dist);
  22961. /* First normalized distance for each code (0 = distance of 1) */
  22962. var StaticTreeDesc = function (static_tree, extra_bits, extra_base, elems, max_length) {
  22963. this.static_tree = static_tree; /* static tree or NULL */
  22964. this.extra_bits = extra_bits; /* extra bits for each code or NULL */
  22965. this.extra_base = extra_base; /* base index for extra_bits */
  22966. this.elems = elems; /* max number of elements in the tree */
  22967. this.max_length = max_length; /* max bit length for the codes */
  22968. // show if `static_tree` has data or dummy - needed for monomorphic objects
  22969. this.has_stree = static_tree && static_tree.length;
  22970. };
  22971. var static_l_desc;
  22972. var static_d_desc;
  22973. var static_bl_desc;
  22974. var TreeDesc = function(dyn_tree, stat_desc) {
  22975. this.dyn_tree = dyn_tree; /* the dynamic tree */
  22976. this.max_code = 0; /* largest code with non zero frequency */
  22977. this.stat_desc = stat_desc; /* the corresponding static tree */
  22978. };
  22979. function d_code(dist) {
  22980. return dist < 256 ? _dist_code[dist] : _dist_code[256 + (dist >>> 7)];
  22981. }
  22982. /* ===========================================================================
  22983. * Output a short LSB first on the stream.
  22984. * IN assertion: there is enough room in pendingBuf.
  22985. */
  22986. function put_short (s, w) {
  22987. // put_byte(s, (uch)((w) & 0xff));
  22988. // put_byte(s, (uch)((ush)(w) >> 8));
  22989. s.pending_buf[s.pending++] = (w) & 0xff;
  22990. s.pending_buf[s.pending++] = (w >>> 8) & 0xff;
  22991. }
  22992. /* ===========================================================================
  22993. * Send a value on a given number of bits.
  22994. * IN assertion: length <= 16 and value fits in length bits.
  22995. */
  22996. function send_bits(s, value, length) {
  22997. if (s.bi_valid > (Buf_size - length)) {
  22998. s.bi_buf |= (value << s.bi_valid) & 0xffff;
  22999. put_short(s, s.bi_buf);
  23000. s.bi_buf = value >> (Buf_size - s.bi_valid);
  23001. s.bi_valid += length - Buf_size;
  23002. } else {
  23003. s.bi_buf |= (value << s.bi_valid) & 0xffff;
  23004. s.bi_valid += length;
  23005. }
  23006. }
  23007. function send_code(s, c, tree) {
  23008. send_bits(s, tree[c*2]/*.Code*/, tree[c*2 + 1]/*.Len*/);
  23009. }
  23010. /* ===========================================================================
  23011. * Reverse the first len bits of a code, using straightforward code (a faster
  23012. * method would use a table)
  23013. * IN assertion: 1 <= len <= 15
  23014. */
  23015. function bi_reverse(code, len) {
  23016. var res = 0;
  23017. do {
  23018. res |= code & 1;
  23019. code >>>= 1;
  23020. res <<= 1;
  23021. } while (--len > 0);
  23022. return res >>> 1;
  23023. }
  23024. /* ===========================================================================
  23025. * Flush the bit buffer, keeping at most 7 bits in it.
  23026. */
  23027. function bi_flush(s) {
  23028. if (s.bi_valid === 16) {
  23029. put_short(s, s.bi_buf);
  23030. s.bi_buf = 0;
  23031. s.bi_valid = 0;
  23032. } else if (s.bi_valid >= 8) {
  23033. s.pending_buf[s.pending++] = s.bi_buf & 0xff;
  23034. s.bi_buf >>= 8;
  23035. s.bi_valid -= 8;
  23036. }
  23037. }
  23038. /* ===========================================================================
  23039. * Compute the optimal bit lengths for a tree and update the total bit length
  23040. * for the current block.
  23041. * IN assertion: the fields freq and dad are set, heap[heap_max] and
  23042. * above are the tree nodes sorted by increasing frequency.
  23043. * OUT assertions: the field len is set to the optimal bit length, the
  23044. * array bl_count contains the frequencies for each bit length.
  23045. * The length opt_len is updated; static_len is also updated if stree is
  23046. * not null.
  23047. */
  23048. function gen_bitlen(s, desc)
  23049. // deflate_state *s;
  23050. // tree_desc *desc; /* the tree descriptor */
  23051. {
  23052. var tree = desc.dyn_tree;
  23053. var max_code = desc.max_code;
  23054. var stree = desc.stat_desc.static_tree;
  23055. var has_stree = desc.stat_desc.has_stree;
  23056. var extra = desc.stat_desc.extra_bits;
  23057. var base = desc.stat_desc.extra_base;
  23058. var max_length = desc.stat_desc.max_length;
  23059. var h; /* heap index */
  23060. var n, m; /* iterate over the tree elements */
  23061. var bits; /* bit length */
  23062. var xbits; /* extra bits */
  23063. var f; /* frequency */
  23064. var overflow = 0; /* number of elements with bit length too large */
  23065. for (bits = 0; bits <= MAX_BITS; bits++) {
  23066. s.bl_count[bits] = 0;
  23067. }
  23068. /* In a first pass, compute the optimal bit lengths (which may
  23069. * overflow in the case of the bit length tree).
  23070. */
  23071. tree[s.heap[s.heap_max]*2 + 1]/*.Len*/ = 0; /* root of the heap */
  23072. for (h = s.heap_max+1; h < HEAP_SIZE; h++) {
  23073. n = s.heap[h];
  23074. bits = tree[tree[n*2 +1]/*.Dad*/ * 2 + 1]/*.Len*/ + 1;
  23075. if (bits > max_length) {
  23076. bits = max_length;
  23077. overflow++;
  23078. }
  23079. tree[n*2 + 1]/*.Len*/ = bits;
  23080. /* We overwrite tree[n].Dad which is no longer needed */
  23081. if (n > max_code) { continue; } /* not a leaf node */
  23082. s.bl_count[bits]++;
  23083. xbits = 0;
  23084. if (n >= base) {
  23085. xbits = extra[n-base];
  23086. }
  23087. f = tree[n * 2]/*.Freq*/;
  23088. s.opt_len += f * (bits + xbits);
  23089. if (has_stree) {
  23090. s.static_len += f * (stree[n*2 + 1]/*.Len*/ + xbits);
  23091. }
  23092. }
  23093. if (overflow === 0) { return; }
  23094. // Trace((stderr,"\nbit length overflow\n"));
  23095. /* This happens for example on obj2 and pic of the Calgary corpus */
  23096. /* Find the first bit length which could increase: */
  23097. do {
  23098. bits = max_length-1;
  23099. while (s.bl_count[bits] === 0) { bits--; }
  23100. s.bl_count[bits]--; /* move one leaf down the tree */
  23101. s.bl_count[bits+1] += 2; /* move one overflow item as its brother */
  23102. s.bl_count[max_length]--;
  23103. /* The brother of the overflow item also moves one step up,
  23104. * but this does not affect bl_count[max_length]
  23105. */
  23106. overflow -= 2;
  23107. } while (overflow > 0);
  23108. /* Now recompute all bit lengths, scanning in increasing frequency.
  23109. * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all
  23110. * lengths instead of fixing only the wrong ones. This idea is taken
  23111. * from 'ar' written by Haruhiko Okumura.)
  23112. */
  23113. for (bits = max_length; bits !== 0; bits--) {
  23114. n = s.bl_count[bits];
  23115. while (n !== 0) {
  23116. m = s.heap[--h];
  23117. if (m > max_code) { continue; }
  23118. if (tree[m*2 + 1]/*.Len*/ !== bits) {
  23119. // Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits));
  23120. s.opt_len += (bits - tree[m*2 + 1]/*.Len*/)*tree[m*2]/*.Freq*/;
  23121. tree[m*2 + 1]/*.Len*/ = bits;
  23122. }
  23123. n--;
  23124. }
  23125. }
  23126. }
  23127. /* ===========================================================================
  23128. * Generate the codes for a given tree and bit counts (which need not be
  23129. * optimal).
  23130. * IN assertion: the array bl_count contains the bit length statistics for
  23131. * the given tree and the field len is set for all tree elements.
  23132. * OUT assertion: the field code is set for all tree elements of non
  23133. * zero code length.
  23134. */
  23135. function gen_codes(tree, max_code, bl_count)
  23136. // ct_data *tree; /* the tree to decorate */
  23137. // int max_code; /* largest code with non zero frequency */
  23138. // ushf *bl_count; /* number of codes at each bit length */
  23139. {
  23140. var next_code = new Array(MAX_BITS+1); /* next code value for each bit length */
  23141. var code = 0; /* running code value */
  23142. var bits; /* bit index */
  23143. var n; /* code index */
  23144. /* The distribution counts are first used to generate the code values
  23145. * without bit reversal.
  23146. */
  23147. for (bits = 1; bits <= MAX_BITS; bits++) {
  23148. next_code[bits] = code = (code + bl_count[bits-1]) << 1;
  23149. }
  23150. /* Check that the bit counts in bl_count are consistent. The last code
  23151. * must be all ones.
  23152. */
  23153. //Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,
  23154. // "inconsistent bit counts");
  23155. //Tracev((stderr,"\ngen_codes: max_code %d ", max_code));
  23156. for (n = 0; n <= max_code; n++) {
  23157. var len = tree[n*2 + 1]/*.Len*/;
  23158. if (len === 0) { continue; }
  23159. /* Now reverse the bits */
  23160. tree[n*2]/*.Code*/ = bi_reverse(next_code[len]++, len);
  23161. //Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ",
  23162. // n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1));
  23163. }
  23164. }
  23165. /* ===========================================================================
  23166. * Initialize the various 'constant' tables.
  23167. */
  23168. function tr_static_init() {
  23169. var n; /* iterates over tree elements */
  23170. var bits; /* bit counter */
  23171. var length; /* length value */
  23172. var code; /* code value */
  23173. var dist; /* distance index */
  23174. var bl_count = new Array(MAX_BITS+1);
  23175. /* number of codes at each bit length for an optimal tree */
  23176. // do check in _tr_init()
  23177. //if (static_init_done) return;
  23178. /* For some embedded targets, global variables are not initialized: */
  23179. /*#ifdef NO_INIT_GLOBAL_POINTERS
  23180. static_l_desc.static_tree = static_ltree;
  23181. static_l_desc.extra_bits = extra_lbits;
  23182. static_d_desc.static_tree = static_dtree;
  23183. static_d_desc.extra_bits = extra_dbits;
  23184. static_bl_desc.extra_bits = extra_blbits;
  23185. #endif*/
  23186. /* Initialize the mapping length (0..255) -> length code (0..28) */
  23187. length = 0;
  23188. for (code = 0; code < LENGTH_CODES-1; code++) {
  23189. base_length[code] = length;
  23190. for (n = 0; n < (1<<extra_lbits[code]); n++) {
  23191. _length_code[length++] = code;
  23192. }
  23193. }
  23194. //Assert (length == 256, "tr_static_init: length != 256");
  23195. /* Note that the length 255 (match length 258) can be represented
  23196. * in two different ways: code 284 + 5 bits or code 285, so we
  23197. * overwrite length_code[255] to use the best encoding:
  23198. */
  23199. _length_code[length-1] = code;
  23200. /* Initialize the mapping dist (0..32K) -> dist code (0..29) */
  23201. dist = 0;
  23202. for (code = 0 ; code < 16; code++) {
  23203. base_dist[code] = dist;
  23204. for (n = 0; n < (1<<extra_dbits[code]); n++) {
  23205. _dist_code[dist++] = code;
  23206. }
  23207. }
  23208. //Assert (dist == 256, "tr_static_init: dist != 256");
  23209. dist >>= 7; /* from now on, all distances are divided by 128 */
  23210. for ( ; code < D_CODES; code++) {
  23211. base_dist[code] = dist << 7;
  23212. for (n = 0; n < (1<<(extra_dbits[code]-7)); n++) {
  23213. _dist_code[256 + dist++] = code;
  23214. }
  23215. }
  23216. //Assert (dist == 256, "tr_static_init: 256+dist != 512");
  23217. /* Construct the codes of the static literal tree */
  23218. for (bits = 0; bits <= MAX_BITS; bits++) {
  23219. bl_count[bits] = 0;
  23220. }
  23221. n = 0;
  23222. while (n <= 143) {
  23223. static_ltree[n*2 + 1]/*.Len*/ = 8;
  23224. n++;
  23225. bl_count[8]++;
  23226. }
  23227. while (n <= 255) {
  23228. static_ltree[n*2 + 1]/*.Len*/ = 9;
  23229. n++;
  23230. bl_count[9]++;
  23231. }
  23232. while (n <= 279) {
  23233. static_ltree[n*2 + 1]/*.Len*/ = 7;
  23234. n++;
  23235. bl_count[7]++;
  23236. }
  23237. while (n <= 287) {
  23238. static_ltree[n*2 + 1]/*.Len*/ = 8;
  23239. n++;
  23240. bl_count[8]++;
  23241. }
  23242. /* Codes 286 and 287 do not exist, but we must include them in the
  23243. * tree construction to get a canonical Huffman tree (longest code
  23244. * all ones)
  23245. */
  23246. gen_codes(static_ltree, L_CODES+1, bl_count);
  23247. /* The static distance tree is trivial: */
  23248. for (n = 0; n < D_CODES; n++) {
  23249. static_dtree[n*2 + 1]/*.Len*/ = 5;
  23250. static_dtree[n*2]/*.Code*/ = bi_reverse(n, 5);
  23251. }
  23252. // Now data ready and we can init static trees
  23253. static_l_desc = new StaticTreeDesc(static_ltree, extra_lbits, LITERALS+1, L_CODES, MAX_BITS);
  23254. static_d_desc = new StaticTreeDesc(static_dtree, extra_dbits, 0, D_CODES, MAX_BITS);
  23255. static_bl_desc =new StaticTreeDesc(new Array(0), extra_blbits, 0, BL_CODES, MAX_BL_BITS);
  23256. //static_init_done = true;
  23257. }
  23258. /* ===========================================================================
  23259. * Initialize a new block.
  23260. */
  23261. function init_block(s) {
  23262. var n; /* iterates over tree elements */
  23263. /* Initialize the trees. */
  23264. for (n = 0; n < L_CODES; n++) { s.dyn_ltree[n*2]/*.Freq*/ = 0; }
  23265. for (n = 0; n < D_CODES; n++) { s.dyn_dtree[n*2]/*.Freq*/ = 0; }
  23266. for (n = 0; n < BL_CODES; n++) { s.bl_tree[n*2]/*.Freq*/ = 0; }
  23267. s.dyn_ltree[END_BLOCK*2]/*.Freq*/ = 1;
  23268. s.opt_len = s.static_len = 0;
  23269. s.last_lit = s.matches = 0;
  23270. }
  23271. /* ===========================================================================
  23272. * Flush the bit buffer and align the output on a byte boundary
  23273. */
  23274. function bi_windup(s)
  23275. {
  23276. if (s.bi_valid > 8) {
  23277. put_short(s, s.bi_buf);
  23278. } else if (s.bi_valid > 0) {
  23279. //put_byte(s, (Byte)s->bi_buf);
  23280. s.pending_buf[s.pending++] = s.bi_buf;
  23281. }
  23282. s.bi_buf = 0;
  23283. s.bi_valid = 0;
  23284. }
  23285. /* ===========================================================================
  23286. * Copy a stored block, storing first the length and its
  23287. * one's complement if requested.
  23288. */
  23289. function copy_block(s, buf, len, header)
  23290. //DeflateState *s;
  23291. //charf *buf; /* the input data */
  23292. //unsigned len; /* its length */
  23293. //int header; /* true if block header must be written */
  23294. {
  23295. bi_windup(s); /* align on byte boundary */
  23296. if (header) {
  23297. put_short(s, len);
  23298. put_short(s, ~len);
  23299. }
  23300. // while (len--) {
  23301. // put_byte(s, *buf++);
  23302. // }
  23303. utils.arraySet(s.pending_buf, s.window, buf, len, s.pending);
  23304. s.pending += len;
  23305. }
  23306. /* ===========================================================================
  23307. * Compares to subtrees, using the tree depth as tie breaker when
  23308. * the subtrees have equal frequency. This minimizes the worst case length.
  23309. */
  23310. function smaller(tree, n, m, depth) {
  23311. var _n2 = n*2;
  23312. var _m2 = m*2;
  23313. return (tree[_n2]/*.Freq*/ < tree[_m2]/*.Freq*/ ||
  23314. (tree[_n2]/*.Freq*/ === tree[_m2]/*.Freq*/ && depth[n] <= depth[m]));
  23315. }
  23316. /* ===========================================================================
  23317. * Restore the heap property by moving down the tree starting at node k,
  23318. * exchanging a node with the smallest of its two sons if necessary, stopping
  23319. * when the heap property is re-established (each father smaller than its
  23320. * two sons).
  23321. */
  23322. function pqdownheap(s, tree, k)
  23323. // deflate_state *s;
  23324. // ct_data *tree; /* the tree to restore */
  23325. // int k; /* node to move down */
  23326. {
  23327. var v = s.heap[k];
  23328. var j = k << 1; /* left son of k */
  23329. while (j <= s.heap_len) {
  23330. /* Set j to the smallest of the two sons: */
  23331. if (j < s.heap_len &&
  23332. smaller(tree, s.heap[j+1], s.heap[j], s.depth)) {
  23333. j++;
  23334. }
  23335. /* Exit if v is smaller than both sons */
  23336. if (smaller(tree, v, s.heap[j], s.depth)) { break; }
  23337. /* Exchange v with the smallest son */
  23338. s.heap[k] = s.heap[j];
  23339. k = j;
  23340. /* And continue down the tree, setting j to the left son of k */
  23341. j <<= 1;
  23342. }
  23343. s.heap[k] = v;
  23344. }
  23345. // inlined manually
  23346. // var SMALLEST = 1;
  23347. /* ===========================================================================
  23348. * Send the block data compressed using the given Huffman trees
  23349. */
  23350. function compress_block(s, ltree, dtree)
  23351. // deflate_state *s;
  23352. // const ct_data *ltree; /* literal tree */
  23353. // const ct_data *dtree; /* distance tree */
  23354. {
  23355. var dist; /* distance of matched string */
  23356. var lc; /* match length or unmatched char (if dist == 0) */
  23357. var lx = 0; /* running index in l_buf */
  23358. var code; /* the code to send */
  23359. var extra; /* number of extra bits to send */
  23360. if (s.last_lit !== 0) {
  23361. do {
  23362. dist = (s.pending_buf[s.d_buf + lx*2] << 8) | (s.pending_buf[s.d_buf + lx*2 + 1]);
  23363. lc = s.pending_buf[s.l_buf + lx];
  23364. lx++;
  23365. if (dist === 0) {
  23366. send_code(s, lc, ltree); /* send a literal byte */
  23367. //Tracecv(isgraph(lc), (stderr," '%c' ", lc));
  23368. } else {
  23369. /* Here, lc is the match length - MIN_MATCH */
  23370. code = _length_code[lc];
  23371. send_code(s, code+LITERALS+1, ltree); /* send the length code */
  23372. extra = extra_lbits[code];
  23373. if (extra !== 0) {
  23374. lc -= base_length[code];
  23375. send_bits(s, lc, extra); /* send the extra length bits */
  23376. }
  23377. dist--; /* dist is now the match distance - 1 */
  23378. code = d_code(dist);
  23379. //Assert (code < D_CODES, "bad d_code");
  23380. send_code(s, code, dtree); /* send the distance code */
  23381. extra = extra_dbits[code];
  23382. if (extra !== 0) {
  23383. dist -= base_dist[code];
  23384. send_bits(s, dist, extra); /* send the extra distance bits */
  23385. }
  23386. } /* literal or match pair ? */
  23387. /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */
  23388. //Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx,
  23389. // "pendingBuf overflow");
  23390. } while (lx < s.last_lit);
  23391. }
  23392. send_code(s, END_BLOCK, ltree);
  23393. }
  23394. /* ===========================================================================
  23395. * Construct one Huffman tree and assigns the code bit strings and lengths.
  23396. * Update the total bit length for the current block.
  23397. * IN assertion: the field freq is set for all tree elements.
  23398. * OUT assertions: the fields len and code are set to the optimal bit length
  23399. * and corresponding code. The length opt_len is updated; static_len is
  23400. * also updated if stree is not null. The field max_code is set.
  23401. */
  23402. function build_tree(s, desc)
  23403. // deflate_state *s;
  23404. // tree_desc *desc; /* the tree descriptor */
  23405. {
  23406. var tree = desc.dyn_tree;
  23407. var stree = desc.stat_desc.static_tree;
  23408. var has_stree = desc.stat_desc.has_stree;
  23409. var elems = desc.stat_desc.elems;
  23410. var n, m; /* iterate over heap elements */
  23411. var max_code = -1; /* largest code with non zero frequency */
  23412. var node; /* new node being created */
  23413. /* Construct the initial heap, with least frequent element in
  23414. * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
  23415. * heap[0] is not used.
  23416. */
  23417. s.heap_len = 0;
  23418. s.heap_max = HEAP_SIZE;
  23419. for (n = 0; n < elems; n++) {
  23420. if (tree[n * 2]/*.Freq*/ !== 0) {
  23421. s.heap[++s.heap_len] = max_code = n;
  23422. s.depth[n] = 0;
  23423. } else {
  23424. tree[n*2 + 1]/*.Len*/ = 0;
  23425. }
  23426. }
  23427. /* The pkzip format requires that at least one distance code exists,
  23428. * and that at least one bit should be sent even if there is only one
  23429. * possible code. So to avoid special checks later on we force at least
  23430. * two codes of non zero frequency.
  23431. */
  23432. while (s.heap_len < 2) {
  23433. node = s.heap[++s.heap_len] = (max_code < 2 ? ++max_code : 0);
  23434. tree[node * 2]/*.Freq*/ = 1;
  23435. s.depth[node] = 0;
  23436. s.opt_len--;
  23437. if (has_stree) {
  23438. s.static_len -= stree[node*2 + 1]/*.Len*/;
  23439. }
  23440. /* node is 0 or 1 so it does not have extra bits */
  23441. }
  23442. desc.max_code = max_code;
  23443. /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
  23444. * establish sub-heaps of increasing lengths:
  23445. */
  23446. for (n = (s.heap_len >> 1/*int /2*/); n >= 1; n--) { pqdownheap(s, tree, n); }
  23447. /* Construct the Huffman tree by repeatedly combining the least two
  23448. * frequent nodes.
  23449. */
  23450. node = elems; /* next internal node of the tree */
  23451. do {
  23452. //pqremove(s, tree, n); /* n = node of least frequency */
  23453. /*** pqremove ***/
  23454. n = s.heap[1/*SMALLEST*/];
  23455. s.heap[1/*SMALLEST*/] = s.heap[s.heap_len--];
  23456. pqdownheap(s, tree, 1/*SMALLEST*/);
  23457. /***/
  23458. m = s.heap[1/*SMALLEST*/]; /* m = node of next least frequency */
  23459. s.heap[--s.heap_max] = n; /* keep the nodes sorted by frequency */
  23460. s.heap[--s.heap_max] = m;
  23461. /* Create a new node father of n and m */
  23462. tree[node * 2]/*.Freq*/ = tree[n * 2]/*.Freq*/ + tree[m * 2]/*.Freq*/;
  23463. s.depth[node] = (s.depth[n] >= s.depth[m] ? s.depth[n] : s.depth[m]) + 1;
  23464. tree[n*2 + 1]/*.Dad*/ = tree[m*2 + 1]/*.Dad*/ = node;
  23465. /* and insert the new node in the heap */
  23466. s.heap[1/*SMALLEST*/] = node++;
  23467. pqdownheap(s, tree, 1/*SMALLEST*/);
  23468. } while (s.heap_len >= 2);
  23469. s.heap[--s.heap_max] = s.heap[1/*SMALLEST*/];
  23470. /* At this point, the fields freq and dad are set. We can now
  23471. * generate the bit lengths.
  23472. */
  23473. gen_bitlen(s, desc);
  23474. /* The field len is now set, we can generate the bit codes */
  23475. gen_codes(tree, max_code, s.bl_count);
  23476. }
  23477. /* ===========================================================================
  23478. * Scan a literal or distance tree to determine the frequencies of the codes
  23479. * in the bit length tree.
  23480. */
  23481. function scan_tree(s, tree, max_code)
  23482. // deflate_state *s;
  23483. // ct_data *tree; /* the tree to be scanned */
  23484. // int max_code; /* and its largest code of non zero frequency */
  23485. {
  23486. var n; /* iterates over all tree elements */
  23487. var prevlen = -1; /* last emitted length */
  23488. var curlen; /* length of current code */
  23489. var nextlen = tree[0*2 + 1]/*.Len*/; /* length of next code */
  23490. var count = 0; /* repeat count of the current code */
  23491. var max_count = 7; /* max repeat count */
  23492. var min_count = 4; /* min repeat count */
  23493. if (nextlen === 0) {
  23494. max_count = 138;
  23495. min_count = 3;
  23496. }
  23497. tree[(max_code+1)*2 + 1]/*.Len*/ = 0xffff; /* guard */
  23498. for (n = 0; n <= max_code; n++) {
  23499. curlen = nextlen;
  23500. nextlen = tree[(n+1)*2 + 1]/*.Len*/;
  23501. if (++count < max_count && curlen === nextlen) {
  23502. continue;
  23503. } else if (count < min_count) {
  23504. s.bl_tree[curlen * 2]/*.Freq*/ += count;
  23505. } else if (curlen !== 0) {
  23506. if (curlen !== prevlen) { s.bl_tree[curlen * 2]/*.Freq*/++; }
  23507. s.bl_tree[REP_3_6*2]/*.Freq*/++;
  23508. } else if (count <= 10) {
  23509. s.bl_tree[REPZ_3_10*2]/*.Freq*/++;
  23510. } else {
  23511. s.bl_tree[REPZ_11_138*2]/*.Freq*/++;
  23512. }
  23513. count = 0;
  23514. prevlen = curlen;
  23515. if (nextlen === 0) {
  23516. max_count = 138;
  23517. min_count = 3;
  23518. } else if (curlen === nextlen) {
  23519. max_count = 6;
  23520. min_count = 3;
  23521. } else {
  23522. max_count = 7;
  23523. min_count = 4;
  23524. }
  23525. }
  23526. }
  23527. /* ===========================================================================
  23528. * Send a literal or distance tree in compressed form, using the codes in
  23529. * bl_tree.
  23530. */
  23531. function send_tree(s, tree, max_code)
  23532. // deflate_state *s;
  23533. // ct_data *tree; /* the tree to be scanned */
  23534. // int max_code; /* and its largest code of non zero frequency */
  23535. {
  23536. var n; /* iterates over all tree elements */
  23537. var prevlen = -1; /* last emitted length */
  23538. var curlen; /* length of current code */
  23539. var nextlen = tree[0*2 + 1]/*.Len*/; /* length of next code */
  23540. var count = 0; /* repeat count of the current code */
  23541. var max_count = 7; /* max repeat count */
  23542. var min_count = 4; /* min repeat count */
  23543. /* tree[max_code+1].Len = -1; */ /* guard already set */
  23544. if (nextlen === 0) {
  23545. max_count = 138;
  23546. min_count = 3;
  23547. }
  23548. for (n = 0; n <= max_code; n++) {
  23549. curlen = nextlen;
  23550. nextlen = tree[(n+1)*2 + 1]/*.Len*/;
  23551. if (++count < max_count && curlen === nextlen) {
  23552. continue;
  23553. } else if (count < min_count) {
  23554. do { send_code(s, curlen, s.bl_tree); } while (--count !== 0);
  23555. } else if (curlen !== 0) {
  23556. if (curlen !== prevlen) {
  23557. send_code(s, curlen, s.bl_tree);
  23558. count--;
  23559. }
  23560. //Assert(count >= 3 && count <= 6, " 3_6?");
  23561. send_code(s, REP_3_6, s.bl_tree);
  23562. send_bits(s, count-3, 2);
  23563. } else if (count <= 10) {
  23564. send_code(s, REPZ_3_10, s.bl_tree);
  23565. send_bits(s, count-3, 3);
  23566. } else {
  23567. send_code(s, REPZ_11_138, s.bl_tree);
  23568. send_bits(s, count-11, 7);
  23569. }
  23570. count = 0;
  23571. prevlen = curlen;
  23572. if (nextlen === 0) {
  23573. max_count = 138;
  23574. min_count = 3;
  23575. } else if (curlen === nextlen) {
  23576. max_count = 6;
  23577. min_count = 3;
  23578. } else {
  23579. max_count = 7;
  23580. min_count = 4;
  23581. }
  23582. }
  23583. }
  23584. /* ===========================================================================
  23585. * Construct the Huffman tree for the bit lengths and return the index in
  23586. * bl_order of the last bit length code to send.
  23587. */
  23588. function build_bl_tree(s) {
  23589. var max_blindex; /* index of last bit length code of non zero freq */
  23590. /* Determine the bit length frequencies for literal and distance trees */
  23591. scan_tree(s, s.dyn_ltree, s.l_desc.max_code);
  23592. scan_tree(s, s.dyn_dtree, s.d_desc.max_code);
  23593. /* Build the bit length tree: */
  23594. build_tree(s, s.bl_desc);
  23595. /* opt_len now includes the length of the tree representations, except
  23596. * the lengths of the bit lengths codes and the 5+5+4 bits for the counts.
  23597. */
  23598. /* Determine the number of bit length codes to send. The pkzip format
  23599. * requires that at least 4 bit length codes be sent. (appnote.txt says
  23600. * 3 but the actual value used is 4.)
  23601. */
  23602. for (max_blindex = BL_CODES-1; max_blindex >= 3; max_blindex--) {
  23603. if (s.bl_tree[bl_order[max_blindex]*2 + 1]/*.Len*/ !== 0) {
  23604. break;
  23605. }
  23606. }
  23607. /* Update opt_len to include the bit length tree and counts */
  23608. s.opt_len += 3*(max_blindex+1) + 5+5+4;
  23609. //Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld",
  23610. // s->opt_len, s->static_len));
  23611. return max_blindex;
  23612. }
  23613. /* ===========================================================================
  23614. * Send the header for a block using dynamic Huffman trees: the counts, the
  23615. * lengths of the bit length codes, the literal tree and the distance tree.
  23616. * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
  23617. */
  23618. function send_all_trees(s, lcodes, dcodes, blcodes)
  23619. // deflate_state *s;
  23620. // int lcodes, dcodes, blcodes; /* number of codes for each tree */
  23621. {
  23622. var rank; /* index in bl_order */
  23623. //Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes");
  23624. //Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,
  23625. // "too many codes");
  23626. //Tracev((stderr, "\nbl counts: "));
  23627. send_bits(s, lcodes-257, 5); /* not +255 as stated in appnote.txt */
  23628. send_bits(s, dcodes-1, 5);
  23629. send_bits(s, blcodes-4, 4); /* not -3 as stated in appnote.txt */
  23630. for (rank = 0; rank < blcodes; rank++) {
  23631. //Tracev((stderr, "\nbl code %2d ", bl_order[rank]));
  23632. send_bits(s, s.bl_tree[bl_order[rank]*2 + 1]/*.Len*/, 3);
  23633. }
  23634. //Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent));
  23635. send_tree(s, s.dyn_ltree, lcodes-1); /* literal tree */
  23636. //Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent));
  23637. send_tree(s, s.dyn_dtree, dcodes-1); /* distance tree */
  23638. //Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent));
  23639. }
  23640. /* ===========================================================================
  23641. * Check if the data type is TEXT or BINARY, using the following algorithm:
  23642. * - TEXT if the two conditions below are satisfied:
  23643. * a) There are no non-portable control characters belonging to the
  23644. * "black list" (0..6, 14..25, 28..31).
  23645. * b) There is at least one printable character belonging to the
  23646. * "white list" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255).
  23647. * - BINARY otherwise.
  23648. * - The following partially-portable control characters form a
  23649. * "gray list" that is ignored in this detection algorithm:
  23650. * (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}).
  23651. * IN assertion: the fields Freq of dyn_ltree are set.
  23652. */
  23653. function detect_data_type(s) {
  23654. /* black_mask is the bit mask of black-listed bytes
  23655. * set bits 0..6, 14..25, and 28..31
  23656. * 0xf3ffc07f = binary 11110011111111111100000001111111
  23657. */
  23658. var black_mask = 0xf3ffc07f;
  23659. var n;
  23660. /* Check for non-textual ("black-listed") bytes. */
  23661. for (n = 0; n <= 31; n++, black_mask >>>= 1) {
  23662. if ((black_mask & 1) && (s.dyn_ltree[n*2]/*.Freq*/ !== 0)) {
  23663. return Z_BINARY;
  23664. }
  23665. }
  23666. /* Check for textual ("white-listed") bytes. */
  23667. if (s.dyn_ltree[9 * 2]/*.Freq*/ !== 0 || s.dyn_ltree[10 * 2]/*.Freq*/ !== 0 ||
  23668. s.dyn_ltree[13 * 2]/*.Freq*/ !== 0) {
  23669. return Z_TEXT;
  23670. }
  23671. for (n = 32; n < LITERALS; n++) {
  23672. if (s.dyn_ltree[n * 2]/*.Freq*/ !== 0) {
  23673. return Z_TEXT;
  23674. }
  23675. }
  23676. /* There are no "black-listed" or "white-listed" bytes:
  23677. * this stream either is empty or has tolerated ("gray-listed") bytes only.
  23678. */
  23679. return Z_BINARY;
  23680. }
  23681. var static_init_done = false;
  23682. /* ===========================================================================
  23683. * Initialize the tree data structures for a new zlib stream.
  23684. */
  23685. function _tr_init(s)
  23686. {
  23687. if (!static_init_done) {
  23688. tr_static_init();
  23689. static_init_done = true;
  23690. }
  23691. s.l_desc = new TreeDesc(s.dyn_ltree, static_l_desc);
  23692. s.d_desc = new TreeDesc(s.dyn_dtree, static_d_desc);
  23693. s.bl_desc = new TreeDesc(s.bl_tree, static_bl_desc);
  23694. s.bi_buf = 0;
  23695. s.bi_valid = 0;
  23696. /* Initialize the first block of the first file: */
  23697. init_block(s);
  23698. }
  23699. /* ===========================================================================
  23700. * Send a stored block
  23701. */
  23702. function _tr_stored_block(s, buf, stored_len, last)
  23703. //DeflateState *s;
  23704. //charf *buf; /* input block */
  23705. //ulg stored_len; /* length of input block */
  23706. //int last; /* one if this is the last block for a file */
  23707. {
  23708. send_bits(s, (STORED_BLOCK<<1)+(last ? 1 : 0), 3); /* send block type */
  23709. copy_block(s, buf, stored_len, true); /* with header */
  23710. }
  23711. /* ===========================================================================
  23712. * Send one empty static block to give enough lookahead for inflate.
  23713. * This takes 10 bits, of which 7 may remain in the bit buffer.
  23714. */
  23715. function _tr_align(s) {
  23716. send_bits(s, STATIC_TREES<<1, 3);
  23717. send_code(s, END_BLOCK, static_ltree);
  23718. bi_flush(s);
  23719. }
  23720. /* ===========================================================================
  23721. * Determine the best encoding for the current block: dynamic trees, static
  23722. * trees or store, and output the encoded block to the zip file.
  23723. */
  23724. function _tr_flush_block(s, buf, stored_len, last)
  23725. //DeflateState *s;
  23726. //charf *buf; /* input block, or NULL if too old */
  23727. //ulg stored_len; /* length of input block */
  23728. //int last; /* one if this is the last block for a file */
  23729. {
  23730. var opt_lenb, static_lenb; /* opt_len and static_len in bytes */
  23731. var max_blindex = 0; /* index of last bit length code of non zero freq */
  23732. /* Build the Huffman trees unless a stored block is forced */
  23733. if (s.level > 0) {
  23734. /* Check if the file is binary or text */
  23735. if (s.strm.data_type === Z_UNKNOWN) {
  23736. s.strm.data_type = detect_data_type(s);
  23737. }
  23738. /* Construct the literal and distance trees */
  23739. build_tree(s, s.l_desc);
  23740. // Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len,
  23741. // s->static_len));
  23742. build_tree(s, s.d_desc);
  23743. // Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len,
  23744. // s->static_len));
  23745. /* At this point, opt_len and static_len are the total bit lengths of
  23746. * the compressed block data, excluding the tree representations.
  23747. */
  23748. /* Build the bit length tree for the above two trees, and get the index
  23749. * in bl_order of the last bit length code to send.
  23750. */
  23751. max_blindex = build_bl_tree(s);
  23752. /* Determine the best encoding. Compute the block lengths in bytes. */
  23753. opt_lenb = (s.opt_len+3+7) >>> 3;
  23754. static_lenb = (s.static_len+3+7) >>> 3;
  23755. // Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ",
  23756. // opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,
  23757. // s->last_lit));
  23758. if (static_lenb <= opt_lenb) { opt_lenb = static_lenb; }
  23759. } else {
  23760. // Assert(buf != (char*)0, "lost buf");
  23761. opt_lenb = static_lenb = stored_len + 5; /* force a stored block */
  23762. }
  23763. if ((stored_len+4 <= opt_lenb) && (buf !== -1)) {
  23764. /* 4: two words for the lengths */
  23765. /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
  23766. * Otherwise we can't have processed more than WSIZE input bytes since
  23767. * the last block flush, because compression would have been
  23768. * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
  23769. * transform a block into a stored block.
  23770. */
  23771. _tr_stored_block(s, buf, stored_len, last);
  23772. } else if (s.strategy === Z_FIXED || static_lenb === opt_lenb) {
  23773. send_bits(s, (STATIC_TREES<<1) + (last ? 1 : 0), 3);
  23774. compress_block(s, static_ltree, static_dtree);
  23775. } else {
  23776. send_bits(s, (DYN_TREES<<1) + (last ? 1 : 0), 3);
  23777. send_all_trees(s, s.l_desc.max_code+1, s.d_desc.max_code+1, max_blindex+1);
  23778. compress_block(s, s.dyn_ltree, s.dyn_dtree);
  23779. }
  23780. // Assert (s->compressed_len == s->bits_sent, "bad compressed size");
  23781. /* The above check is made mod 2^32, for files larger than 512 MB
  23782. * and uLong implemented on 32 bits.
  23783. */
  23784. init_block(s);
  23785. if (last) {
  23786. bi_windup(s);
  23787. }
  23788. // Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3,
  23789. // s->compressed_len-7*last));
  23790. }
  23791. /* ===========================================================================
  23792. * Save the match info and tally the frequency counts. Return true if
  23793. * the current block must be flushed.
  23794. */
  23795. function _tr_tally(s, dist, lc)
  23796. // deflate_state *s;
  23797. // unsigned dist; /* distance of matched string */
  23798. // unsigned lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */
  23799. {
  23800. //var out_length, in_length, dcode;
  23801. s.pending_buf[s.d_buf + s.last_lit * 2] = (dist >>> 8) & 0xff;
  23802. s.pending_buf[s.d_buf + s.last_lit * 2 + 1] = dist & 0xff;
  23803. s.pending_buf[s.l_buf + s.last_lit] = lc & 0xff;
  23804. s.last_lit++;
  23805. if (dist === 0) {
  23806. /* lc is the unmatched char */
  23807. s.dyn_ltree[lc*2]/*.Freq*/++;
  23808. } else {
  23809. s.matches++;
  23810. /* Here, lc is the match length - MIN_MATCH */
  23811. dist--; /* dist = match distance - 1 */
  23812. //Assert((ush)dist < (ush)MAX_DIST(s) &&
  23813. // (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&
  23814. // (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match");
  23815. s.dyn_ltree[(_length_code[lc]+LITERALS+1) * 2]/*.Freq*/++;
  23816. s.dyn_dtree[d_code(dist) * 2]/*.Freq*/++;
  23817. }
  23818. // (!) This block is disabled in zlib defailts,
  23819. // don't enable it for binary compatibility
  23820. //#ifdef TRUNCATE_BLOCK
  23821. // /* Try to guess if it is profitable to stop the current block here */
  23822. // if ((s.last_lit & 0x1fff) === 0 && s.level > 2) {
  23823. // /* Compute an upper bound for the compressed length */
  23824. // out_length = s.last_lit*8;
  23825. // in_length = s.strstart - s.block_start;
  23826. //
  23827. // for (dcode = 0; dcode < D_CODES; dcode++) {
  23828. // out_length += s.dyn_dtree[dcode*2]/*.Freq*/ * (5 + extra_dbits[dcode]);
  23829. // }
  23830. // out_length >>>= 3;
  23831. // //Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ",
  23832. // // s->last_lit, in_length, out_length,
  23833. // // 100L - out_length*100L/in_length));
  23834. // if (s.matches < (s.last_lit>>1)/*int /2*/ && out_length < (in_length>>1)/*int /2*/) {
  23835. // return true;
  23836. // }
  23837. // }
  23838. //#endif
  23839. return (s.last_lit === s.lit_bufsize-1);
  23840. /* We avoid equality with lit_bufsize because of wraparound at 64K
  23841. * on 16 bit machines and because stored blocks are restricted to
  23842. * 64K-1 bytes.
  23843. */
  23844. }
  23845. exports._tr_init = _tr_init;
  23846. exports._tr_stored_block = _tr_stored_block;
  23847. exports._tr_flush_block = _tr_flush_block;
  23848. exports._tr_tally = _tr_tally;
  23849. exports._tr_align = _tr_align;
  23850. },{"../utils/common":69}],81:[function(require,module,exports){
  23851. 'use strict';
  23852. function ZStream() {
  23853. /* next input byte */
  23854. this.input = null; // JS specific, because we have no pointers
  23855. this.next_in = 0;
  23856. /* number of bytes available at input */
  23857. this.avail_in = 0;
  23858. /* total number of input bytes read so far */
  23859. this.total_in = 0;
  23860. /* next output byte should be put there */
  23861. this.output = null; // JS specific, because we have no pointers
  23862. this.next_out = 0;
  23863. /* remaining free space at output */
  23864. this.avail_out = 0;
  23865. /* total number of bytes output so far */
  23866. this.total_out = 0;
  23867. /* last error message, NULL if no error */
  23868. this.msg = ''/*Z_NULL*/;
  23869. /* not visible by applications */
  23870. this.state = null;
  23871. /* best guess about the data type: binary or text */
  23872. this.data_type = 2/*Z_UNKNOWN*/;
  23873. /* adler32 value of the uncompressed data */
  23874. this.adler = 0;
  23875. }
  23876. module.exports = ZStream;
  23877. },{}],82:[function(require,module,exports){
  23878. module.exports = function arrayEquals(array) {
  23879. // if the other array is a falsy value, return
  23880. if (!array)
  23881. return false;
  23882. // compare lengths - can save a lot of time
  23883. if (this.length != array.length)
  23884. return false;
  23885. for (var i = 0, l = this.length; i < l; i++) {
  23886. // Check if we have nested arrays
  23887. if (this[i] instanceof Array && array[i] instanceof Array) {
  23888. // recurse into the nested arrays
  23889. if (!arrayEquals.apply(this[i], [array[i]]))
  23890. return false;
  23891. } else if (this[i] != array[i]) {
  23892. // Warning - two different object instances will never be equal:
  23893. // {x:20} != {x:20}
  23894. return false;
  23895. }
  23896. }
  23897. return true;
  23898. }
  23899. },{}],83:[function(require,module,exports){
  23900. exports.Interop = require('./interop');
  23901. },{"./interop":84}],84:[function(require,module,exports){
  23902. var transform = require('./transform');
  23903. var arrayEquals = require('./array-equals');
  23904. function Interop() { }
  23905. module.exports = Interop;
  23906. /**
  23907. * This map holds the most recent Plan A offer/answer SDP that was converted
  23908. * to Plan B, with the SDP type ('offer' or 'answer') as keys and the SDP
  23909. * string as values.
  23910. *
  23911. * @type {{}}
  23912. */
  23913. var cache = {};
  23914. /**
  23915. * This method transforms a Plan A SDP to an equivalent Plan B SDP. A
  23916. * PeerConnection wrapper transforms the SDP to Plan B before passing it to the
  23917. * application.
  23918. *
  23919. * @param desc
  23920. * @returns {*}
  23921. */
  23922. Interop.prototype.toPlanB = function(desc) {
  23923. //#region Preliminary input validation.
  23924. if (typeof desc !== 'object' || desc === null ||
  23925. typeof desc.sdp !== 'string') {
  23926. console.warn('An empty description was passed as an argument.');
  23927. return desc;
  23928. }
  23929. // Objectify the SDP for easier manipulation.
  23930. var session = transform.parse(desc.sdp);
  23931. // If the SDP contains no media, there's nothing to transform.
  23932. if (typeof session.media === 'undefined' ||
  23933. !Array.isArray(session.media) || session.media.length === 0) {
  23934. console.warn('The description has no media.');
  23935. return desc;
  23936. }
  23937. // Try some heuristics to "make sure" this is a Plan A SDP. Plan B SDP has
  23938. // a video, an audio and a data "channel" at most.
  23939. if (session.media.length <= 3 && session.media.every(function(m) {
  23940. return ['video', 'audio', 'data'].indexOf(m.mid) !== -1;
  23941. })) {
  23942. console.warn('This description does not look like Plan A.');
  23943. return desc;
  23944. }
  23945. //#endregion
  23946. // Plan A SDP is our "precious". Cache it for later use in the Plan B ->
  23947. // Plan A transformation.
  23948. cache[desc.type] = desc.sdp;
  23949. //#region Convert from Plan A to Plan B.
  23950. // We rebuild the session.media array.
  23951. var media = session.media;
  23952. session.media = [];
  23953. // Associative array that maps channel types to channel objects for fast
  23954. // access to channel objects by their type, e.g. channels['audio']->channel
  23955. // obj.
  23956. var channels = {};
  23957. // Used to build the group:BUNDLE value after the channels construction
  23958. // loop.
  23959. var types = [];
  23960. // Implode the Plan A m-lines/tracks into Plan B "channels".
  23961. media.forEach(function(mLine) {
  23962. // rtcp-mux is required in the Plan B SDP.
  23963. if (typeof mLine.rtcpMux !== 'string' ||
  23964. mLine.rtcpMux !== 'rtcp-mux') {
  23965. throw new Error('Cannot convert to Plan B because m-lines ' +
  23966. 'without the rtcp-mux attribute were found.');
  23967. }
  23968. // If we don't have a channel for this mLine.type, then use this mLine
  23969. // as the channel basis.
  23970. if (typeof channels[mLine.type] === 'undefined') {
  23971. channels[mLine.type] = mLine;
  23972. }
  23973. // Add sources to the channel and handle a=msid.
  23974. if (typeof mLine.sources === 'object') {
  23975. Object.keys(mLine.sources).forEach(function(ssrc) {
  23976. // Assign the sources to the channel.
  23977. channels[mLine.type].sources[ssrc] = mLine.sources[ssrc];
  23978. // In Plan B the msid is an SSRC attribute. Also, we don't care
  23979. // about the obsolete label and mslabel attributes.
  23980. channels[mLine.type].sources[ssrc].msid = mLine.msid;
  23981. // NOTE ssrcs in ssrc groups will share msids, as
  23982. // draft-uberti-rtcweb-plan-00 mandates.
  23983. });
  23984. }
  23985. // Add ssrc groups to the channel.
  23986. if (typeof mLine.ssrcGroups !== 'undefined' &&
  23987. Array.isArray(mLine.ssrcGroups)) {
  23988. // Create the ssrcGroups array, if it's not defined.
  23989. if (typeof channel.ssrcGroups === 'undefined' ||
  23990. !Array.isArray(channel.ssrcGroups)) {
  23991. channel.ssrcGroups = [];
  23992. }
  23993. channel.ssrcGroups = channel.ssrcGroups.concat(mLine.ssrcGroups);
  23994. }
  23995. if (channels[mLine.type] === mLine) {
  23996. // Copy ICE related stuff from the principal media line.
  23997. mLine.candidates = media[0].candidates;
  23998. mLine.iceUfrag = media[0].iceUfrag;
  23999. mLine.icePwd = media[0].icePwd;
  24000. mLine.fingerprint = media[0].fingerprint;
  24001. // Plan B mids are in ['audio', 'video', 'data']
  24002. mLine.mid = mLine.type;
  24003. // Plan B doesn't support/need the bundle-only attribute.
  24004. delete mLine.bundleOnly;
  24005. // In Plan B the msid is an SSRC attribute.
  24006. delete mLine.msid;
  24007. // Used to build the group:BUNDLE value after this loop.
  24008. types.push(mLine.type);
  24009. // Add the channel to the new media array.
  24010. session.media.push(mLine);
  24011. }
  24012. });
  24013. // We regenerate the BUNDLE group with the new mids.
  24014. session.groups.every(function(group) {
  24015. if (group.type === 'BUNDLE') {
  24016. group.mids = types.join(' ');
  24017. return false;
  24018. } else {
  24019. return true;
  24020. }
  24021. });
  24022. // msid semantic
  24023. session.msidSemantic = {
  24024. semantic: 'WMS',
  24025. token: '*'
  24026. };
  24027. var resStr = transform.write(session);
  24028. return new RTCSessionDescription({
  24029. type: desc.type,
  24030. sdp: resStr
  24031. });
  24032. //#endregion
  24033. };
  24034. /**
  24035. * This method transforms a Plan B SDP to an equivalent Plan A SDP. A
  24036. * PeerConnection wrapper transforms the SDP to Plan A before passing it to FF.
  24037. *
  24038. * @param desc
  24039. * @returns {*}
  24040. */
  24041. Interop.prototype.toPlanA = function(desc) {
  24042. //#region Preliminary input validation.
  24043. if (typeof desc !== 'object' || desc === null ||
  24044. typeof desc.sdp !== 'string') {
  24045. console.warn('An empty description was passed as an argument.');
  24046. return desc;
  24047. }
  24048. var session = transform.parse(desc.sdp);
  24049. // If the SDP contains no media, there's nothing to transform.
  24050. if (typeof session.media === 'undefined' ||
  24051. !Array.isArray(session.media) || session.media.length === 0) {
  24052. console.warn('The description has no media.');
  24053. return desc;
  24054. }
  24055. // Try some heuristics to "make sure" this is a Plan B SDP. Plan B SDP has
  24056. // a video, an audio and a data "channel" at most.
  24057. if (session.media.length > 3 || !session.media.every(function(m) {
  24058. return ['video', 'audio', 'data'].indexOf(m.mid) !== -1;
  24059. })) {
  24060. console.warn('This description does not look like Plan B.');
  24061. return desc;
  24062. }
  24063. // Make sure this Plan B SDP can be converted to a Plan A SDP.
  24064. var mids = [];
  24065. session.media.forEach(function(m) {
  24066. mids.push(m.mid);
  24067. });
  24068. var hasBundle = false;
  24069. if (typeof session.groups !== 'undefined' &&
  24070. Array.isArray(session.groups)) {
  24071. hasBundle = session.groups.every(function(g) {
  24072. return g.type !== 'BUNDLE' ||
  24073. arrayEquals.apply(g.mids.sort(), [mids.sort()]);
  24074. });
  24075. }
  24076. if (!hasBundle) {
  24077. throw new Error("Cannot convert to Plan A because m-lines that are " +
  24078. "not bundled were found.");
  24079. }
  24080. //#endregion
  24081. //#region Convert from Plan B to Plan A.
  24082. // Unfortunately, a Plan B offer/answer doesn't have enough information to
  24083. // rebuild an equivalent Plan A offer/answer.
  24084. //
  24085. // For example, if this is a local answer (in Plan A style) that we convert
  24086. // to Plan B prior to handing it over to the application (the
  24087. // PeerConnection wrapper called us, for instance, after a successful
  24088. // createAnswer), we want to remember the m-line at which we've seen the
  24089. // (local) SSRC. That's because when the application wants to do call the
  24090. // SLD method, forcing us to do the inverse transformation (from Plan B to
  24091. // Plan A), we need to know to which m-line to assign the (local) SSRC. We
  24092. // also need to know all the other m-lines that the original answer had and
  24093. // include them in the transformed answer as well.
  24094. //
  24095. // Another example is if this is a remote offer that we convert to Plan B
  24096. // prior to giving it to the application, we want to remember the mid at
  24097. // which we've seen the (remote) SSRC.
  24098. //
  24099. // In the iteration that follows, we use the cached Plan A (if it exists)
  24100. // to assign mids to ssrcs.
  24101. var cached;
  24102. if (typeof cache[desc.type] !== 'undefined') {
  24103. cached = transform.parse(cache[desc.type]);
  24104. }
  24105. // A helper map that sends mids to m-line objects. We use it later to
  24106. // rebuild the Plan A style session.media array.
  24107. var media = {};
  24108. session.media.forEach(function(channel) {
  24109. if (typeof channel.rtcpMux !== 'string' ||
  24110. channel.rtcpMux !== 'rtcp-mux') {
  24111. throw new Error("Cannot convert to Plan A because m-lines " +
  24112. "without the rtcp-mux attribute were found.");
  24113. }
  24114. // With rtcp-mux and bundle all the channels should have the same ICE
  24115. // stuff.
  24116. var sources = channel.sources;
  24117. var ssrcGroups = channel.ssrcGroups;
  24118. var candidates = channel.candidates;
  24119. var iceUfrag = channel.iceUfrag;
  24120. var icePwd = channel.icePwd;
  24121. var fingerprint = channel.fingerprint;
  24122. var port = channel.port;
  24123. // We'll use the "channel" object as a prototype for each new "mLine"
  24124. // that we create, but first we need to clean it up a bit.
  24125. delete channel.sources;
  24126. delete channel.ssrcGroups;
  24127. delete channel.candidates;
  24128. delete channel.iceUfrag;
  24129. delete channel.icePwd;
  24130. delete channel.fingerprint;
  24131. delete channel.port;
  24132. delete channel.mid;
  24133. // inverted ssrc group map
  24134. var invertedGroups = {};
  24135. if (typeof ssrcGroups !== 'undefined' && Array.isArray(ssrcGroups)) {
  24136. ssrcGroups.forEach(function (ssrcGroup) {
  24137. // TODO(gp) find out how to receive simulcast with FF. For the
  24138. // time being, hide it.
  24139. if (ssrcGroup.semantics === 'SIM') {
  24140. return;
  24141. }
  24142. if (typeof ssrcGroup.ssrcs !== 'undefined' &&
  24143. Array.isArray(ssrcGroup.ssrcs)) {
  24144. ssrcGroup.ssrcs.forEach(function (ssrc) {
  24145. if (typeof invertedGroups[ssrc] === 'undefined') {
  24146. invertedGroups[ssrc] = [];
  24147. }
  24148. invertedGroups[ssrc].push(ssrcGroup);
  24149. });
  24150. }
  24151. });
  24152. }
  24153. // ssrc to m-line index.
  24154. var mLines = {};
  24155. if (typeof sources === 'object') {
  24156. // Explode the Plan B channel sources with one m-line per source.
  24157. Object.keys(sources).forEach(function(ssrc) {
  24158. var mLine;
  24159. if (typeof invertedGroups[ssrc] !== 'undefined' &&
  24160. Array.isArray(invertedGroups[ssrc])) {
  24161. invertedGroups[ssrc].every(function (ssrcGroup) {
  24162. // ssrcGroup.ssrcs *is* an Array, no need to check
  24163. // again here.
  24164. return ssrcGroup.ssrcs.every(function (related) {
  24165. if (typeof mLines[related] === 'object') {
  24166. mLine = mLines[related];
  24167. return false;
  24168. } else {
  24169. return true;
  24170. }
  24171. });
  24172. });
  24173. }
  24174. if (typeof mLine === 'object') {
  24175. // the m-line already exists. Just add the source.
  24176. mLine.sources[ssrc] = sources[ssrc];
  24177. delete sources[ssrc].msid;
  24178. } else {
  24179. // Use the "channel" as a prototype for the "mLine".
  24180. mLine = Object.create(channel);
  24181. mLines[ssrc] = mLine;
  24182. // Assign the msid of the source to the m-line.
  24183. mLine.msid = sources[ssrc].msid;
  24184. delete sources[ssrc].msid;
  24185. // We assign one SSRC per media line.
  24186. mLine.sources = {};
  24187. mLine.sources[ssrc] = sources[ssrc];
  24188. mLine.ssrcGroups = invertedGroups[ssrc];
  24189. // Use the cached Plan A SDP (if it exists) to assign SSRCs to
  24190. // mids.
  24191. if (typeof cached !== 'undefined' &&
  24192. typeof cached.media !== 'undefined' &&
  24193. Array.isArray(cached.media)) {
  24194. cached.media.forEach(function(m) {
  24195. if (typeof m.sources === 'object') {
  24196. Object.keys(m.sources).forEach(function(s) {
  24197. if (s === ssrc) {
  24198. mLine.mid = m.mid;
  24199. }
  24200. });
  24201. }
  24202. });
  24203. }
  24204. if (typeof mLine.mid === 'undefined') {
  24205. // If this is an SSRC that we see for the first time assign
  24206. // it a new mid. This is typically the case when this
  24207. // method is called to transform a remote description for
  24208. // the first time or when there is a new SSRC in the remote
  24209. // description because a new peer has joined the
  24210. // conference. Local SSRCs should have already been added
  24211. // to the map in the toPlanB method.
  24212. //
  24213. // Because FF generates answers in Plan A style, we MUST
  24214. // already have a cached answer with all the local SSRCs
  24215. // mapped to some mLine/mid.
  24216. if (desc.type === 'answer') {
  24217. throw new Error("An unmapped SSRC was found.");
  24218. }
  24219. mLine.mid = [channel.type, '-', ssrc].join('');
  24220. }
  24221. // Include the candidates in the 1st media line.
  24222. mLine.candidates = candidates;
  24223. mLine.iceUfrag = iceUfrag;
  24224. mLine.icePwd = icePwd;
  24225. mLine.fingerprint = fingerprint;
  24226. mLine.port = port;
  24227. media[mLine.mid] = mLine;
  24228. }
  24229. });
  24230. }
  24231. });
  24232. // Rebuild the media array in the right order and add the missing mLines
  24233. // (missing from the Plan B SDP).
  24234. session.media = [];
  24235. mids = []; // reuse
  24236. if (desc.type === 'answer') {
  24237. // The media lines in the answer must match the media lines in the
  24238. // offer. The order is important too. Here we use the cached offer to
  24239. // find the m-lines that are missing (from the converted answer), and
  24240. // use the cached answer to complete the converted answer.
  24241. if (typeof cache['offer'] === 'undefined') {
  24242. throw new Error("An answer is being processed but we couldn't " +
  24243. "find a cached offer.");
  24244. }
  24245. var cachedOffer = transform.parse(cache['offer']);
  24246. if (typeof cachedOffer === 'undefined' ||
  24247. typeof cachedOffer.media === 'undefined' ||
  24248. !Array.isArray(cachedOffer.media)) {
  24249. // FIXME(gp) is this really a problem in the general case?
  24250. throw new Error("The cached offer has no media.");
  24251. }
  24252. cachedOffer.media.forEach(function(mo) {
  24253. var mLine;
  24254. if (typeof media[mo.mid] === 'undefined') {
  24255. // This is probably an m-line containing a remote track only.
  24256. // It MUST exist in the cached answer as a remote track only
  24257. // mLine.
  24258. cached.media.every(function(ma) {
  24259. if (mo.mid == ma.mid) {
  24260. mLine = ma;
  24261. return false;
  24262. } else {
  24263. return true;
  24264. }
  24265. });
  24266. } else {
  24267. mLine = media[mo.mid];
  24268. }
  24269. if (typeof mLine === 'undefined') {
  24270. throw new Error("The cached offer contains an m-line that " +
  24271. "doesn't exist neither in the cached answer nor in " +
  24272. "the converted answer.");
  24273. }
  24274. session.media.push(mLine);
  24275. mids.push(mLine.mid);
  24276. });
  24277. } else {
  24278. // SDP offer/answer (and the JSEP spec) forbids removing an m-section
  24279. // under any circumstances. If we are no longer interested in sending a
  24280. // track, we just remove the msid and ssrc attributes and set it to
  24281. // either a=recvonly (as the reofferer, we must use recvonly if the
  24282. // other side was previously sending on the m-section, but we can also
  24283. // leave the possibility open if it wasn't previously in use), or
  24284. // a=inacive.
  24285. if (typeof cached !== 'undefined' &&
  24286. typeof cached.media !== 'undefined' &&
  24287. Array.isArray(cached.media)) {
  24288. cached.media.forEach(function(pm) {
  24289. mids.push(pm.mid);
  24290. if (typeof media[pm.mid] !== 'undefined') {
  24291. session.media.push(media[pm.mid]);
  24292. } else {
  24293. delete pm.msid;
  24294. delete pm.sources;
  24295. delete pm.ssrcGroups;
  24296. pm.direction = 'recvonly';
  24297. session.media.push(pm);
  24298. }
  24299. });
  24300. }
  24301. // Add all the remaining (new) m-lines of the transformed SDP.
  24302. Object.keys(media).forEach(function(mid) {
  24303. if (mids.indexOf(mid) === -1) {
  24304. mids.push(mid);
  24305. session.media.push(media[mid]);
  24306. }
  24307. });
  24308. }
  24309. // We regenerate the BUNDLE group (since we regenerated the mids)
  24310. session.groups.every(function(group) {
  24311. if (group.type === 'BUNDLE') {
  24312. group.mids = mids.join(' ');
  24313. return false;
  24314. } else {
  24315. return true;
  24316. }
  24317. });
  24318. // msid semantic
  24319. session.msidSemantic = {
  24320. semantic: 'WMS',
  24321. token: '*'
  24322. };
  24323. var resStr = transform.write(session);
  24324. // Cache the transformed SDP (Plan A) for later re-use in this function.
  24325. cache[desc.type] = resStr;
  24326. return new RTCSessionDescription({
  24327. type: desc.type,
  24328. sdp: resStr
  24329. });
  24330. //#endregion
  24331. };
  24332. },{"./array-equals":82,"./transform":85}],85:[function(require,module,exports){
  24333. var transform = require('sdp-transform');
  24334. exports.write = function(session, opts) {
  24335. if (typeof session !== 'undefined' &&
  24336. typeof session.media !== 'undefined' &&
  24337. Array.isArray(session.media)) {
  24338. session.media.forEach(function (mLine) {
  24339. // expand sources to ssrcs
  24340. if (typeof mLine.sources !== 'undefined' &&
  24341. Object.keys(mLine.sources).length !== 0) {
  24342. mLine.ssrcs = [];
  24343. Object.keys(mLine.sources).forEach(function (ssrc) {
  24344. var source = mLine.sources[ssrc];
  24345. Object.keys(source).forEach(function (attribute) {
  24346. mLine.ssrcs.push({
  24347. id: ssrc,
  24348. attribute: attribute,
  24349. value: source[attribute]
  24350. });
  24351. });
  24352. });
  24353. delete mLine.sources;
  24354. }
  24355. // join ssrcs in ssrc groups
  24356. if (typeof mLine.ssrcGroups !== 'undefined' &&
  24357. Array.isArray(mLine.ssrcGroups)) {
  24358. mLine.ssrcGroups.forEach(function (ssrcGroup) {
  24359. if (typeof ssrcGroup.ssrcs !== 'undefined' &&
  24360. Array.isArray(ssrcGroup.ssrcs)) {
  24361. ssrcGroup.ssrcs = ssrcGroup.ssrcs.join(' ');
  24362. }
  24363. });
  24364. }
  24365. });
  24366. }
  24367. // join group mids
  24368. if (typeof session !== 'undefined' &&
  24369. typeof session.groups !== 'undefined' && Array.isArray(session.groups)) {
  24370. session.groups.forEach(function (g) {
  24371. if (typeof g.mids !== 'undefined' && Array.isArray(g.mids)) {
  24372. g.mids = g.mids.join(' ');
  24373. }
  24374. });
  24375. }
  24376. return transform.write(session, opts);
  24377. };
  24378. exports.parse = function(sdp) {
  24379. var session = transform.parse(sdp);
  24380. if (typeof session !== 'undefined' && typeof session.media !== 'undefined' &&
  24381. Array.isArray(session.media)) {
  24382. session.media.forEach(function (mLine) {
  24383. // group sources attributes by ssrc
  24384. if (typeof mLine.ssrcs !== 'undefined' && Array.isArray(mLine.ssrcs)) {
  24385. mLine.sources = {};
  24386. mLine.ssrcs.forEach(function (ssrc) {
  24387. if (!mLine.sources[ssrc.id])
  24388. mLine.sources[ssrc.id] = {};
  24389. mLine.sources[ssrc.id][ssrc.attribute] = ssrc.value;
  24390. });
  24391. delete mLine.ssrcs;
  24392. }
  24393. // split ssrcs in ssrc groups
  24394. if (typeof mLine.ssrcGroups !== 'undefined' &&
  24395. Array.isArray(mLine.ssrcGroups)) {
  24396. mLine.ssrcGroups.forEach(function (ssrcGroup) {
  24397. if (typeof ssrcGroup.ssrcs === 'string') {
  24398. ssrcGroup.ssrcs = ssrcGroup.ssrcs.split(' ');
  24399. }
  24400. });
  24401. }
  24402. });
  24403. }
  24404. // split group mids
  24405. if (typeof session !== 'undefined' &&
  24406. typeof session.groups !== 'undefined' && Array.isArray(session.groups)) {
  24407. session.groups.forEach(function (g) {
  24408. if (typeof g.mids === 'string') {
  24409. g.mids = g.mids.split(' ');
  24410. }
  24411. });
  24412. }
  24413. return session;
  24414. };
  24415. },{"sdp-transform":87}],86:[function(require,module,exports){
  24416. var grammar = module.exports = {
  24417. v: [{
  24418. name: 'version',
  24419. reg: /^(\d*)$/
  24420. }],
  24421. o: [{ //o=- 20518 0 IN IP4 203.0.113.1
  24422. // NB: sessionId will be a String in most cases because it is huge
  24423. name: 'origin',
  24424. reg: /^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/,
  24425. names: ['username', 'sessionId', 'sessionVersion', 'netType', 'ipVer', 'address'],
  24426. format: "%s %s %d %s IP%d %s"
  24427. }],
  24428. // default parsing of these only (though some of these feel outdated)
  24429. s: [{ name: 'name' }],
  24430. i: [{ name: 'description' }],
  24431. u: [{ name: 'uri' }],
  24432. e: [{ name: 'email' }],
  24433. p: [{ name: 'phone' }],
  24434. z: [{ name: 'timezones' }], // TODO: this one can actually be parsed properly..
  24435. r: [{ name: 'repeats' }], // TODO: this one can also be parsed properly
  24436. //k: [{}], // outdated thing ignored
  24437. t: [{ //t=0 0
  24438. name: 'timing',
  24439. reg: /^(\d*) (\d*)/,
  24440. names: ['start', 'stop'],
  24441. format: "%d %d"
  24442. }],
  24443. c: [{ //c=IN IP4 10.47.197.26
  24444. name: 'connection',
  24445. reg: /^IN IP(\d) (\S*)/,
  24446. names: ['version', 'ip'],
  24447. format: "IN IP%d %s"
  24448. }],
  24449. b: [{ //b=AS:4000
  24450. push: 'bandwidth',
  24451. reg: /^(TIAS|AS|CT|RR|RS):(\d*)/,
  24452. names: ['type', 'limit'],
  24453. format: "%s:%s"
  24454. }],
  24455. m: [{ //m=video 51744 RTP/AVP 126 97 98 34 31
  24456. // NB: special - pushes to session
  24457. // TODO: rtp/fmtp should be filtered by the payloads found here?
  24458. reg: /^(\w*) (\d*) ([\w\/]*)(?: (.*))?/,
  24459. names: ['type', 'port', 'protocol', 'payloads'],
  24460. format: "%s %d %s %s"
  24461. }],
  24462. a: [
  24463. { //a=rtpmap:110 opus/48000/2
  24464. push: 'rtp',
  24465. reg: /^rtpmap:(\d*) ([\w\-]*)\/(\d*)(?:\s*\/(\S*))?/,
  24466. names: ['payload', 'codec', 'rate', 'encoding'],
  24467. format: function (o) {
  24468. return (o.encoding) ?
  24469. "rtpmap:%d %s/%s/%s":
  24470. "rtpmap:%d %s/%s";
  24471. }
  24472. },
  24473. { //a=fmtp:108 profile-level-id=24;object=23;bitrate=64000
  24474. push: 'fmtp',
  24475. reg: /^fmtp:(\d*) (\S*)/,
  24476. names: ['payload', 'config'],
  24477. format: "fmtp:%d %s"
  24478. },
  24479. { //a=control:streamid=0
  24480. name: 'control',
  24481. reg: /^control:(.*)/,
  24482. format: "control:%s"
  24483. },
  24484. { //a=rtcp:65179 IN IP4 193.84.77.194
  24485. name: 'rtcp',
  24486. reg: /^rtcp:(\d*)(?: (\S*) IP(\d) (\S*))?/,
  24487. names: ['port', 'netType', 'ipVer', 'address'],
  24488. format: function (o) {
  24489. return (o.address != null) ?
  24490. "rtcp:%d %s IP%d %s":
  24491. "rtcp:%d";
  24492. }
  24493. },
  24494. { //a=rtcp-fb:98 trr-int 100
  24495. push: 'rtcpFbTrrInt',
  24496. reg: /^rtcp-fb:(\*|\d*) trr-int (\d*)/,
  24497. names: ['payload', 'value'],
  24498. format: "rtcp-fb:%d trr-int %d"
  24499. },
  24500. { //a=rtcp-fb:98 nack rpsi
  24501. push: 'rtcpFb',
  24502. reg: /^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,
  24503. names: ['payload', 'type', 'subtype'],
  24504. format: function (o) {
  24505. return (o.subtype != null) ?
  24506. "rtcp-fb:%s %s %s":
  24507. "rtcp-fb:%s %s";
  24508. }
  24509. },
  24510. { //a=extmap:2 urn:ietf:params:rtp-hdrext:toffset
  24511. //a=extmap:1/recvonly URI-gps-string
  24512. push: 'ext',
  24513. reg: /^extmap:([\w_\/]*) (\S*)(?: (\S*))?/,
  24514. names: ['value', 'uri', 'config'], // value may include "/direction" suffix
  24515. format: function (o) {
  24516. return (o.config != null) ?
  24517. "extmap:%s %s %s":
  24518. "extmap:%s %s";
  24519. }
  24520. },
  24521. {
  24522. //a=crypto:1 AES_CM_128_HMAC_SHA1_80 inline:PS1uQCVeeCFCanVmcjkpPywjNWhcYD0mXXtxaVBR|2^20|1:32
  24523. push: 'crypto',
  24524. reg: /^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,
  24525. names: ['id', 'suite', 'config', 'sessionConfig'],
  24526. format: function (o) {
  24527. return (o.sessionConfig != null) ?
  24528. "crypto:%d %s %s %s":
  24529. "crypto:%d %s %s";
  24530. }
  24531. },
  24532. { //a=setup:actpass
  24533. name: 'setup',
  24534. reg: /^setup:(\w*)/,
  24535. format: "setup:%s"
  24536. },
  24537. { //a=mid:1
  24538. name: 'mid',
  24539. reg: /^mid:([^\s]*)/,
  24540. format: "mid:%s"
  24541. },
  24542. { //a=msid:0c8b064d-d807-43b4-b434-f92a889d8587 98178685-d409-46e0-8e16-7ef0db0db64a
  24543. name: 'msid',
  24544. reg: /^msid:(.*)/,
  24545. format: "msid:%s"
  24546. },
  24547. { //a=ptime:20
  24548. name: 'ptime',
  24549. reg: /^ptime:(\d*)/,
  24550. format: "ptime:%d"
  24551. },
  24552. { //a=maxptime:60
  24553. name: 'maxptime',
  24554. reg: /^maxptime:(\d*)/,
  24555. format: "maxptime:%d"
  24556. },
  24557. { //a=sendrecv
  24558. name: 'direction',
  24559. reg: /^(sendrecv|recvonly|sendonly|inactive)/
  24560. },
  24561. { //a=ice-lite
  24562. name: 'icelite',
  24563. reg: /^(ice-lite)/
  24564. },
  24565. { //a=ice-ufrag:F7gI
  24566. name: 'iceUfrag',
  24567. reg: /^ice-ufrag:(\S*)/,
  24568. format: "ice-ufrag:%s"
  24569. },
  24570. { //a=ice-pwd:x9cml/YzichV2+XlhiMu8g
  24571. name: 'icePwd',
  24572. reg: /^ice-pwd:(\S*)/,
  24573. format: "ice-pwd:%s"
  24574. },
  24575. { //a=fingerprint:SHA-1 00:11:22:33:44:55:66:77:88:99:AA:BB:CC:DD:EE:FF:00:11:22:33
  24576. name: 'fingerprint',
  24577. reg: /^fingerprint:(\S*) (\S*)/,
  24578. names: ['type', 'hash'],
  24579. format: "fingerprint:%s %s"
  24580. },
  24581. {
  24582. //a=candidate:0 1 UDP 2113667327 203.0.113.1 54400 typ host
  24583. //a=candidate:1162875081 1 udp 2113937151 192.168.34.75 60017 typ host generation 0
  24584. //a=candidate:3289912957 2 udp 1845501695 193.84.77.194 60017 typ srflx raddr 192.168.34.75 rport 60017 generation 0
  24585. push:'candidates',
  24586. reg: /^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: generation (\d*))?/,
  24587. names: ['foundation', 'component', 'transport', 'priority', 'ip', 'port', 'type', 'raddr', 'rport', 'generation'],
  24588. format: function (o) {
  24589. var str = "candidate:%s %d %s %d %s %d typ %s";
  24590. // NB: candidate has two optional chunks, so %void middle one if it's missing
  24591. str += (o.raddr != null) ? " raddr %s rport %d" : "%v%v";
  24592. if (o.generation != null) {
  24593. str += " generation %d";
  24594. }
  24595. return str;
  24596. }
  24597. },
  24598. { //a=end-of-candidates (keep after the candidates line for readability)
  24599. name: 'endOfCandidates',
  24600. reg: /^(end-of-candidates)/
  24601. },
  24602. { //a=remote-candidates:1 203.0.113.1 54400 2 203.0.113.1 54401 ...
  24603. name: 'remoteCandidates',
  24604. reg: /^remote-candidates:(.*)/,
  24605. format: "remote-candidates:%s"
  24606. },
  24607. { //a=ice-options:google-ice
  24608. name: 'iceOptions',
  24609. reg: /^ice-options:(\S*)/,
  24610. format: "ice-options:%s"
  24611. },
  24612. { //a=ssrc:2566107569 cname:t9YU8M1UxTF8Y1A1
  24613. push: "ssrcs",
  24614. reg: /^ssrc:(\d*) ([\w_]*):(.*)/,
  24615. names: ['id', 'attribute', 'value'],
  24616. format: "ssrc:%d %s:%s"
  24617. },
  24618. { //a=ssrc-group:FEC 1 2
  24619. push: "ssrcGroups",
  24620. reg: /^ssrc-group:(\w*) (.*)/,
  24621. names: ['semantics', 'ssrcs'],
  24622. format: "ssrc-group:%s %s"
  24623. },
  24624. { //a=msid-semantic: WMS Jvlam5X3SX1OP6pn20zWogvaKJz5Hjf9OnlV
  24625. name: "msidSemantic",
  24626. reg: /^msid-semantic:\s?(\w*) (\S*)/,
  24627. names: ['semantic', 'token'],
  24628. format: "msid-semantic: %s %s" // space after ":" is not accidental
  24629. },
  24630. { //a=group:BUNDLE audio video
  24631. push: 'groups',
  24632. reg: /^group:(\w*) (.*)/,
  24633. names: ['type', 'mids'],
  24634. format: "group:%s %s"
  24635. },
  24636. { //a=rtcp-mux
  24637. name: 'rtcpMux',
  24638. reg: /^(rtcp-mux)/
  24639. },
  24640. { // any a= that we don't understand is kepts verbatim on media.invalid
  24641. push: 'invalid',
  24642. names: ["value"]
  24643. }
  24644. ]
  24645. };
  24646. // set sensible defaults to avoid polluting the grammar with boring details
  24647. Object.keys(grammar).forEach(function (key) {
  24648. var objs = grammar[key];
  24649. objs.forEach(function (obj) {
  24650. if (!obj.reg) {
  24651. obj.reg = /(.*)/;
  24652. }
  24653. if (!obj.format) {
  24654. obj.format = "%s";
  24655. }
  24656. });
  24657. });
  24658. },{}],87:[function(require,module,exports){
  24659. var parser = require('./parser');
  24660. var writer = require('./writer');
  24661. exports.write = writer;
  24662. exports.parse = parser.parse;
  24663. exports.parseFmtpConfig = parser.parseFmtpConfig;
  24664. exports.parsePayloads = parser.parsePayloads;
  24665. exports.parseRemoteCandidates = parser.parseRemoteCandidates;
  24666. },{"./parser":88,"./writer":89}],88:[function(require,module,exports){
  24667. var toIntIfInt = function (v) {
  24668. return String(Number(v)) === v ? Number(v) : v;
  24669. };
  24670. var attachProperties = function (match, location, names, rawName) {
  24671. if (rawName && !names) {
  24672. location[rawName] = toIntIfInt(match[1]);
  24673. }
  24674. else {
  24675. for (var i = 0; i < names.length; i += 1) {
  24676. if (match[i+1] != null) {
  24677. location[names[i]] = toIntIfInt(match[i+1]);
  24678. }
  24679. }
  24680. }
  24681. };
  24682. var parseReg = function (obj, location, content) {
  24683. var needsBlank = obj.name && obj.names;
  24684. if (obj.push && !location[obj.push]) {
  24685. location[obj.push] = [];
  24686. }
  24687. else if (needsBlank && !location[obj.name]) {
  24688. location[obj.name] = {};
  24689. }
  24690. var keyLocation = obj.push ?
  24691. {} : // blank object that will be pushed
  24692. needsBlank ? location[obj.name] : location; // otherwise, named location or root
  24693. attachProperties(content.match(obj.reg), keyLocation, obj.names, obj.name);
  24694. if (obj.push) {
  24695. location[obj.push].push(keyLocation);
  24696. }
  24697. };
  24698. var grammar = require('./grammar');
  24699. var validLine = RegExp.prototype.test.bind(/^([a-z])=(.*)/);
  24700. exports.parse = function (sdp) {
  24701. var session = {}
  24702. , media = []
  24703. , location = session; // points at where properties go under (one of the above)
  24704. // parse lines we understand
  24705. sdp.split(/(\r\n|\r|\n)/).filter(validLine).forEach(function (l) {
  24706. var type = l[0];
  24707. var content = l.slice(2);
  24708. if (type === 'm') {
  24709. media.push({rtp: [], fmtp: []});
  24710. location = media[media.length-1]; // point at latest media line
  24711. }
  24712. for (var j = 0; j < (grammar[type] || []).length; j += 1) {
  24713. var obj = grammar[type][j];
  24714. if (obj.reg.test(content)) {
  24715. return parseReg(obj, location, content);
  24716. }
  24717. }
  24718. });
  24719. session.media = media; // link it up
  24720. return session;
  24721. };
  24722. var fmtpReducer = function (acc, expr) {
  24723. var s = expr.split('=');
  24724. if (s.length === 2) {
  24725. acc[s[0]] = toIntIfInt(s[1]);
  24726. }
  24727. return acc;
  24728. };
  24729. exports.parseFmtpConfig = function (str) {
  24730. return str.split(';').reduce(fmtpReducer, {});
  24731. };
  24732. exports.parsePayloads = function (str) {
  24733. return str.split(' ').map(Number);
  24734. };
  24735. exports.parseRemoteCandidates = function (str) {
  24736. var candidates = [];
  24737. var parts = str.split(' ').map(toIntIfInt);
  24738. for (var i = 0; i < parts.length; i += 3) {
  24739. candidates.push({
  24740. component: parts[i],
  24741. ip: parts[i + 1],
  24742. port: parts[i + 2]
  24743. });
  24744. }
  24745. return candidates;
  24746. };
  24747. },{"./grammar":86}],89:[function(require,module,exports){
  24748. var grammar = require('./grammar');
  24749. // customized util.format - discards excess arguments and can void middle ones
  24750. var formatRegExp = /%[sdv%]/g;
  24751. var format = function (formatStr) {
  24752. var i = 1;
  24753. var args = arguments;
  24754. var len = args.length;
  24755. return formatStr.replace(formatRegExp, function (x) {
  24756. if (i >= len) {
  24757. return x; // missing argument
  24758. }
  24759. var arg = args[i];
  24760. i += 1;
  24761. switch (x) {
  24762. case '%%':
  24763. return '%';
  24764. case '%s':
  24765. return String(arg);
  24766. case '%d':
  24767. return Number(arg);
  24768. case '%v':
  24769. return '';
  24770. }
  24771. });
  24772. // NB: we discard excess arguments - they are typically undefined from makeLine
  24773. };
  24774. var makeLine = function (type, obj, location) {
  24775. var str = obj.format instanceof Function ?
  24776. (obj.format(obj.push ? location : location[obj.name])) :
  24777. obj.format;
  24778. var args = [type + '=' + str];
  24779. if (obj.names) {
  24780. for (var i = 0; i < obj.names.length; i += 1) {
  24781. var n = obj.names[i];
  24782. if (obj.name) {
  24783. args.push(location[obj.name][n]);
  24784. }
  24785. else { // for mLine and push attributes
  24786. args.push(location[obj.names[i]]);
  24787. }
  24788. }
  24789. }
  24790. else {
  24791. args.push(location[obj.name]);
  24792. }
  24793. return format.apply(null, args);
  24794. };
  24795. // RFC specified order
  24796. // TODO: extend this with all the rest
  24797. var defaultOuterOrder = [
  24798. 'v', 'o', 's', 'i',
  24799. 'u', 'e', 'p', 'c',
  24800. 'b', 't', 'r', 'z', 'a'
  24801. ];
  24802. var defaultInnerOrder = ['i', 'c', 'b', 'a'];
  24803. module.exports = function (session, opts) {
  24804. opts = opts || {};
  24805. // ensure certain properties exist
  24806. if (session.version == null) {
  24807. session.version = 0; // "v=0" must be there (only defined version atm)
  24808. }
  24809. if (session.name == null) {
  24810. session.name = " "; // "s= " must be there if no meaningful name set
  24811. }
  24812. session.media.forEach(function (mLine) {
  24813. if (mLine.payloads == null) {
  24814. mLine.payloads = "";
  24815. }
  24816. });
  24817. var outerOrder = opts.outerOrder || defaultOuterOrder;
  24818. var innerOrder = opts.innerOrder || defaultInnerOrder;
  24819. var sdp = [];
  24820. // loop through outerOrder for matching properties on session
  24821. outerOrder.forEach(function (type) {
  24822. grammar[type].forEach(function (obj) {
  24823. if (obj.name in session && session[obj.name] != null) {
  24824. sdp.push(makeLine(type, obj, session));
  24825. }
  24826. else if (obj.push in session && session[obj.push] != null) {
  24827. session[obj.push].forEach(function (el) {
  24828. sdp.push(makeLine(type, obj, el));
  24829. });
  24830. }
  24831. });
  24832. });
  24833. // then for each media line, follow the innerOrder
  24834. session.media.forEach(function (mLine) {
  24835. sdp.push(makeLine('m', grammar.m[0], mLine));
  24836. innerOrder.forEach(function (type) {
  24837. grammar[type].forEach(function (obj) {
  24838. if (obj.name in mLine && mLine[obj.name] != null) {
  24839. sdp.push(makeLine(type, obj, mLine));
  24840. }
  24841. else if (obj.push in mLine && mLine[obj.push] != null) {
  24842. mLine[obj.push].forEach(function (el) {
  24843. sdp.push(makeLine(type, obj, el));
  24844. });
  24845. }
  24846. });
  24847. });
  24848. });
  24849. return sdp.join('\r\n') + '\r\n';
  24850. };
  24851. },{"./grammar":86}],90:[function(require,module,exports){
  24852. var MediaStreamType = {
  24853. VIDEO_TYPE: "Video",
  24854. AUDIO_TYPE: "Audio"
  24855. };
  24856. module.exports = MediaStreamType;
  24857. },{}],91:[function(require,module,exports){
  24858. var RTCBrowserType = {
  24859. RTC_BROWSER_CHROME: "rtc_browser.chrome",
  24860. RTC_BROWSER_FIREFOX: "rtc_browser.firefox"
  24861. };
  24862. module.exports = RTCBrowserType;
  24863. },{}],92:[function(require,module,exports){
  24864. var RTCEvents = {
  24865. LASTN_CHANGED: "rtc.lastn_changed",
  24866. DOMINANTSPEAKER_CHANGED: "rtc.dominantspeaker_changed",
  24867. LASTN_ENDPOINT_CHANGED: "rtc.lastn_endpoint_changed",
  24868. SIMULCAST_LAYER_CHANGED: "rtc.simulcast_layer_changed",
  24869. SIMULCAST_LAYER_CHANGING: "rtc.simulcast_layer_changing",
  24870. SIMULCAST_START: "rtc.simlcast_start",
  24871. SIMULCAST_STOP: "rtc.simlcast_stop",
  24872. AVAILABLE_DEVICES_CHANGED: "rtc.available_devices_changed"
  24873. };
  24874. module.exports = RTCEvents;
  24875. },{}],93:[function(require,module,exports){
  24876. var Resolutions = {
  24877. "1080": {
  24878. width: 1920,
  24879. height: 1080,
  24880. order: 7
  24881. },
  24882. "fullhd": {
  24883. width: 1920,
  24884. height: 1080,
  24885. order: 7
  24886. },
  24887. "720": {
  24888. width: 1280,
  24889. height: 720,
  24890. order: 6
  24891. },
  24892. "hd": {
  24893. width: 1280,
  24894. height: 720,
  24895. order: 6
  24896. },
  24897. "960": {
  24898. width: 960,
  24899. height: 720,
  24900. order: 5
  24901. },
  24902. "640": {
  24903. width: 640,
  24904. height: 480,
  24905. order: 4
  24906. },
  24907. "vga": {
  24908. width: 640,
  24909. height: 480,
  24910. order: 4
  24911. },
  24912. "360": {
  24913. width: 640,
  24914. height: 360,
  24915. order: 3
  24916. },
  24917. "320": {
  24918. width: 320,
  24919. height: 240,
  24920. order: 2
  24921. },
  24922. "180": {
  24923. width: 320,
  24924. height: 180,
  24925. order: 1
  24926. }
  24927. };
  24928. module.exports = Resolutions;
  24929. },{}],94:[function(require,module,exports){
  24930. var StreamEventTypes = {
  24931. EVENT_TYPE_LOCAL_CREATED: "stream.local_created",
  24932. EVENT_TYPE_LOCAL_CHANGED: "stream.local_changed",
  24933. EVENT_TYPE_LOCAL_ENDED: "stream.local_ended",
  24934. EVENT_TYPE_REMOTE_CREATED: "stream.remote_created",
  24935. EVENT_TYPE_REMOTE_ENDED: "stream.remote_ended",
  24936. EVENT_TYPE_REMOTE_CHANGED: "stream.changed"
  24937. };
  24938. module.exports = StreamEventTypes;
  24939. },{}],95:[function(require,module,exports){
  24940. var UIEvents = {
  24941. NICKNAME_CHANGED: "UI.nickname_changed",
  24942. SELECTED_ENDPOINT: "UI.selected_endpoint",
  24943. PINNED_ENDPOINT: "UI.pinned_endpoint"
  24944. };
  24945. module.exports = UIEvents;
  24946. },{}],96:[function(require,module,exports){
  24947. var AuthenticationEvents = {
  24948. /**
  24949. * Event callback arguments:
  24950. * function(authenticationEnabled, userIdentity)
  24951. * authenticationEnabled - indicates whether authentication has been enabled
  24952. * in this session
  24953. * userIdentity - if user has been logged in then it contains user name. If
  24954. * contains 'null' or 'undefined' then user is not logged in.
  24955. */
  24956. IDENTITY_UPDATED: "authentication.identity_updated"
  24957. };
  24958. module.exports = AuthenticationEvents;
  24959. },{}],97:[function(require,module,exports){
  24960. var CQEvents = {
  24961. LOCALSTATS_UPDATED: "cq.localstats_updated",
  24962. REMOTESTATS_UPDATED: "cq.remotestats_updated",
  24963. STOP: "cq.stop"
  24964. };
  24965. module.exports = CQEvents;
  24966. },{}],98:[function(require,module,exports){
  24967. var DesktopSharingEventTypes = {
  24968. INIT: "ds.init",
  24969. SWITCHING_DONE: "ds.switching_done",
  24970. NEW_STREAM_CREATED: "ds.new_stream_created"
  24971. };
  24972. module.exports = DesktopSharingEventTypes;
  24973. },{}],99:[function(require,module,exports){
  24974. var Events = {
  24975. DTMF_SUPPORT_CHANGED: "members.dtmf_support_changed"
  24976. };
  24977. module.exports = Events;
  24978. },{}],100:[function(require,module,exports){
  24979. module.exports = {
  24980. getLanguages : function () {
  24981. var languages = [];
  24982. for(var lang in this)
  24983. {
  24984. if(typeof this[lang] === "string")
  24985. languages.push(this[lang]);
  24986. }
  24987. return languages;
  24988. },
  24989. EN: "en",
  24990. BG: "bg",
  24991. DE: "de",
  24992. TR: "tr"
  24993. }
  24994. },{}],101:[function(require,module,exports){
  24995. var XMPPEvents = {
  24996. CONFERENCE_CREATED: "xmpp.conferenceCreated.jingle",
  24997. CALL_TERMINATED: "xmpp.callterminated.jingle",
  24998. CALL_INCOMING: "xmpp.callincoming.jingle",
  24999. DISPOSE_CONFERENCE: "xmpp.dispose_conference",
  25000. GRACEFUL_SHUTDOWN: "xmpp.graceful_shutdown",
  25001. KICKED: "xmpp.kicked",
  25002. BRIDGE_DOWN: "xmpp.bridge_down",
  25003. USER_ID_CHANGED: "xmpp.user_id_changed",
  25004. STREAMS_CHANGED: "xmpp.streams_changed",
  25005. // We joined the MUC
  25006. MUC_JOINED: "xmpp.muc_joined",
  25007. // A member joined the MUC
  25008. MUC_MEMBER_JOINED: "xmpp.muc_member_joined",
  25009. // A member left the MUC
  25010. MUC_MEMBER_LEFT: "xmpp.muc_member_left",
  25011. MUC_ROLE_CHANGED: "xmpp.muc_role_changed",
  25012. MUC_DESTROYED: "xmpp.muc_destroyed",
  25013. DISPLAY_NAME_CHANGED: "xmpp.display_name_changed",
  25014. REMOTE_STATS: "xmpp.remote_stats",
  25015. LOCAL_ROLE_CHANGED: "xmpp.localrole_changed",
  25016. PRESENCE_STATUS: "xmpp.presence_status",
  25017. RESERVATION_ERROR: "xmpp.room_reservation_error",
  25018. SUBJECT_CHANGED: "xmpp.subject_changed",
  25019. MESSAGE_RECEIVED: "xmpp.message_received",
  25020. SENDING_CHAT_MESSAGE: "xmpp.sending_chat_message",
  25021. PASSWORD_REQUIRED: "xmpp.password_required",
  25022. AUTHENTICATION_REQUIRED: "xmpp.authentication_required",
  25023. CHAT_ERROR_RECEIVED: "xmpp.chat_error_received",
  25024. ETHERPAD: "xmpp.etherpad",
  25025. DEVICE_AVAILABLE: "xmpp.device_available"
  25026. };
  25027. module.exports = XMPPEvents;
  25028. },{}],102:[function(require,module,exports){
  25029. // Copyright Joyent, Inc. and other Node contributors.
  25030. //
  25031. // Permission is hereby granted, free of charge, to any person obtaining a
  25032. // copy of this software and associated documentation files (the
  25033. // "Software"), to deal in the Software without restriction, including
  25034. // without limitation the rights to use, copy, modify, merge, publish,
  25035. // distribute, sublicense, and/or sell copies of the Software, and to permit
  25036. // persons to whom the Software is furnished to do so, subject to the
  25037. // following conditions:
  25038. //
  25039. // The above copyright notice and this permission notice shall be included
  25040. // in all copies or substantial portions of the Software.
  25041. //
  25042. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  25043. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  25044. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  25045. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  25046. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  25047. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  25048. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  25049. function EventEmitter() {
  25050. this._events = this._events || {};
  25051. this._maxListeners = this._maxListeners || undefined;
  25052. }
  25053. module.exports = EventEmitter;
  25054. // Backwards-compat with node 0.10.x
  25055. EventEmitter.EventEmitter = EventEmitter;
  25056. EventEmitter.prototype._events = undefined;
  25057. EventEmitter.prototype._maxListeners = undefined;
  25058. // By default EventEmitters will print a warning if more than 10 listeners are
  25059. // added to it. This is a useful default which helps finding memory leaks.
  25060. EventEmitter.defaultMaxListeners = 10;
  25061. // Obviously not all Emitters should be limited to 10. This function allows
  25062. // that to be increased. Set to zero for unlimited.
  25063. EventEmitter.prototype.setMaxListeners = function(n) {
  25064. if (!isNumber(n) || n < 0 || isNaN(n))
  25065. throw TypeError('n must be a positive number');
  25066. this._maxListeners = n;
  25067. return this;
  25068. };
  25069. EventEmitter.prototype.emit = function(type) {
  25070. var er, handler, len, args, i, listeners;
  25071. if (!this._events)
  25072. this._events = {};
  25073. // If there is no 'error' event listener then throw.
  25074. if (type === 'error') {
  25075. if (!this._events.error ||
  25076. (isObject(this._events.error) && !this._events.error.length)) {
  25077. er = arguments[1];
  25078. if (er instanceof Error) {
  25079. throw er; // Unhandled 'error' event
  25080. }
  25081. throw TypeError('Uncaught, unspecified "error" event.');
  25082. }
  25083. }
  25084. handler = this._events[type];
  25085. if (isUndefined(handler))
  25086. return false;
  25087. if (isFunction(handler)) {
  25088. switch (arguments.length) {
  25089. // fast cases
  25090. case 1:
  25091. handler.call(this);
  25092. break;
  25093. case 2:
  25094. handler.call(this, arguments[1]);
  25095. break;
  25096. case 3:
  25097. handler.call(this, arguments[1], arguments[2]);
  25098. break;
  25099. // slower
  25100. default:
  25101. len = arguments.length;
  25102. args = new Array(len - 1);
  25103. for (i = 1; i < len; i++)
  25104. args[i - 1] = arguments[i];
  25105. handler.apply(this, args);
  25106. }
  25107. } else if (isObject(handler)) {
  25108. len = arguments.length;
  25109. args = new Array(len - 1);
  25110. for (i = 1; i < len; i++)
  25111. args[i - 1] = arguments[i];
  25112. listeners = handler.slice();
  25113. len = listeners.length;
  25114. for (i = 0; i < len; i++)
  25115. listeners[i].apply(this, args);
  25116. }
  25117. return true;
  25118. };
  25119. EventEmitter.prototype.addListener = function(type, listener) {
  25120. var m;
  25121. if (!isFunction(listener))
  25122. throw TypeError('listener must be a function');
  25123. if (!this._events)
  25124. this._events = {};
  25125. // To avoid recursion in the case that type === "newListener"! Before
  25126. // adding it to the listeners, first emit "newListener".
  25127. if (this._events.newListener)
  25128. this.emit('newListener', type,
  25129. isFunction(listener.listener) ?
  25130. listener.listener : listener);
  25131. if (!this._events[type])
  25132. // Optimize the case of one listener. Don't need the extra array object.
  25133. this._events[type] = listener;
  25134. else if (isObject(this._events[type]))
  25135. // If we've already got an array, just append.
  25136. this._events[type].push(listener);
  25137. else
  25138. // Adding the second element, need to change to array.
  25139. this._events[type] = [this._events[type], listener];
  25140. // Check for listener leak
  25141. if (isObject(this._events[type]) && !this._events[type].warned) {
  25142. var m;
  25143. if (!isUndefined(this._maxListeners)) {
  25144. m = this._maxListeners;
  25145. } else {
  25146. m = EventEmitter.defaultMaxListeners;
  25147. }
  25148. if (m && m > 0 && this._events[type].length > m) {
  25149. this._events[type].warned = true;
  25150. console.error('(node) warning: possible EventEmitter memory ' +
  25151. 'leak detected. %d listeners added. ' +
  25152. 'Use emitter.setMaxListeners() to increase limit.',
  25153. this._events[type].length);
  25154. if (typeof console.trace === 'function') {
  25155. // not supported in IE 10
  25156. console.trace();
  25157. }
  25158. }
  25159. }
  25160. return this;
  25161. };
  25162. EventEmitter.prototype.on = EventEmitter.prototype.addListener;
  25163. EventEmitter.prototype.once = function(type, listener) {
  25164. if (!isFunction(listener))
  25165. throw TypeError('listener must be a function');
  25166. var fired = false;
  25167. function g() {
  25168. this.removeListener(type, g);
  25169. if (!fired) {
  25170. fired = true;
  25171. listener.apply(this, arguments);
  25172. }
  25173. }
  25174. g.listener = listener;
  25175. this.on(type, g);
  25176. return this;
  25177. };
  25178. // emits a 'removeListener' event iff the listener was removed
  25179. EventEmitter.prototype.removeListener = function(type, listener) {
  25180. var list, position, length, i;
  25181. if (!isFunction(listener))
  25182. throw TypeError('listener must be a function');
  25183. if (!this._events || !this._events[type])
  25184. return this;
  25185. list = this._events[type];
  25186. length = list.length;
  25187. position = -1;
  25188. if (list === listener ||
  25189. (isFunction(list.listener) && list.listener === listener)) {
  25190. delete this._events[type];
  25191. if (this._events.removeListener)
  25192. this.emit('removeListener', type, listener);
  25193. } else if (isObject(list)) {
  25194. for (i = length; i-- > 0;) {
  25195. if (list[i] === listener ||
  25196. (list[i].listener && list[i].listener === listener)) {
  25197. position = i;
  25198. break;
  25199. }
  25200. }
  25201. if (position < 0)
  25202. return this;
  25203. if (list.length === 1) {
  25204. list.length = 0;
  25205. delete this._events[type];
  25206. } else {
  25207. list.splice(position, 1);
  25208. }
  25209. if (this._events.removeListener)
  25210. this.emit('removeListener', type, listener);
  25211. }
  25212. return this;
  25213. };
  25214. EventEmitter.prototype.removeAllListeners = function(type) {
  25215. var key, listeners;
  25216. if (!this._events)
  25217. return this;
  25218. // not listening for removeListener, no need to emit
  25219. if (!this._events.removeListener) {
  25220. if (arguments.length === 0)
  25221. this._events = {};
  25222. else if (this._events[type])
  25223. delete this._events[type];
  25224. return this;
  25225. }
  25226. // emit removeListener for all listeners on all events
  25227. if (arguments.length === 0) {
  25228. for (key in this._events) {
  25229. if (key === 'removeListener') continue;
  25230. this.removeAllListeners(key);
  25231. }
  25232. this.removeAllListeners('removeListener');
  25233. this._events = {};
  25234. return this;
  25235. }
  25236. listeners = this._events[type];
  25237. if (isFunction(listeners)) {
  25238. this.removeListener(type, listeners);
  25239. } else {
  25240. // LIFO order
  25241. while (listeners.length)
  25242. this.removeListener(type, listeners[listeners.length - 1]);
  25243. }
  25244. delete this._events[type];
  25245. return this;
  25246. };
  25247. EventEmitter.prototype.listeners = function(type) {
  25248. var ret;
  25249. if (!this._events || !this._events[type])
  25250. ret = [];
  25251. else if (isFunction(this._events[type]))
  25252. ret = [this._events[type]];
  25253. else
  25254. ret = this._events[type].slice();
  25255. return ret;
  25256. };
  25257. EventEmitter.listenerCount = function(emitter, type) {
  25258. var ret;
  25259. if (!emitter._events || !emitter._events[type])
  25260. ret = 0;
  25261. else if (isFunction(emitter._events[type]))
  25262. ret = 1;
  25263. else
  25264. ret = emitter._events[type].length;
  25265. return ret;
  25266. };
  25267. function isFunction(arg) {
  25268. return typeof arg === 'function';
  25269. }
  25270. function isNumber(arg) {
  25271. return typeof arg === 'number';
  25272. }
  25273. function isObject(arg) {
  25274. return typeof arg === 'object' && arg !== null;
  25275. }
  25276. function isUndefined(arg) {
  25277. return arg === void 0;
  25278. }
  25279. },{}],103:[function(require,module,exports){
  25280. // shim for using process in browser
  25281. var process = module.exports = {};
  25282. var queue = [];
  25283. var draining = false;
  25284. function drainQueue() {
  25285. if (draining) {
  25286. return;
  25287. }
  25288. draining = true;
  25289. var currentQueue;
  25290. var len = queue.length;
  25291. while(len) {
  25292. currentQueue = queue;
  25293. queue = [];
  25294. var i = -1;
  25295. while (++i < len) {
  25296. currentQueue[i]();
  25297. }
  25298. len = queue.length;
  25299. }
  25300. draining = false;
  25301. }
  25302. process.nextTick = function (fun) {
  25303. queue.push(fun);
  25304. if (!draining) {
  25305. setTimeout(drainQueue, 0);
  25306. }
  25307. };
  25308. process.title = 'browser';
  25309. process.browser = true;
  25310. process.env = {};
  25311. process.argv = [];
  25312. process.version = ''; // empty string to avoid regexp issues
  25313. function noop() {}
  25314. process.on = noop;
  25315. process.addListener = noop;
  25316. process.once = noop;
  25317. process.off = noop;
  25318. process.removeListener = noop;
  25319. process.removeAllListeners = noop;
  25320. process.emit = noop;
  25321. process.binding = function (name) {
  25322. throw new Error('process.binding is not supported');
  25323. };
  25324. // TODO(shtylman)
  25325. process.cwd = function () { return '/' };
  25326. process.chdir = function (dir) {
  25327. throw new Error('process.chdir is not supported');
  25328. };
  25329. process.umask = function() { return 0; };
  25330. },{}]},{},[1])(1)
  25331. });