Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

app.bundle.js 884KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837
  1. !function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{var f;"undefined"!=typeof window?f=window:"undefined"!=typeof global?f=global:"undefined"!=typeof self&&(f=self),f.APP=e()}}(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. }
  19. };
  20. function init() {
  21. APP.RTC.start();
  22. APP.xmpp.start(APP.UI.getCredentials());
  23. APP.statistics.start();
  24. APP.connectionquality.init();
  25. // Set default desktop sharing method
  26. APP.desktopsharing.init();
  27. APP.keyboardshortcut.init();
  28. }
  29. $(document).ready(function () {
  30. APP.init();
  31. APP.translation.init();
  32. if(APP.API.isEnabled())
  33. APP.API.init();
  34. APP.UI.start(init);
  35. });
  36. $(window).bind('beforeunload', function () {
  37. if(APP.API.isEnabled())
  38. APP.API.dispose();
  39. });
  40. module.exports = APP;
  41. },{"./modules/API/API":2,"./modules/RTC/RTC":6,"./modules/UI/UI":8,"./modules/connectionquality/connectionquality":34,"./modules/desktopsharing/desktopsharing":35,"./modules/keyboardshortcut/keyboardshortcut":36,"./modules/settings/Settings":37,"./modules/simulcast/simulcast":42,"./modules/statistics/statistics":45,"./modules/translation/translation":46,"./modules/xmpp/xmpp":60}],2:[function(require,module,exports){
  42. /**
  43. * Implements API class that communicates with external api class
  44. * and provides interface to access Jitsi Meet features by external
  45. * applications that embed Jitsi Meet
  46. */
  47. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  48. /**
  49. * List of the available commands.
  50. * @type {{
  51. * displayName: inputDisplayNameHandler,
  52. * muteAudio: toggleAudio,
  53. * muteVideo: toggleVideo,
  54. * filmStrip: toggleFilmStrip
  55. * }}
  56. */
  57. var commands =
  58. {
  59. displayName: APP.UI.inputDisplayNameHandler,
  60. muteAudio: APP.UI.toggleAudio,
  61. muteVideo: APP.UI.toggleVideo,
  62. toggleFilmStrip: APP.UI.toggleFilmStrip,
  63. toggleChat: APP.UI.toggleChat,
  64. toggleContactList: APP.UI.toggleContactList
  65. };
  66. /**
  67. * Maps the supported events and their status
  68. * (true it the event is enabled and false if it is disabled)
  69. * @type {{
  70. * incomingMessage: boolean,
  71. * outgoingMessage: boolean,
  72. * displayNameChange: boolean,
  73. * participantJoined: boolean,
  74. * participantLeft: boolean
  75. * }}
  76. */
  77. var events =
  78. {
  79. incomingMessage: false,
  80. outgoingMessage:false,
  81. displayNameChange: false,
  82. participantJoined: false,
  83. participantLeft: false
  84. };
  85. var displayName = {};
  86. /**
  87. * Processes commands from external applicaiton.
  88. * @param message the object with the command
  89. */
  90. function processCommand(message)
  91. {
  92. if(message.action != "execute")
  93. {
  94. console.error("Unknown action of the message");
  95. return;
  96. }
  97. for(var key in message)
  98. {
  99. if(commands[key])
  100. commands[key].apply(null, message[key]);
  101. }
  102. }
  103. /**
  104. * Processes events objects from external applications
  105. * @param event the event
  106. */
  107. function processEvent(event) {
  108. if(!event.action)
  109. {
  110. console.error("Event with no action is received.");
  111. return;
  112. }
  113. var i = 0;
  114. switch(event.action)
  115. {
  116. case "add":
  117. for(; i < event.events.length; i++)
  118. {
  119. events[event.events[i]] = true;
  120. }
  121. break;
  122. case "remove":
  123. for(; i < event.events.length; i++)
  124. {
  125. events[event.events[i]] = false;
  126. }
  127. break;
  128. default:
  129. console.error("Unknown action for event.");
  130. }
  131. }
  132. /**
  133. * Sends message to the external application.
  134. * @param object
  135. */
  136. function sendMessage(object) {
  137. window.parent.postMessage(JSON.stringify(object), "*");
  138. }
  139. /**
  140. * Processes a message event from the external application
  141. * @param event the message event
  142. */
  143. function processMessage(event)
  144. {
  145. var message;
  146. try {
  147. message = JSON.parse(event.data);
  148. } catch (e) {}
  149. if(!message.type)
  150. return;
  151. switch (message.type)
  152. {
  153. case "command":
  154. processCommand(message);
  155. break;
  156. case "event":
  157. processEvent(message);
  158. break;
  159. default:
  160. console.error("Unknown type of the message");
  161. return;
  162. }
  163. }
  164. function setupListeners() {
  165. APP.xmpp.addListener(XMPPEvents.MUC_ENTER, function (from) {
  166. API.triggerEvent("participantJoined", {jid: from});
  167. });
  168. APP.xmpp.addListener(XMPPEvents.MESSAGE_RECEIVED, function (from, nick, txt, myjid) {
  169. if (from != myjid)
  170. API.triggerEvent("incomingMessage",
  171. {"from": from, "nick": nick, "message": txt});
  172. });
  173. APP.xmpp.addListener(XMPPEvents.MUC_LEFT, function (jid) {
  174. API.triggerEvent("participantLeft", {jid: jid});
  175. });
  176. APP.xmpp.addListener(XMPPEvents.DISPLAY_NAME_CHANGED, function (jid, newDisplayName) {
  177. name = displayName[jid];
  178. if(!name || name != newDisplayName) {
  179. API.triggerEvent("displayNameChange", {jid: jid, displayname: newDisplayName});
  180. displayName[jid] = newDisplayName;
  181. }
  182. });
  183. APP.xmpp.addListener(XMPPEvents.SENDING_CHAT_MESSAGE, function (body) {
  184. APP.API.triggerEvent("outgoingMessage", {"message": body});
  185. });
  186. }
  187. var API = {
  188. /**
  189. * Check whether the API should be enabled or not.
  190. * @returns {boolean}
  191. */
  192. isEnabled: function () {
  193. var hash = location.hash;
  194. if(hash && hash.indexOf("external") > -1 && window.postMessage)
  195. return true;
  196. return false;
  197. },
  198. /**
  199. * Initializes the APIConnector. Setups message event listeners that will
  200. * receive information from external applications that embed Jitsi Meet.
  201. * It also sends a message to the external application that APIConnector
  202. * is initialized.
  203. */
  204. init: function () {
  205. if (window.addEventListener)
  206. {
  207. window.addEventListener('message',
  208. processMessage, false);
  209. }
  210. else
  211. {
  212. window.attachEvent('onmessage', processMessage);
  213. }
  214. sendMessage({type: "system", loaded: true});
  215. setupListeners();
  216. },
  217. /**
  218. * Checks whether the event is enabled ot not.
  219. * @param name the name of the event.
  220. * @returns {*}
  221. */
  222. isEventEnabled: function (name) {
  223. return events[name];
  224. },
  225. /**
  226. * Sends event object to the external application that has been subscribed
  227. * for that event.
  228. * @param name the name event
  229. * @param object data associated with the event
  230. */
  231. triggerEvent: function (name, object) {
  232. if(this.isEnabled() && this.isEventEnabled(name))
  233. sendMessage({
  234. type: "event", action: "result", event: name, result: object});
  235. },
  236. /**
  237. * Removes the listeners.
  238. */
  239. dispose: function () {
  240. if(window.removeEventListener)
  241. {
  242. window.removeEventListener("message",
  243. processMessage, false);
  244. }
  245. else
  246. {
  247. window.detachEvent('onmessage', processMessage);
  248. }
  249. }
  250. };
  251. module.exports = API;
  252. },{"../../service/xmpp/XMPPEvents":96}],3:[function(require,module,exports){
  253. /* global Strophe, updateLargeVideo, focusedVideoSrc*/
  254. // cache datachannels to avoid garbage collection
  255. // https://code.google.com/p/chromium/issues/detail?id=405545
  256. var RTCEvents = require("../../service/RTC/RTCEvents");
  257. var _dataChannels = [];
  258. var eventEmitter = null;
  259. var DataChannels =
  260. {
  261. /**
  262. * Callback triggered by PeerConnection when new data channel is opened
  263. * on the bridge.
  264. * @param event the event info object.
  265. */
  266. onDataChannel: function (event)
  267. {
  268. var dataChannel = event.channel;
  269. dataChannel.onopen = function () {
  270. console.info("Data channel opened by the Videobridge!", dataChannel);
  271. // Code sample for sending string and/or binary data
  272. // Sends String message to the bridge
  273. //dataChannel.send("Hello bridge!");
  274. // Sends 12 bytes binary message to the bridge
  275. //dataChannel.send(new ArrayBuffer(12));
  276. // when the data channel becomes available, tell the bridge about video
  277. // selections so that it can do adaptive simulcast,
  278. // we want the notification to trigger even if userJid is undefined,
  279. // or null.
  280. var userJid = APP.UI.getLargeVideoState().userResourceJid;
  281. // we want the notification to trigger even if userJid is undefined,
  282. // or null.
  283. onSelectedEndpointChanged(userJid);
  284. };
  285. dataChannel.onerror = function (error) {
  286. console.error("Data Channel Error:", error, dataChannel);
  287. };
  288. dataChannel.onmessage = function (event) {
  289. var data = event.data;
  290. // JSON
  291. var obj;
  292. try {
  293. obj = JSON.parse(data);
  294. }
  295. catch (e) {
  296. console.error(
  297. "Failed to parse data channel message as JSON: ",
  298. data,
  299. dataChannel);
  300. }
  301. if (('undefined' !== typeof(obj)) && (null !== obj)) {
  302. var colibriClass = obj.colibriClass;
  303. if ("DominantSpeakerEndpointChangeEvent" === colibriClass) {
  304. // Endpoint ID from the Videobridge.
  305. var dominantSpeakerEndpoint = obj.dominantSpeakerEndpoint;
  306. console.info(
  307. "Data channel new dominant speaker event: ",
  308. dominantSpeakerEndpoint);
  309. eventEmitter.emit(RTCEvents.DOMINANTSPEAKER_CHANGED, dominantSpeakerEndpoint);
  310. }
  311. else if ("InLastNChangeEvent" === colibriClass)
  312. {
  313. var oldValue = obj.oldValue;
  314. var newValue = obj.newValue;
  315. // Make sure that oldValue and newValue are of type boolean.
  316. var type;
  317. if ((type = typeof oldValue) !== 'boolean') {
  318. if (type === 'string') {
  319. oldValue = (oldValue == "true");
  320. } else {
  321. oldValue = new Boolean(oldValue).valueOf();
  322. }
  323. }
  324. if ((type = typeof newValue) !== 'boolean') {
  325. if (type === 'string') {
  326. newValue = (newValue == "true");
  327. } else {
  328. newValue = new Boolean(newValue).valueOf();
  329. }
  330. }
  331. eventEmitter.emit(RTCEvents.LASTN_CHANGED, oldValue, newValue);
  332. }
  333. else if ("LastNEndpointsChangeEvent" === colibriClass)
  334. {
  335. // The new/latest list of last-n endpoint IDs.
  336. var lastNEndpoints = obj.lastNEndpoints;
  337. // The list of endpoint IDs which are entering the list of
  338. // last-n at this time i.e. were not in the old list of last-n
  339. // endpoint IDs.
  340. var endpointsEnteringLastN = obj.endpointsEnteringLastN;
  341. var stream = obj.stream;
  342. console.log(
  343. "Data channel new last-n event: ",
  344. lastNEndpoints, endpointsEnteringLastN, obj);
  345. eventEmitter.emit(RTCEvents.LASTN_ENDPOINT_CHANGED,
  346. lastNEndpoints, endpointsEnteringLastN, obj);
  347. }
  348. else if ("SimulcastLayersChangedEvent" === colibriClass)
  349. {
  350. eventEmitter.emit(RTCEvents.SIMULCAST_LAYER_CHANGED,
  351. obj.endpointSimulcastLayers);
  352. }
  353. else if ("SimulcastLayersChangingEvent" === colibriClass)
  354. {
  355. eventEmitter.emit(RTCEvents.SIMULCAST_LAYER_CHANGING,
  356. obj.endpointSimulcastLayers);
  357. }
  358. else if ("StartSimulcastLayerEvent" === colibriClass)
  359. {
  360. eventEmitter.emit(RTCEvents.SIMULCAST_START, obj.simulcastLayer);
  361. }
  362. else if ("StopSimulcastLayerEvent" === colibriClass)
  363. {
  364. eventEmitter.emit(RTCEvents.SIMULCAST_STOP, obj.simulcastLayer);
  365. }
  366. else
  367. {
  368. console.debug("Data channel JSON-formatted message: ", obj);
  369. }
  370. }
  371. };
  372. dataChannel.onclose = function ()
  373. {
  374. console.info("The Data Channel closed", dataChannel);
  375. var idx = _dataChannels.indexOf(dataChannel);
  376. if (idx > -1)
  377. _dataChannels = _dataChannels.splice(idx, 1);
  378. };
  379. _dataChannels.push(dataChannel);
  380. },
  381. /**
  382. * Binds "ondatachannel" event listener to given PeerConnection instance.
  383. * @param peerConnection WebRTC peer connection instance.
  384. */
  385. init: function (peerConnection, emitter) {
  386. if(!config.openSctp)
  387. return;
  388. peerConnection.ondatachannel = this.onDataChannel;
  389. eventEmitter = emitter;
  390. // Sample code for opening new data channel from Jitsi Meet to the bridge.
  391. // Although it's not a requirement to open separate channels from both bridge
  392. // and peer as single channel can be used for sending and receiving data.
  393. // So either channel opened by the bridge or the one opened here is enough
  394. // for communication with the bridge.
  395. /*var dataChannelOptions =
  396. {
  397. reliable: true
  398. };
  399. var dataChannel
  400. = peerConnection.createDataChannel("myChannel", dataChannelOptions);
  401. // Can be used only when is in open state
  402. dataChannel.onopen = function ()
  403. {
  404. dataChannel.send("My channel !!!");
  405. };
  406. dataChannel.onmessage = function (event)
  407. {
  408. var msgData = event.data;
  409. console.info("Got My Data Channel Message:", msgData, dataChannel);
  410. };*/
  411. },
  412. handleSelectedEndpointEvent: onSelectedEndpointChanged,
  413. handlePinnedEndpointEvent: onPinnedEndpointChanged
  414. };
  415. function onSelectedEndpointChanged(userResource)
  416. {
  417. console.log('selected endpoint changed: ', userResource);
  418. if (_dataChannels && _dataChannels.length != 0)
  419. {
  420. _dataChannels.some(function (dataChannel) {
  421. if (dataChannel.readyState == 'open')
  422. {
  423. console.log('sending selected endpoint changed '
  424. + 'notification to the bridge: ', userResource);
  425. dataChannel.send(JSON.stringify({
  426. 'colibriClass': 'SelectedEndpointChangedEvent',
  427. 'selectedEndpoint':
  428. (!userResource || userResource === null)?
  429. null : userResource
  430. }));
  431. return true;
  432. }
  433. });
  434. }
  435. }
  436. function onPinnedEndpointChanged(userResource)
  437. {
  438. console.log('pinned endpoint changed: ', userResource);
  439. if (_dataChannels && _dataChannels.length != 0)
  440. {
  441. _dataChannels.some(function (dataChannel) {
  442. if (dataChannel.readyState == 'open')
  443. {
  444. dataChannel.send(JSON.stringify({
  445. 'colibriClass': 'PinnedEndpointChangedEvent',
  446. 'pinnedEndpoint':
  447. (!userResource || userResource == null)?
  448. null : userResource
  449. }));
  450. return true;
  451. }
  452. });
  453. }
  454. }
  455. module.exports = DataChannels;
  456. },{"../../service/RTC/RTCEvents":88}],4:[function(require,module,exports){
  457. var StreamEventTypes = require("../../service/RTC/StreamEventTypes.js");
  458. function LocalStream(stream, type, eventEmitter, videoType)
  459. {
  460. this.stream = stream;
  461. this.eventEmitter = eventEmitter;
  462. this.type = type;
  463. this.videoType = videoType;
  464. var self = this;
  465. if(type == "audio")
  466. {
  467. this.getTracks = function () {
  468. return self.stream.getAudioTracks();
  469. };
  470. }
  471. else
  472. {
  473. this.getTracks = function () {
  474. return self.stream.getVideoTracks();
  475. };
  476. }
  477. this.stream.onended = function()
  478. {
  479. self.streamEnded();
  480. };
  481. }
  482. LocalStream.prototype.streamEnded = function () {
  483. this.eventEmitter.emit(StreamEventTypes.EVENT_TYPE_LOCAL_ENDED, this);
  484. }
  485. LocalStream.prototype.getOriginalStream = function()
  486. {
  487. return this.stream;
  488. }
  489. LocalStream.prototype.isAudioStream = function () {
  490. return (this.stream.getAudioTracks() && this.stream.getAudioTracks().length > 0);
  491. };
  492. LocalStream.prototype.mute = function()
  493. {
  494. var ismuted = false;
  495. var tracks = this.getTracks();
  496. for (var idx = 0; idx < tracks.length; idx++) {
  497. ismuted = !tracks[idx].enabled;
  498. tracks[idx].enabled = ismuted;
  499. }
  500. return ismuted;
  501. };
  502. LocalStream.prototype.setMute = function(mute)
  503. {
  504. var tracks = this.getTracks();
  505. for (var idx = 0; idx < tracks.length; idx++) {
  506. tracks[idx].enabled = mute;
  507. }
  508. };
  509. LocalStream.prototype.isMuted = function () {
  510. var tracks = [];
  511. if(this.type == "audio")
  512. {
  513. tracks = this.stream.getAudioTracks();
  514. }
  515. else
  516. {
  517. tracks = this.stream.getVideoTracks();
  518. }
  519. for (var idx = 0; idx < tracks.length; idx++) {
  520. if(tracks[idx].enabled)
  521. return false;
  522. }
  523. return true;
  524. }
  525. LocalStream.prototype.getId = function () {
  526. return this.stream.getTracks()[0].id;
  527. }
  528. module.exports = LocalStream;
  529. },{"../../service/RTC/StreamEventTypes.js":90}],5:[function(require,module,exports){
  530. ////These lines should be uncommented when require works in app.js
  531. var RTCBrowserType = require("../../service/RTC/RTCBrowserType.js");
  532. var MediaStreamType = require("../../service/RTC/MediaStreamTypes");
  533. /**
  534. * Creates a MediaStream object for the given data, session id and ssrc.
  535. * It is a wrapper class for the MediaStream.
  536. *
  537. * @param data the data object from which we obtain the stream,
  538. * the peerjid, etc.
  539. * @param sid the session id
  540. * @param ssrc the ssrc corresponding to this MediaStream
  541. *
  542. * @constructor
  543. */
  544. function MediaStream(data, sid, ssrc, browser) {
  545. // XXX(gp) to minimize headaches in the future, we should build our
  546. // abstractions around tracks and not streams. ORTC is track based API.
  547. // Mozilla expects m-lines to represent media tracks.
  548. //
  549. // Practically, what I'm saying is that we should have a MediaTrack class
  550. // and not a MediaStream class.
  551. //
  552. // Also, we should be able to associate multiple SSRCs with a MediaTrack as
  553. // a track might have an associated RTX and FEC sources.
  554. this.sid = sid;
  555. this.stream = data.stream;
  556. this.peerjid = data.peerjid;
  557. this.ssrc = ssrc;
  558. this.type = (this.stream.getVideoTracks().length > 0)?
  559. MediaStreamType.VIDEO_TYPE : MediaStreamType.AUDIO_TYPE;
  560. this.videoType = null;
  561. this.muted = false;
  562. }
  563. MediaStream.prototype.getOriginalStream = function()
  564. {
  565. return this.stream;
  566. }
  567. MediaStream.prototype.setMute = function (value)
  568. {
  569. this.stream.muted = value;
  570. this.muted = value;
  571. }
  572. module.exports = MediaStream;
  573. },{"../../service/RTC/MediaStreamTypes":86,"../../service/RTC/RTCBrowserType.js":87}],6:[function(require,module,exports){
  574. var EventEmitter = require("events");
  575. var RTCUtils = require("./RTCUtils.js");
  576. var LocalStream = require("./LocalStream.js");
  577. var DataChannels = require("./DataChannels");
  578. var MediaStream = require("./MediaStream.js");
  579. var DesktopSharingEventTypes
  580. = require("../../service/desktopsharing/DesktopSharingEventTypes");
  581. var MediaStreamType = require("../../service/RTC/MediaStreamTypes");
  582. var StreamEventTypes = require("../../service/RTC/StreamEventTypes.js");
  583. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  584. var UIEvents = require("../../service/UI/UIEvents");
  585. var eventEmitter = new EventEmitter();
  586. var RTC = {
  587. rtcUtils: null,
  588. localStreams: [],
  589. remoteStreams: {},
  590. localAudio: null,
  591. localVideo: null,
  592. addStreamListener: function (listener, eventType) {
  593. eventEmitter.on(eventType, listener);
  594. },
  595. addListener: function (type, listener) {
  596. eventEmitter.on(type, listener);
  597. },
  598. removeStreamListener: function (listener, eventType) {
  599. if(!(eventType instanceof StreamEventTypes))
  600. throw "Illegal argument";
  601. eventEmitter.removeListener(eventType, listener);
  602. },
  603. createLocalStream: function (stream, type, change) {
  604. var localStream = new LocalStream(stream, type, eventEmitter);
  605. //in firefox we have only one stream object
  606. if(this.localStreams.length == 0 ||
  607. this.localStreams[0].getOriginalStream() != stream)
  608. this.localStreams.push(localStream);
  609. if(type == "audio")
  610. {
  611. this.localAudio = localStream;
  612. }
  613. else
  614. {
  615. this.localVideo = localStream;
  616. }
  617. var eventType = StreamEventTypes.EVENT_TYPE_LOCAL_CREATED;
  618. if(change)
  619. eventType = StreamEventTypes.EVENT_TYPE_LOCAL_CHANGED;
  620. eventEmitter.emit(eventType, localStream);
  621. return localStream;
  622. },
  623. removeLocalStream: function (stream) {
  624. for(var i = 0; i < this.localStreams.length; i++)
  625. {
  626. if(this.localStreams[i].getOriginalStream() === stream) {
  627. delete this.localStreams[i];
  628. return;
  629. }
  630. }
  631. },
  632. createRemoteStream: function (data, sid, thessrc) {
  633. var remoteStream = new MediaStream(data, sid, thessrc,
  634. this.getBrowserType());
  635. var jid = data.peerjid || APP.xmpp.myJid();
  636. if(!this.remoteStreams[jid]) {
  637. this.remoteStreams[jid] = {};
  638. }
  639. this.remoteStreams[jid][remoteStream.type]= remoteStream;
  640. eventEmitter.emit(StreamEventTypes.EVENT_TYPE_REMOTE_CREATED, remoteStream);
  641. console.debug("ADD remote stream ", remoteStream.type, " ", jid, " ", thessrc);
  642. return remoteStream;
  643. },
  644. getBrowserType: function () {
  645. return this.rtcUtils.browser;
  646. },
  647. getPCConstraints: function () {
  648. return this.rtcUtils.pc_constraints;
  649. },
  650. getUserMediaWithConstraints:function(um, success_callback,
  651. failure_callback, resolution,
  652. bandwidth, fps, desktopStream)
  653. {
  654. return this.rtcUtils.getUserMediaWithConstraints(um, success_callback,
  655. failure_callback, resolution, bandwidth, fps, desktopStream);
  656. },
  657. attachMediaStream: function (element, stream) {
  658. this.rtcUtils.attachMediaStream(element, stream);
  659. },
  660. getStreamID: function (stream) {
  661. return this.rtcUtils.getStreamID(stream);
  662. },
  663. getVideoSrc: function (element) {
  664. return this.rtcUtils.getVideoSrc(element);
  665. },
  666. setVideoSrc: function (element, src) {
  667. this.rtcUtils.setVideoSrc(element, src);
  668. },
  669. dispose: function() {
  670. if (this.rtcUtils) {
  671. this.rtcUtils = null;
  672. }
  673. },
  674. stop: function () {
  675. this.dispose();
  676. },
  677. start: function () {
  678. var self = this;
  679. APP.desktopsharing.addListener(
  680. function (stream, isUsingScreenStream, callback) {
  681. self.changeLocalVideo(stream, isUsingScreenStream, callback);
  682. }, DesktopSharingEventTypes.NEW_STREAM_CREATED);
  683. APP.xmpp.addListener(XMPPEvents.CHANGED_STREAMS, function (jid, changedStreams) {
  684. for(var i = 0; i < changedStreams.length; i++) {
  685. var type = changedStreams[i].type;
  686. if (type != "audio") {
  687. var peerStreams = self.remoteStreams[jid];
  688. if(!peerStreams)
  689. continue;
  690. var videoStream = peerStreams[MediaStreamType.VIDEO_TYPE];
  691. if(!videoStream)
  692. continue;
  693. videoStream.videoType = changedStreams[i].type;
  694. }
  695. }
  696. });
  697. APP.xmpp.addListener(XMPPEvents.CALL_INCOMING, function(event) {
  698. DataChannels.init(event.peerconnection, eventEmitter);
  699. });
  700. APP.UI.addListener(UIEvents.SELECTED_ENDPOINT,
  701. DataChannels.handleSelectedEndpointEvent);
  702. APP.UI.addListener(UIEvents.PINNED_ENDPOINT,
  703. DataChannels.handlePinnedEndpointEvent);
  704. this.rtcUtils = new RTCUtils(this);
  705. this.rtcUtils.obtainAudioAndVideoPermissions();
  706. },
  707. muteRemoteVideoStream: function (jid, value) {
  708. var stream;
  709. if(this.remoteStreams[jid] &&
  710. this.remoteStreams[jid][MediaStreamType.VIDEO_TYPE])
  711. {
  712. stream = this.remoteStreams[jid][MediaStreamType.VIDEO_TYPE];
  713. }
  714. if(!stream)
  715. return false;
  716. if (value != stream.muted) {
  717. stream.setMute(value);
  718. return true;
  719. }
  720. return false;
  721. },
  722. switchVideoStreams: function (new_stream) {
  723. this.localVideo.stream = new_stream;
  724. this.localStreams = [];
  725. //in firefox we have only one stream object
  726. if (this.localAudio.getOriginalStream() != new_stream)
  727. this.localStreams.push(this.localAudio);
  728. this.localStreams.push(this.localVideo);
  729. },
  730. changeLocalVideo: function (stream, isUsingScreenStream, callback) {
  731. var oldStream = this.localVideo.getOriginalStream();
  732. var type = (isUsingScreenStream? "screen" : "video");
  733. this.localVideo = this.createLocalStream(stream, "video", true, type);
  734. // Stop the stream to trigger onended event for old stream
  735. oldStream.stop();
  736. APP.xmpp.switchStreams(stream, oldStream,callback);
  737. },
  738. /**
  739. * Checks if video identified by given src is desktop stream.
  740. * @param videoSrc eg.
  741. * blob:https%3A//pawel.jitsi.net/9a46e0bd-131e-4d18-9c14-a9264e8db395
  742. * @returns {boolean}
  743. */
  744. isVideoSrcDesktop: function (jid) {
  745. if(!jid)
  746. return false;
  747. var isDesktop = false;
  748. var stream = null;
  749. if (APP.xmpp.myJid() &&
  750. APP.xmpp.myResource() === jid) {
  751. // local video
  752. stream = this.localVideo;
  753. } else {
  754. var peerStreams = this.remoteStreams[jid];
  755. if(!peerStreams)
  756. return false;
  757. stream = peerStreams[MediaStreamType.VIDEO_TYPE];
  758. }
  759. if(stream)
  760. isDesktop = (stream.videoType === "screen");
  761. return isDesktop;
  762. }
  763. };
  764. module.exports = RTC;
  765. },{"../../service/RTC/MediaStreamTypes":86,"../../service/RTC/StreamEventTypes.js":90,"../../service/UI/UIEvents":91,"../../service/desktopsharing/DesktopSharingEventTypes":94,"../../service/xmpp/XMPPEvents":96,"./DataChannels":3,"./LocalStream.js":4,"./MediaStream.js":5,"./RTCUtils.js":7,"events":97}],7:[function(require,module,exports){
  766. var RTCBrowserType = require("../../service/RTC/RTCBrowserType.js");
  767. var Resolutions = require("../../service/RTC/Resolutions");
  768. var currentResolution = null;
  769. function getPreviousResolution(resolution) {
  770. if(!Resolutions[resolution])
  771. return null;
  772. var order = Resolutions[resolution].order;
  773. var res = null;
  774. var resName = null;
  775. for(var i in Resolutions)
  776. {
  777. var tmp = Resolutions[i];
  778. if(res == null || (res.order < tmp.order && tmp.order < order))
  779. {
  780. resName = i;
  781. res = tmp;
  782. }
  783. }
  784. return resName;
  785. }
  786. function setResolutionConstraints(constraints, resolution, isAndroid)
  787. {
  788. if (resolution && !constraints.video || isAndroid) {
  789. constraints.video = { mandatory: {}, optional: [] };// same behaviour as true
  790. }
  791. if(Resolutions[resolution])
  792. {
  793. constraints.video.mandatory.minWidth = Resolutions[resolution].width;
  794. constraints.video.mandatory.minHeight = Resolutions[resolution].height;
  795. }
  796. else
  797. {
  798. if (isAndroid) {
  799. constraints.video.mandatory.minWidth = 320;
  800. constraints.video.mandatory.minHeight = 240;
  801. constraints.video.mandatory.maxFrameRate = 15;
  802. }
  803. }
  804. if (constraints.video.mandatory.minWidth)
  805. constraints.video.mandatory.maxWidth = constraints.video.mandatory.minWidth;
  806. if (constraints.video.mandatory.minHeight)
  807. constraints.video.mandatory.maxHeight = constraints.video.mandatory.minHeight;
  808. }
  809. function getConstraints(um, resolution, bandwidth, fps, desktopStream, isAndroid)
  810. {
  811. var constraints = {audio: false, video: false};
  812. if (um.indexOf('video') >= 0) {
  813. constraints.video = { mandatory: {}, optional: [] };// same behaviour as true
  814. }
  815. if (um.indexOf('audio') >= 0) {
  816. constraints.audio = { mandatory: {}, optional: []};// same behaviour as true
  817. }
  818. if (um.indexOf('screen') >= 0) {
  819. constraints.video = {
  820. mandatory: {
  821. chromeMediaSource: "screen",
  822. googLeakyBucket: true,
  823. maxWidth: window.screen.width,
  824. maxHeight: window.screen.height,
  825. maxFrameRate: 3
  826. },
  827. optional: []
  828. };
  829. }
  830. if (um.indexOf('desktop') >= 0) {
  831. constraints.video = {
  832. mandatory: {
  833. chromeMediaSource: "desktop",
  834. chromeMediaSourceId: desktopStream,
  835. googLeakyBucket: true,
  836. maxWidth: window.screen.width,
  837. maxHeight: window.screen.height,
  838. maxFrameRate: 3
  839. },
  840. optional: []
  841. };
  842. }
  843. if (constraints.audio) {
  844. // if it is good enough for hangouts...
  845. constraints.audio.optional.push(
  846. {googEchoCancellation: true},
  847. {googAutoGainControl: true},
  848. {googNoiseSupression: true},
  849. {googHighpassFilter: true},
  850. {googNoisesuppression2: true},
  851. {googEchoCancellation2: true},
  852. {googAutoGainControl2: true}
  853. );
  854. }
  855. if (constraints.video) {
  856. constraints.video.optional.push(
  857. {googNoiseReduction: false} // chrome 37 workaround for issue 3807, reenable in M38
  858. );
  859. if (um.indexOf('video') >= 0) {
  860. constraints.video.optional.push(
  861. {googLeakyBucket: true}
  862. );
  863. }
  864. }
  865. if (um.indexOf('video') >= 0) {
  866. setResolutionConstraints(constraints, resolution, isAndroid);
  867. }
  868. if (bandwidth) { // doesn't work currently, see webrtc issue 1846
  869. if (!constraints.video) constraints.video = {mandatory: {}, optional: []};//same behaviour as true
  870. constraints.video.optional.push({bandwidth: bandwidth});
  871. }
  872. if (fps) { // for some cameras it might be necessary to request 30fps
  873. // so they choose 30fps mjpg over 10fps yuy2
  874. if (!constraints.video) constraints.video = {mandatory: {}, optional: []};// same behaviour as true;
  875. constraints.video.mandatory.minFrameRate = fps;
  876. }
  877. return constraints;
  878. }
  879. function RTCUtils(RTCService)
  880. {
  881. this.service = RTCService;
  882. if (navigator.mozGetUserMedia) {
  883. console.log('This appears to be Firefox');
  884. var version = parseInt(navigator.userAgent.match(/Firefox\/([0-9]+)\./)[1], 10);
  885. if (version >= 22) {
  886. this.peerconnection = mozRTCPeerConnection;
  887. this.browser = RTCBrowserType.RTC_BROWSER_FIREFOX;
  888. this.getUserMedia = navigator.mozGetUserMedia.bind(navigator);
  889. this.pc_constraints = {};
  890. this.attachMediaStream = function (element, stream) {
  891. // srcObject is being standardized and FF will eventually
  892. // support that unprefixed. FF also supports the
  893. // "element.src = URL.createObjectURL(...)" combo, but that
  894. // will be deprecated in favour of srcObject.
  895. //
  896. // https://groups.google.com/forum/#!topic/mozilla.dev.media/pKOiioXonJg
  897. // https://github.com/webrtc/samples/issues/302
  898. element[0].mozSrcObject = stream;
  899. element[0].play();
  900. };
  901. this.getStreamID = function (stream) {
  902. var tracks = stream.getVideoTracks();
  903. if(!tracks || tracks.length == 0)
  904. {
  905. tracks = stream.getAudioTracks();
  906. }
  907. return tracks[0].id.replace(/[\{,\}]/g,"");
  908. };
  909. this.getVideoSrc = function (element) {
  910. return element.mozSrcObject;
  911. };
  912. this.setVideoSrc = function (element, src) {
  913. element.mozSrcObject = src;
  914. };
  915. RTCSessionDescription = mozRTCSessionDescription;
  916. RTCIceCandidate = mozRTCIceCandidate;
  917. }
  918. } else if (navigator.webkitGetUserMedia) {
  919. console.log('This appears to be Chrome');
  920. this.peerconnection = webkitRTCPeerConnection;
  921. this.browser = RTCBrowserType.RTC_BROWSER_CHROME;
  922. this.getUserMedia = navigator.webkitGetUserMedia.bind(navigator);
  923. this.attachMediaStream = function (element, stream) {
  924. element.attr('src', webkitURL.createObjectURL(stream));
  925. };
  926. this.getStreamID = function (stream) {
  927. // streams from FF endpoints have the characters '{' and '}'
  928. // that make jQuery choke.
  929. return stream.id.replace(/[\{,\}]/g,"");
  930. };
  931. this.getVideoSrc = function (element) {
  932. return element.getAttribute("src");
  933. };
  934. this.setVideoSrc = function (element, src) {
  935. element.setAttribute("src", src);
  936. };
  937. // DTLS should now be enabled by default but..
  938. this.pc_constraints = {'optional': [{'DtlsSrtpKeyAgreement': 'true'}]};
  939. if (navigator.userAgent.indexOf('Android') != -1) {
  940. this.pc_constraints = {}; // disable DTLS on Android
  941. }
  942. if (!webkitMediaStream.prototype.getVideoTracks) {
  943. webkitMediaStream.prototype.getVideoTracks = function () {
  944. return this.videoTracks;
  945. };
  946. }
  947. if (!webkitMediaStream.prototype.getAudioTracks) {
  948. webkitMediaStream.prototype.getAudioTracks = function () {
  949. return this.audioTracks;
  950. };
  951. }
  952. }
  953. else
  954. {
  955. try { console.log('Browser does not appear to be WebRTC-capable'); } catch (e) { }
  956. window.location.href = 'unsupported_browser.html';
  957. return;
  958. }
  959. if (this.browser !== RTCBrowserType.RTC_BROWSER_CHROME &&
  960. config.enableFirefoxSupport !== true) {
  961. window.location.href = 'unsupported_browser.html';
  962. return;
  963. }
  964. }
  965. RTCUtils.prototype.getUserMediaWithConstraints = function(
  966. um, success_callback, failure_callback, resolution,bandwidth, fps,
  967. desktopStream)
  968. {
  969. currentResolution = resolution;
  970. // Check if we are running on Android device
  971. var isAndroid = navigator.userAgent.indexOf('Android') != -1;
  972. var constraints = getConstraints(
  973. um, resolution, bandwidth, fps, desktopStream, isAndroid);
  974. var isFF = navigator.userAgent.toLowerCase().indexOf('firefox') > -1;
  975. try {
  976. if (config.enableSimulcast
  977. && constraints.video
  978. && constraints.video.chromeMediaSource !== 'screen'
  979. && constraints.video.chromeMediaSource !== 'desktop'
  980. && !isAndroid
  981. // We currently do not support FF, as it doesn't have multistream support.
  982. && !isFF) {
  983. APP.simulcast.getUserMedia(constraints, function (stream) {
  984. console.log('onUserMediaSuccess');
  985. success_callback(stream);
  986. },
  987. function (error) {
  988. console.warn('Failed to get access to local media. Error ', error);
  989. if (failure_callback) {
  990. failure_callback(error);
  991. }
  992. });
  993. } else {
  994. this.getUserMedia(constraints,
  995. function (stream) {
  996. console.log('onUserMediaSuccess');
  997. success_callback(stream);
  998. },
  999. function (error) {
  1000. console.warn('Failed to get access to local media. Error ',
  1001. error, constraints);
  1002. if (failure_callback) {
  1003. failure_callback(error);
  1004. }
  1005. });
  1006. }
  1007. } catch (e) {
  1008. console.error('GUM failed: ', e);
  1009. if(failure_callback) {
  1010. failure_callback(e);
  1011. }
  1012. }
  1013. };
  1014. /**
  1015. * We ask for audio and video combined stream in order to get permissions and
  1016. * not to ask twice.
  1017. */
  1018. RTCUtils.prototype.obtainAudioAndVideoPermissions = function() {
  1019. var self = this;
  1020. // Get AV
  1021. this.getUserMediaWithConstraints(
  1022. ['audio', 'video'],
  1023. function (stream) {
  1024. self.successCallback(stream);
  1025. },
  1026. function (error) {
  1027. self.errorCallback(error);
  1028. },
  1029. config.resolution || '360');
  1030. }
  1031. RTCUtils.prototype.successCallback = function (stream) {
  1032. console.log('got', stream, stream.getAudioTracks().length,
  1033. stream.getVideoTracks().length);
  1034. this.handleLocalStream(stream);
  1035. };
  1036. RTCUtils.prototype.errorCallback = function (error) {
  1037. var self = this;
  1038. console.error('failed to obtain audio/video stream - trying audio only', error);
  1039. var resolution = getPreviousResolution(currentResolution);
  1040. if(typeof error == "object" && error.constraintName && error.name
  1041. && (error.name == "ConstraintNotSatisfiedError" ||
  1042. error.name == "OverconstrainedError") &&
  1043. (error.constraintName == "minWidth" || error.constraintName == "maxWidth" ||
  1044. error.constraintName == "minHeight" || error.constraintName == "maxHeight")
  1045. && resolution != null)
  1046. {
  1047. self.getUserMediaWithConstraints(['audio', 'video'],
  1048. function (stream) {
  1049. return self.successCallback(stream);
  1050. }, function (error) {
  1051. return self.errorCallback(error);
  1052. }, resolution);
  1053. }
  1054. else
  1055. {
  1056. self.getUserMediaWithConstraints(
  1057. ['audio'],
  1058. function (stream) {
  1059. return self.successCallback(stream);
  1060. },
  1061. function (error) {
  1062. console.error('failed to obtain audio/video stream - stop',
  1063. error);
  1064. APP.UI.messageHandler.showError("dialog.error",
  1065. "dialog.failedpermissions");
  1066. }
  1067. );
  1068. }
  1069. }
  1070. RTCUtils.prototype.handleLocalStream = function(stream)
  1071. {
  1072. if(window.webkitMediaStream)
  1073. {
  1074. var audioStream = new webkitMediaStream();
  1075. var videoStream = new webkitMediaStream();
  1076. var audioTracks = stream.getAudioTracks();
  1077. var videoTracks = stream.getVideoTracks();
  1078. for (var i = 0; i < audioTracks.length; i++) {
  1079. audioStream.addTrack(audioTracks[i]);
  1080. }
  1081. this.service.createLocalStream(audioStream, "audio");
  1082. for (i = 0; i < videoTracks.length; i++) {
  1083. videoStream.addTrack(videoTracks[i]);
  1084. }
  1085. this.service.createLocalStream(videoStream, "video");
  1086. }
  1087. else
  1088. {//firefox
  1089. this.service.createLocalStream(stream, "stream");
  1090. }
  1091. };
  1092. module.exports = RTCUtils;
  1093. },{"../../service/RTC/RTCBrowserType.js":87,"../../service/RTC/Resolutions":89}],8:[function(require,module,exports){
  1094. var UI = {};
  1095. var VideoLayout = require("./videolayout/VideoLayout.js");
  1096. var AudioLevels = require("./audio_levels/AudioLevels.js");
  1097. var Prezi = require("./prezi/Prezi.js");
  1098. var Etherpad = require("./etherpad/Etherpad.js");
  1099. var Chat = require("./side_pannels/chat/Chat.js");
  1100. var Toolbar = require("./toolbars/Toolbar");
  1101. var ToolbarToggler = require("./toolbars/ToolbarToggler");
  1102. var BottomToolbar = require("./toolbars/BottomToolbar");
  1103. var ContactList = require("./side_pannels/contactlist/ContactList");
  1104. var Avatar = require("./avatar/Avatar");
  1105. var EventEmitter = require("events");
  1106. var SettingsMenu = require("./side_pannels/settings/SettingsMenu");
  1107. var Settings = require("./../settings/Settings");
  1108. var PanelToggler = require("./side_pannels/SidePanelToggler");
  1109. var RoomNameGenerator = require("./welcome_page/RoomnameGenerator");
  1110. UI.messageHandler = require("./util/MessageHandler");
  1111. var messageHandler = UI.messageHandler;
  1112. var Authentication = require("./authentication/Authentication");
  1113. var UIUtil = require("./util/UIUtil");
  1114. var NicknameHandler = require("./util/NicknameHandler");
  1115. var CQEvents = require("../../service/connectionquality/CQEvents");
  1116. var DesktopSharingEventTypes
  1117. = require("../../service/desktopsharing/DesktopSharingEventTypes");
  1118. var RTCEvents = require("../../service/RTC/RTCEvents");
  1119. var StreamEventTypes = require("../../service/RTC/StreamEventTypes");
  1120. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  1121. var eventEmitter = new EventEmitter();
  1122. var roomName = null;
  1123. function setupPrezi()
  1124. {
  1125. $("#reloadPresentationLink").click(function()
  1126. {
  1127. Prezi.reloadPresentation();
  1128. });
  1129. }
  1130. function setupChat()
  1131. {
  1132. Chat.init();
  1133. $("#toggle_smileys").click(function() {
  1134. Chat.toggleSmileys();
  1135. });
  1136. }
  1137. function setupToolbars() {
  1138. Toolbar.init(UI);
  1139. Toolbar.setupButtonsFromConfig();
  1140. BottomToolbar.init();
  1141. }
  1142. function streamHandler(stream) {
  1143. switch (stream.type)
  1144. {
  1145. case "audio":
  1146. VideoLayout.changeLocalAudio(stream);
  1147. break;
  1148. case "video":
  1149. VideoLayout.changeLocalVideo(stream);
  1150. break;
  1151. case "stream":
  1152. VideoLayout.changeLocalStream(stream);
  1153. break;
  1154. }
  1155. }
  1156. function onDisposeConference(unload) {
  1157. Toolbar.showAuthenticateButton(false);
  1158. };
  1159. function onDisplayNameChanged(jid, displayName) {
  1160. ContactList.onDisplayNameChange(jid, displayName);
  1161. SettingsMenu.onDisplayNameChange(jid, displayName);
  1162. VideoLayout.onDisplayNameChanged(jid, displayName);
  1163. }
  1164. function registerListeners() {
  1165. APP.RTC.addStreamListener(streamHandler, StreamEventTypes.EVENT_TYPE_LOCAL_CREATED);
  1166. APP.RTC.addStreamListener(streamHandler, StreamEventTypes.EVENT_TYPE_LOCAL_CHANGED);
  1167. APP.RTC.addStreamListener(function (stream) {
  1168. VideoLayout.onRemoteStreamAdded(stream);
  1169. }, StreamEventTypes.EVENT_TYPE_REMOTE_CREATED);
  1170. APP.RTC.addListener(RTCEvents.LASTN_CHANGED, onLastNChanged);
  1171. APP.RTC.addListener(RTCEvents.DOMINANTSPEAKER_CHANGED, function (resourceJid) {
  1172. VideoLayout.onDominantSpeakerChanged(resourceJid);
  1173. });
  1174. APP.RTC.addListener(RTCEvents.LASTN_ENDPOINT_CHANGED,
  1175. function (lastNEndpoints, endpointsEnteringLastN, stream) {
  1176. VideoLayout.onLastNEndpointsChanged(lastNEndpoints,
  1177. endpointsEnteringLastN, stream);
  1178. });
  1179. APP.RTC.addListener(RTCEvents.SIMULCAST_LAYER_CHANGED,
  1180. function (endpointSimulcastLayers) {
  1181. VideoLayout.onSimulcastLayersChanged(endpointSimulcastLayers);
  1182. });
  1183. APP.RTC.addListener(RTCEvents.SIMULCAST_LAYER_CHANGING,
  1184. function (endpointSimulcastLayers) {
  1185. VideoLayout.onSimulcastLayersChanging(endpointSimulcastLayers);
  1186. });
  1187. APP.statistics.addAudioLevelListener(function(jid, audioLevel)
  1188. {
  1189. var resourceJid;
  1190. if(jid === APP.statistics.LOCAL_JID)
  1191. {
  1192. resourceJid = AudioLevels.LOCAL_LEVEL;
  1193. if(APP.RTC.localAudio.isMuted())
  1194. {
  1195. audioLevel = 0;
  1196. }
  1197. }
  1198. else
  1199. {
  1200. resourceJid = Strophe.getResourceFromJid(jid);
  1201. }
  1202. AudioLevels.updateAudioLevel(resourceJid, audioLevel,
  1203. UI.getLargeVideoState().userResourceJid);
  1204. });
  1205. APP.desktopsharing.addListener(function () {
  1206. ToolbarToggler.showDesktopSharingButton();
  1207. }, DesktopSharingEventTypes.INIT);
  1208. APP.desktopsharing.addListener(
  1209. Toolbar.changeDesktopSharingButtonState,
  1210. DesktopSharingEventTypes.SWITCHING_DONE);
  1211. APP.connectionquality.addListener(CQEvents.LOCALSTATS_UPDATED,
  1212. VideoLayout.updateLocalConnectionStats);
  1213. APP.connectionquality.addListener(CQEvents.REMOTESTATS_UPDATED,
  1214. VideoLayout.updateConnectionStats);
  1215. APP.connectionquality.addListener(CQEvents.STOP,
  1216. VideoLayout.onStatsStop);
  1217. APP.xmpp.addListener(XMPPEvents.DISPOSE_CONFERENCE, onDisposeConference);
  1218. APP.xmpp.addListener(XMPPEvents.GRACEFUL_SHUTDOWN, function () {
  1219. messageHandler.openMessageDialog(
  1220. 'dialog.serviceUnavailable',
  1221. 'dialog.gracefulShutdown'
  1222. );
  1223. });
  1224. APP.xmpp.addListener(XMPPEvents.RESERVATION_ERROR, function (code, msg) {
  1225. var title = APP.translation.generateTranslatonHTML(
  1226. "dialog.reservationError");
  1227. var message = APP.translation.generateTranslatonHTML(
  1228. "dialog.reservationErrorMsg", {code: code, msg: msg});
  1229. messageHandler.openDialog(
  1230. title,
  1231. message,
  1232. true, {},
  1233. function (event, value, message, formVals)
  1234. {
  1235. return false;
  1236. }
  1237. );
  1238. });
  1239. APP.xmpp.addListener(XMPPEvents.KICKED, function () {
  1240. messageHandler.openMessageDialog("dialog.sessTerminated",
  1241. "dialog.kickMessage");
  1242. });
  1243. APP.xmpp.addListener(XMPPEvents.MUC_DESTROYED, function (reason) {
  1244. //FIXME: use Session Terminated from translation, but
  1245. // 'reason' text comes from XMPP packet and is not translated
  1246. var title = APP.translation.generateTranslatonHTML("dialog.sessTerminated");
  1247. messageHandler.openDialog(
  1248. title, reason, true, {},
  1249. function (event, value, message, formVals)
  1250. {
  1251. return false;
  1252. }
  1253. );
  1254. });
  1255. APP.xmpp.addListener(XMPPEvents.BRIDGE_DOWN, function () {
  1256. messageHandler.showError("dialog.error",
  1257. "dialog.bridgeUnavailable");
  1258. });
  1259. APP.xmpp.addListener(XMPPEvents.USER_ID_CHANGED, function (from, id) {
  1260. Avatar.setUserAvatar(from, id);
  1261. });
  1262. APP.xmpp.addListener(XMPPEvents.CHANGED_STREAMS, function (jid, changedStreams) {
  1263. for(stream in changedStreams)
  1264. {
  1265. // might need to update the direction if participant just went from sendrecv to recvonly
  1266. if (stream.type === 'video' || stream.type === 'screen') {
  1267. var el = $('#participant_' + Strophe.getResourceFromJid(jid) + '>video');
  1268. switch (stream.direction) {
  1269. case 'sendrecv':
  1270. el.show();
  1271. break;
  1272. case 'recvonly':
  1273. el.hide();
  1274. // FIXME: Check if we have to change large video
  1275. //VideoLayout.updateLargeVideo(el);
  1276. break;
  1277. }
  1278. }
  1279. }
  1280. });
  1281. APP.xmpp.addListener(XMPPEvents.DISPLAY_NAME_CHANGED, onDisplayNameChanged);
  1282. APP.xmpp.addListener(XMPPEvents.MUC_JOINED, onMucJoined);
  1283. APP.xmpp.addListener(XMPPEvents.LOCALROLE_CHANGED, onLocalRoleChange);
  1284. APP.xmpp.addListener(XMPPEvents.MUC_ENTER, onMucEntered);
  1285. APP.xmpp.addListener(XMPPEvents.MUC_ROLE_CHANGED, onMucRoleChanged);
  1286. APP.xmpp.addListener(XMPPEvents.PRESENCE_STATUS, onMucPresenceStatus);
  1287. APP.xmpp.addListener(XMPPEvents.SUBJECT_CHANGED, chatSetSubject);
  1288. APP.xmpp.addListener(XMPPEvents.MESSAGE_RECEIVED, updateChatConversation);
  1289. APP.xmpp.addListener(XMPPEvents.MUC_LEFT, onMucLeft);
  1290. APP.xmpp.addListener(XMPPEvents.PASSWORD_REQUIRED, onPasswordReqiured);
  1291. APP.xmpp.addListener(XMPPEvents.CHAT_ERROR_RECEIVED, chatAddError);
  1292. APP.xmpp.addListener(XMPPEvents.ETHERPAD, initEtherpad);
  1293. APP.xmpp.addListener(XMPPEvents.AUTHENTICATION_REQUIRED, onAuthenticationRequired);
  1294. }
  1295. /**
  1296. * Mutes/unmutes the local video.
  1297. *
  1298. * @param mute <tt>true</tt> to mute the local video; otherwise, <tt>false</tt>
  1299. * @param options an object which specifies optional arguments such as the
  1300. * <tt>boolean</tt> key <tt>byUser</tt> with default value <tt>true</tt> which
  1301. * specifies whether the method was initiated in response to a user command (in
  1302. * contrast to an automatic decision taken by the application logic)
  1303. */
  1304. function setVideoMute(mute, options) {
  1305. APP.xmpp.setVideoMute(
  1306. mute,
  1307. function (mute) {
  1308. var video = $('#video');
  1309. var communicativeClass = "icon-camera";
  1310. var muteClass = "icon-camera icon-camera-disabled";
  1311. if (mute) {
  1312. video.removeClass(communicativeClass);
  1313. video.addClass(muteClass);
  1314. } else {
  1315. video.removeClass(muteClass);
  1316. video.addClass(communicativeClass);
  1317. }
  1318. },
  1319. options);
  1320. }
  1321. function bindEvents()
  1322. {
  1323. /**
  1324. * Resizes and repositions videos in full screen mode.
  1325. */
  1326. $(document).on('webkitfullscreenchange mozfullscreenchange fullscreenchange',
  1327. function () {
  1328. VideoLayout.resizeLargeVideoContainer();
  1329. VideoLayout.positionLarge();
  1330. }
  1331. );
  1332. $(window).resize(function () {
  1333. VideoLayout.resizeLargeVideoContainer();
  1334. VideoLayout.positionLarge();
  1335. });
  1336. }
  1337. UI.start = function (init) {
  1338. document.title = interfaceConfig.APP_NAME;
  1339. if(config.enableWelcomePage && window.location.pathname == "/" &&
  1340. (!window.localStorage.welcomePageDisabled || window.localStorage.welcomePageDisabled == "false"))
  1341. {
  1342. $("#videoconference_page").hide();
  1343. var setupWelcomePage = require("./welcome_page/WelcomePage");
  1344. setupWelcomePage();
  1345. return;
  1346. }
  1347. if (interfaceConfig.SHOW_JITSI_WATERMARK) {
  1348. var leftWatermarkDiv
  1349. = $("#largeVideoContainer div[class='watermark leftwatermark']");
  1350. leftWatermarkDiv.css({display: 'block'});
  1351. leftWatermarkDiv.parent().get(0).href
  1352. = interfaceConfig.JITSI_WATERMARK_LINK;
  1353. }
  1354. if (interfaceConfig.SHOW_BRAND_WATERMARK) {
  1355. var rightWatermarkDiv
  1356. = $("#largeVideoContainer div[class='watermark rightwatermark']");
  1357. rightWatermarkDiv.css({display: 'block'});
  1358. rightWatermarkDiv.parent().get(0).href
  1359. = interfaceConfig.BRAND_WATERMARK_LINK;
  1360. rightWatermarkDiv.get(0).style.backgroundImage
  1361. = "url(images/rightwatermark.png)";
  1362. }
  1363. if (interfaceConfig.SHOW_POWERED_BY) {
  1364. $("#largeVideoContainer>a[class='poweredby']").css({display: 'block'});
  1365. }
  1366. $("#welcome_page").hide();
  1367. VideoLayout.resizeLargeVideoContainer();
  1368. $("#videospace").mousemove(function () {
  1369. return ToolbarToggler.showToolbar();
  1370. });
  1371. // Set the defaults for prompt dialogs.
  1372. jQuery.prompt.setDefaults({persistent: false});
  1373. VideoLayout.init(eventEmitter);
  1374. AudioLevels.init();
  1375. NicknameHandler.init(eventEmitter);
  1376. registerListeners();
  1377. bindEvents();
  1378. setupPrezi();
  1379. setupToolbars();
  1380. setupChat();
  1381. document.title = interfaceConfig.APP_NAME;
  1382. $("#downloadlog").click(function (event) {
  1383. dump(event.target);
  1384. });
  1385. if(config.enableWelcomePage && window.location.pathname == "/" &&
  1386. (!window.localStorage.welcomePageDisabled || window.localStorage.welcomePageDisabled == "false"))
  1387. {
  1388. $("#videoconference_page").hide();
  1389. var setupWelcomePage = require("./welcome_page/WelcomePage");
  1390. setupWelcomePage();
  1391. return;
  1392. }
  1393. $("#welcome_page").hide();
  1394. document.getElementById('largeVideo').volume = 0;
  1395. if (!$('#settings').is(':visible')) {
  1396. console.log('init');
  1397. init();
  1398. } else {
  1399. loginInfo.onsubmit = function (e) {
  1400. if (e.preventDefault) e.preventDefault();
  1401. $('#settings').hide();
  1402. init();
  1403. };
  1404. }
  1405. toastr.options = {
  1406. "closeButton": true,
  1407. "debug": false,
  1408. "positionClass": "notification-bottom-right",
  1409. "onclick": null,
  1410. "showDuration": "300",
  1411. "hideDuration": "1000",
  1412. "timeOut": "2000",
  1413. "extendedTimeOut": "1000",
  1414. "showEasing": "swing",
  1415. "hideEasing": "linear",
  1416. "showMethod": "fadeIn",
  1417. "hideMethod": "fadeOut",
  1418. "reposition": function() {
  1419. if(PanelToggler.isVisible()) {
  1420. $("#toast-container").addClass("notification-bottom-right-center");
  1421. } else {
  1422. $("#toast-container").removeClass("notification-bottom-right-center");
  1423. }
  1424. },
  1425. "newestOnTop": false
  1426. };
  1427. SettingsMenu.init();
  1428. };
  1429. function chatAddError(errorMessage, originalText)
  1430. {
  1431. return Chat.chatAddError(errorMessage, originalText);
  1432. };
  1433. function chatSetSubject(text)
  1434. {
  1435. return Chat.chatSetSubject(text);
  1436. };
  1437. function updateChatConversation(from, displayName, message) {
  1438. return Chat.updateChatConversation(from, displayName, message);
  1439. };
  1440. function onMucJoined(jid, info) {
  1441. Toolbar.updateRoomUrl(window.location.href);
  1442. var meHTML = APP.translation.generateTranslatonHTML("me");
  1443. $("#localNick").html(Strophe.getResourceFromJid(jid) + " (" + meHTML + ")");
  1444. var settings = Settings.getSettings();
  1445. // Add myself to the contact list.
  1446. ContactList.addContact(jid, settings.email || settings.uid);
  1447. // Once we've joined the muc show the toolbar
  1448. ToolbarToggler.showToolbar();
  1449. var displayName = !config.displayJids
  1450. ? info.displayName : Strophe.getResourceFromJid(jid);
  1451. if (displayName)
  1452. onDisplayNameChanged('localVideoContainer', displayName);
  1453. }
  1454. function initEtherpad(name) {
  1455. Etherpad.init(name);
  1456. };
  1457. function onMucLeft(jid) {
  1458. console.log('left.muc', jid);
  1459. var displayName = $('#participant_' + Strophe.getResourceFromJid(jid) +
  1460. '>.displayname').html();
  1461. messageHandler.notify(displayName,'notify.somebody',
  1462. 'disconnected',
  1463. 'notify.disconnected');
  1464. // Need to call this with a slight delay, otherwise the element couldn't be
  1465. // found for some reason.
  1466. // XXX(gp) it works fine without the timeout for me (with Chrome 38).
  1467. window.setTimeout(function () {
  1468. var container = document.getElementById(
  1469. 'participant_' + Strophe.getResourceFromJid(jid));
  1470. if (container) {
  1471. ContactList.removeContact(jid);
  1472. VideoLayout.removeConnectionIndicator(jid);
  1473. // hide here, wait for video to close before removing
  1474. $(container).hide();
  1475. VideoLayout.resizeThumbnails();
  1476. }
  1477. }, 10);
  1478. VideoLayout.participantLeft(jid);
  1479. };
  1480. function onLocalRoleChange(jid, info, pres, isModerator)
  1481. {
  1482. console.info("My role changed, new role: " + info.role);
  1483. onModeratorStatusChanged(isModerator);
  1484. VideoLayout.showModeratorIndicator();
  1485. if (isModerator) {
  1486. Authentication.closeAuthenticationWindow();
  1487. messageHandler.notify(null, "notify.me",
  1488. 'connected', "notify.moderator");
  1489. }
  1490. }
  1491. function onModeratorStatusChanged(isModerator) {
  1492. Toolbar.showSipCallButton(isModerator);
  1493. Toolbar.showRecordingButton(
  1494. isModerator); //&&
  1495. // FIXME:
  1496. // Recording visible if
  1497. // there are at least 2(+ 1 focus) participants
  1498. //Object.keys(connection.emuc.members).length >= 3);
  1499. if (isModerator && config.etherpad_base) {
  1500. Etherpad.init();
  1501. }
  1502. };
  1503. function onPasswordReqiured(callback) {
  1504. // password is required
  1505. Toolbar.lockLockButton();
  1506. var message = '<h2 data-i18n="dialog.passwordRequired">';
  1507. message += APP.translation.translateString(
  1508. "dialog.passwordRequired");
  1509. message += '</h2>' +
  1510. '<input id="lockKey" type="text" data-i18n=' +
  1511. '"[placeholder]dialog.password" placeholder="' +
  1512. APP.translation.translateString("dialog.password") +
  1513. '" autofocus>';
  1514. messageHandler.openTwoButtonDialog(null, null, null, message,
  1515. true,
  1516. "dialog.Ok",
  1517. function (e, v, m, f) {},
  1518. function (event) {
  1519. document.getElementById('lockKey').focus();
  1520. },
  1521. function (e, v, m, f) {
  1522. if (v) {
  1523. var lockKey = document.getElementById('lockKey');
  1524. if (lockKey.value !== null) {
  1525. Toolbar.setSharedKey(lockKey.value);
  1526. callback(lockKey.value);
  1527. }
  1528. }
  1529. }
  1530. );
  1531. }
  1532. function onMucEntered(jid, id, displayName) {
  1533. messageHandler.notify(displayName,'notify.somebody',
  1534. 'connected',
  1535. 'notify.connected');
  1536. // Add Peer's container
  1537. VideoLayout.ensurePeerContainerExists(jid,id);
  1538. }
  1539. function onMucPresenceStatus( jid, info) {
  1540. VideoLayout.setPresenceStatus(
  1541. 'participant_' + Strophe.getResourceFromJid(jid), info.status);
  1542. }
  1543. function onMucRoleChanged(role, displayName) {
  1544. VideoLayout.showModeratorIndicator();
  1545. if (role === 'moderator') {
  1546. var messageKey, messageOptions = {};
  1547. if (!displayName) {
  1548. messageKey = "notify.grantedToUnknown";
  1549. }
  1550. else
  1551. {
  1552. messageKey = "notify.grantedTo";
  1553. messageOptions = {to: displayName};
  1554. }
  1555. messageHandler.notify(
  1556. displayName,'notify.somebody',
  1557. 'connected', messageKey,
  1558. messageOptions);
  1559. }
  1560. }
  1561. function onAuthenticationRequired(intervalCallback) {
  1562. Authentication.openAuthenticationDialog(
  1563. roomName, intervalCallback, function () {
  1564. Toolbar.authenticateClicked();
  1565. });
  1566. };
  1567. function onLastNChanged(oldValue, newValue) {
  1568. if (config.muteLocalVideoIfNotInLastN) {
  1569. setVideoMute(!newValue, { 'byUser': false });
  1570. }
  1571. }
  1572. UI.toggleSmileys = function () {
  1573. Chat.toggleSmileys();
  1574. };
  1575. UI.getSettings = function () {
  1576. return Settings.getSettings();
  1577. };
  1578. UI.toggleFilmStrip = function () {
  1579. return BottomToolbar.toggleFilmStrip();
  1580. };
  1581. UI.toggleChat = function () {
  1582. return BottomToolbar.toggleChat();
  1583. };
  1584. UI.toggleContactList = function () {
  1585. return BottomToolbar.toggleContactList();
  1586. };
  1587. UI.inputDisplayNameHandler = function (value) {
  1588. VideoLayout.inputDisplayNameHandler(value);
  1589. };
  1590. UI.getLargeVideoState = function()
  1591. {
  1592. return VideoLayout.getLargeVideoState();
  1593. };
  1594. UI.generateRoomName = function() {
  1595. if(roomName)
  1596. return roomName;
  1597. var roomnode = null;
  1598. var path = window.location.pathname;
  1599. // determinde the room node from the url
  1600. // TODO: just the roomnode or the whole bare jid?
  1601. if (config.getroomnode && typeof config.getroomnode === 'function') {
  1602. // custom function might be responsible for doing the pushstate
  1603. roomnode = config.getroomnode(path);
  1604. } else {
  1605. /* fall back to default strategy
  1606. * this is making assumptions about how the URL->room mapping happens.
  1607. * It currently assumes deployment at root, with a rewrite like the
  1608. * following one (for nginx):
  1609. location ~ ^/([a-zA-Z0-9]+)$ {
  1610. rewrite ^/(.*)$ / break;
  1611. }
  1612. */
  1613. if (path.length > 1) {
  1614. roomnode = path.substr(1).toLowerCase();
  1615. } else {
  1616. var word = RoomNameGenerator.generateRoomWithoutSeparator();
  1617. roomnode = word.toLowerCase();
  1618. window.history.pushState('VideoChat',
  1619. 'Room: ' + word, window.location.pathname + word);
  1620. }
  1621. }
  1622. roomName = roomnode + '@' + config.hosts.muc;
  1623. return roomName;
  1624. };
  1625. UI.connectionIndicatorShowMore = function(id)
  1626. {
  1627. return VideoLayout.connectionIndicators[id].showMore();
  1628. };
  1629. UI.getCredentials = function () {
  1630. var settings = this.getSettings();
  1631. return {
  1632. bosh: document.getElementById('boshURL').value,
  1633. password: document.getElementById('password').value,
  1634. jid: document.getElementById('jid').value,
  1635. email: settings.email,
  1636. displayName: settings.displayName,
  1637. uid: settings.uid
  1638. };
  1639. };
  1640. UI.disableConnect = function () {
  1641. document.getElementById('connect').disabled = true;
  1642. };
  1643. UI.showLoginPopup = function(callback)
  1644. {
  1645. console.log('password is required');
  1646. var message = '<h2 data-i18n="dialog.passwordRequired">';
  1647. message += APP.translation.translateString(
  1648. "dialog.passwordRequired");
  1649. message += '</h2>' +
  1650. '<input id="passwordrequired.username" type="text" ' +
  1651. 'placeholder="user@domain.net" autofocus>' +
  1652. '<input id="passwordrequired.password" ' +
  1653. 'type="password" data-i18n="[placeholder]dialog.userPassword"' +
  1654. ' placeholder="user password">';
  1655. UI.messageHandler.openTwoButtonDialog(null, null, null, message,
  1656. true,
  1657. "dialog.Ok",
  1658. function (e, v, m, f) {
  1659. if (v) {
  1660. var username = document.getElementById('passwordrequired.username');
  1661. var password = document.getElementById('passwordrequired.password');
  1662. if (username.value !== null && password.value != null) {
  1663. callback(username.value, password.value);
  1664. }
  1665. }
  1666. },
  1667. function (event) {
  1668. document.getElementById('passwordrequired.username').focus();
  1669. }
  1670. );
  1671. }
  1672. UI.checkForNicknameAndJoin = function () {
  1673. Authentication.closeAuthenticationDialog();
  1674. Authentication.stopInterval();
  1675. var nick = null;
  1676. if (config.useNicks) {
  1677. nick = window.prompt('Your nickname (optional)');
  1678. }
  1679. APP.xmpp.joinRoom(roomName, config.useNicks, nick);
  1680. };
  1681. function dump(elem, filename) {
  1682. elem = elem.parentNode;
  1683. elem.download = filename || 'meetlog.json';
  1684. elem.href = 'data:application/json;charset=utf-8,\n';
  1685. var data = APP.xmpp.populateData();
  1686. var metadata = {};
  1687. metadata.time = new Date();
  1688. metadata.url = window.location.href;
  1689. metadata.ua = navigator.userAgent;
  1690. var log = APP.xmpp.getLogger();
  1691. if (log) {
  1692. metadata.xmpp = log;
  1693. }
  1694. data.metadata = metadata;
  1695. elem.href += encodeURIComponent(JSON.stringify(data, null, ' '));
  1696. return false;
  1697. }
  1698. UI.getRoomName = function () {
  1699. return roomName;
  1700. };
  1701. /**
  1702. * Mutes/unmutes the local video.
  1703. */
  1704. UI.toggleVideo = function () {
  1705. UIUtil.buttonClick("#video", "icon-camera icon-camera-disabled");
  1706. setVideoMute(!APP.RTC.localVideo.isMuted());
  1707. };
  1708. /**
  1709. * Mutes / unmutes audio for the local participant.
  1710. */
  1711. UI.toggleAudio = function() {
  1712. UI.setAudioMuted(!APP.RTC.localAudio.isMuted());
  1713. };
  1714. /**
  1715. * Sets muted audio state for the local participant.
  1716. */
  1717. UI.setAudioMuted = function (mute) {
  1718. if(!APP.xmpp.setAudioMute(mute, function () {
  1719. VideoLayout.showLocalAudioIndicator(mute);
  1720. UIUtil.buttonClick("#mute", "icon-microphone icon-mic-disabled");
  1721. }))
  1722. {
  1723. // We still click the button.
  1724. UIUtil.buttonClick("#mute", "icon-microphone icon-mic-disabled");
  1725. return;
  1726. }
  1727. }
  1728. UI.addListener = function (type, listener) {
  1729. eventEmitter.on(type, listener);
  1730. }
  1731. UI.clickOnVideo = function (videoNumber) {
  1732. var remoteVideos = $(".videocontainer:not(#mixedstream)");
  1733. if (remoteVideos.length > videoNumber) {
  1734. remoteVideos[videoNumber].click();
  1735. }
  1736. }
  1737. //Used by torture
  1738. UI.showToolbar = function () {
  1739. return ToolbarToggler.showToolbar();
  1740. }
  1741. //Used by torture
  1742. UI.dockToolbar = function (isDock) {
  1743. return ToolbarToggler.dockToolbar(isDock);
  1744. }
  1745. module.exports = UI;
  1746. },{"../../service/RTC/RTCEvents":88,"../../service/RTC/StreamEventTypes":90,"../../service/connectionquality/CQEvents":93,"../../service/desktopsharing/DesktopSharingEventTypes":94,"../../service/xmpp/XMPPEvents":96,"./../settings/Settings":37,"./audio_levels/AudioLevels.js":9,"./authentication/Authentication":11,"./avatar/Avatar":12,"./etherpad/Etherpad.js":13,"./prezi/Prezi.js":14,"./side_pannels/SidePanelToggler":16,"./side_pannels/chat/Chat.js":17,"./side_pannels/contactlist/ContactList":21,"./side_pannels/settings/SettingsMenu":22,"./toolbars/BottomToolbar":23,"./toolbars/Toolbar":24,"./toolbars/ToolbarToggler":25,"./util/MessageHandler":27,"./util/NicknameHandler":28,"./util/UIUtil":29,"./videolayout/VideoLayout.js":31,"./welcome_page/RoomnameGenerator":32,"./welcome_page/WelcomePage":33,"events":97}],9:[function(require,module,exports){
  1747. var CanvasUtil = require("./CanvasUtils");
  1748. var ASDrawContext = $('#activeSpeakerAudioLevel')[0].getContext('2d');
  1749. function initActiveSpeakerAudioLevels() {
  1750. var ASRadius = interfaceConfig.ACTIVE_SPEAKER_AVATAR_SIZE / 2;
  1751. var ASCenter = (interfaceConfig.ACTIVE_SPEAKER_AVATAR_SIZE + ASRadius) / 2;
  1752. // Draw a circle.
  1753. ASDrawContext.arc(ASCenter, ASCenter, ASRadius, 0, 2 * Math.PI);
  1754. // Add a shadow around the circle
  1755. ASDrawContext.shadowColor = interfaceConfig.SHADOW_COLOR;
  1756. ASDrawContext.shadowOffsetX = 0;
  1757. ASDrawContext.shadowOffsetY = 0;
  1758. }
  1759. /**
  1760. * The audio Levels plugin.
  1761. */
  1762. var AudioLevels = (function(my) {
  1763. var audioLevelCanvasCache = {};
  1764. my.LOCAL_LEVEL = 'local';
  1765. my.init = function () {
  1766. initActiveSpeakerAudioLevels();
  1767. }
  1768. /**
  1769. * Updates the audio level canvas for the given peerJid. If the canvas
  1770. * didn't exist we create it.
  1771. */
  1772. my.updateAudioLevelCanvas = function (peerJid, VideoLayout) {
  1773. var resourceJid = null;
  1774. var videoSpanId = null;
  1775. if (!peerJid)
  1776. videoSpanId = 'localVideoContainer';
  1777. else {
  1778. resourceJid = Strophe.getResourceFromJid(peerJid);
  1779. videoSpanId = 'participant_' + resourceJid;
  1780. }
  1781. var videoSpan = document.getElementById(videoSpanId);
  1782. if (!videoSpan) {
  1783. if (resourceJid)
  1784. console.error("No video element for jid", resourceJid);
  1785. else
  1786. console.error("No video element for local video.");
  1787. return;
  1788. }
  1789. var audioLevelCanvas = $('#' + videoSpanId + '>canvas');
  1790. var videoSpaceWidth = $('#remoteVideos').width();
  1791. var thumbnailSize = VideoLayout.calculateThumbnailSize(videoSpaceWidth);
  1792. var thumbnailWidth = thumbnailSize[0];
  1793. var thumbnailHeight = thumbnailSize[1];
  1794. if (!audioLevelCanvas || audioLevelCanvas.length === 0) {
  1795. audioLevelCanvas = document.createElement('canvas');
  1796. audioLevelCanvas.className = "audiolevel";
  1797. audioLevelCanvas.style.bottom = "-" + interfaceConfig.CANVAS_EXTRA/2 + "px";
  1798. audioLevelCanvas.style.left = "-" + interfaceConfig.CANVAS_EXTRA/2 + "px";
  1799. resizeAudioLevelCanvas( audioLevelCanvas,
  1800. thumbnailWidth,
  1801. thumbnailHeight);
  1802. videoSpan.appendChild(audioLevelCanvas);
  1803. } else {
  1804. audioLevelCanvas = audioLevelCanvas.get(0);
  1805. resizeAudioLevelCanvas( audioLevelCanvas,
  1806. thumbnailWidth,
  1807. thumbnailHeight);
  1808. }
  1809. };
  1810. /**
  1811. * Updates the audio level UI for the given resourceJid.
  1812. *
  1813. * @param resourceJid the resource jid indicating the video element for
  1814. * which we draw the audio level
  1815. * @param audioLevel the newAudio level to render
  1816. */
  1817. my.updateAudioLevel = function (resourceJid, audioLevel, largeVideoResourceJid) {
  1818. drawAudioLevelCanvas(resourceJid, audioLevel);
  1819. var videoSpanId = getVideoSpanId(resourceJid);
  1820. var audioLevelCanvas = $('#' + videoSpanId + '>canvas').get(0);
  1821. if (!audioLevelCanvas)
  1822. return;
  1823. var drawContext = audioLevelCanvas.getContext('2d');
  1824. var canvasCache = audioLevelCanvasCache[resourceJid];
  1825. drawContext.clearRect (0, 0,
  1826. audioLevelCanvas.width, audioLevelCanvas.height);
  1827. drawContext.drawImage(canvasCache, 0, 0);
  1828. if(resourceJid === AudioLevels.LOCAL_LEVEL) {
  1829. if(!APP.xmpp.myJid()) {
  1830. return;
  1831. }
  1832. resourceJid = APP.xmpp.myResource();
  1833. }
  1834. if(resourceJid === largeVideoResourceJid) {
  1835. window.requestAnimationFrame(function () {
  1836. AudioLevels.updateActiveSpeakerAudioLevel(audioLevel);
  1837. });
  1838. }
  1839. };
  1840. my.updateActiveSpeakerAudioLevel = function(audioLevel) {
  1841. if($("#activeSpeaker").css("visibility") == "hidden")
  1842. return;
  1843. ASDrawContext.clearRect(0, 0, 300, 300);
  1844. if(audioLevel == 0)
  1845. return;
  1846. ASDrawContext.shadowBlur = getShadowLevel(audioLevel);
  1847. // Fill the shape.
  1848. ASDrawContext.fill();
  1849. };
  1850. /**
  1851. * Resizes the given audio level canvas to match the given thumbnail size.
  1852. */
  1853. function resizeAudioLevelCanvas(audioLevelCanvas,
  1854. thumbnailWidth,
  1855. thumbnailHeight) {
  1856. audioLevelCanvas.width = thumbnailWidth + interfaceConfig.CANVAS_EXTRA;
  1857. audioLevelCanvas.height = thumbnailHeight + interfaceConfig.CANVAS_EXTRA;
  1858. }
  1859. /**
  1860. * Draws the audio level canvas into the cached canvas object.
  1861. *
  1862. * @param resourceJid the resource jid indicating the video element for
  1863. * which we draw the audio level
  1864. * @param audioLevel the newAudio level to render
  1865. */
  1866. function drawAudioLevelCanvas(resourceJid, audioLevel) {
  1867. if (!audioLevelCanvasCache[resourceJid]) {
  1868. var videoSpanId = getVideoSpanId(resourceJid);
  1869. var audioLevelCanvasOrig = $('#' + videoSpanId + '>canvas').get(0);
  1870. /*
  1871. * FIXME Testing has shown that audioLevelCanvasOrig may not exist.
  1872. * In such a case, the method CanvasUtil.cloneCanvas may throw an
  1873. * error. Since audio levels are frequently updated, the errors have
  1874. * been observed to pile into the console, strain the CPU.
  1875. */
  1876. if (audioLevelCanvasOrig)
  1877. {
  1878. audioLevelCanvasCache[resourceJid]
  1879. = CanvasUtil.cloneCanvas(audioLevelCanvasOrig);
  1880. }
  1881. }
  1882. var canvas = audioLevelCanvasCache[resourceJid];
  1883. if (!canvas)
  1884. return;
  1885. var drawContext = canvas.getContext('2d');
  1886. drawContext.clearRect(0, 0, canvas.width, canvas.height);
  1887. var shadowLevel = getShadowLevel(audioLevel);
  1888. if (shadowLevel > 0)
  1889. // drawContext, x, y, w, h, r, shadowColor, shadowLevel
  1890. CanvasUtil.drawRoundRectGlow( drawContext,
  1891. interfaceConfig.CANVAS_EXTRA/2, interfaceConfig.CANVAS_EXTRA/2,
  1892. canvas.width - interfaceConfig.CANVAS_EXTRA,
  1893. canvas.height - interfaceConfig.CANVAS_EXTRA,
  1894. interfaceConfig.CANVAS_RADIUS,
  1895. interfaceConfig.SHADOW_COLOR,
  1896. shadowLevel);
  1897. }
  1898. /**
  1899. * Returns the shadow/glow level for the given audio level.
  1900. *
  1901. * @param audioLevel the audio level from which we determine the shadow
  1902. * level
  1903. */
  1904. function getShadowLevel (audioLevel) {
  1905. var shadowLevel = 0;
  1906. if (audioLevel <= 0.3) {
  1907. shadowLevel = Math.round(interfaceConfig.CANVAS_EXTRA/2*(audioLevel/0.3));
  1908. }
  1909. else if (audioLevel <= 0.6) {
  1910. shadowLevel = Math.round(interfaceConfig.CANVAS_EXTRA/2*((audioLevel - 0.3) / 0.3));
  1911. }
  1912. else {
  1913. shadowLevel = Math.round(interfaceConfig.CANVAS_EXTRA/2*((audioLevel - 0.6) / 0.4));
  1914. }
  1915. return shadowLevel;
  1916. }
  1917. /**
  1918. * Returns the video span id corresponding to the given resourceJid or local
  1919. * user.
  1920. */
  1921. function getVideoSpanId(resourceJid) {
  1922. var videoSpanId = null;
  1923. if (resourceJid === AudioLevels.LOCAL_LEVEL
  1924. || (APP.xmpp.myResource() && resourceJid
  1925. === APP.xmpp.myResource()))
  1926. videoSpanId = 'localVideoContainer';
  1927. else
  1928. videoSpanId = 'participant_' + resourceJid;
  1929. return videoSpanId;
  1930. }
  1931. /**
  1932. * Indicates that the remote video has been resized.
  1933. */
  1934. $(document).bind('remotevideo.resized', function (event, width, height) {
  1935. var resized = false;
  1936. $('#remoteVideos>span>canvas').each(function() {
  1937. var canvas = $(this).get(0);
  1938. if (canvas.width !== width + interfaceConfig.CANVAS_EXTRA) {
  1939. canvas.width = width + interfaceConfig.CANVAS_EXTRA;
  1940. resized = true;
  1941. }
  1942. if (canvas.heigh !== height + interfaceConfig.CANVAS_EXTRA) {
  1943. canvas.height = height + interfaceConfig.CANVAS_EXTRA;
  1944. resized = true;
  1945. }
  1946. });
  1947. if (resized)
  1948. Object.keys(audioLevelCanvasCache).forEach(function (resourceJid) {
  1949. audioLevelCanvasCache[resourceJid].width
  1950. = width + interfaceConfig.CANVAS_EXTRA;
  1951. audioLevelCanvasCache[resourceJid].height
  1952. = height + interfaceConfig.CANVAS_EXTRA;
  1953. });
  1954. });
  1955. return my;
  1956. })(AudioLevels || {});
  1957. module.exports = AudioLevels;
  1958. },{"./CanvasUtils":10}],10:[function(require,module,exports){
  1959. /**
  1960. * Utility class for drawing canvas shapes.
  1961. */
  1962. var CanvasUtil = (function(my) {
  1963. /**
  1964. * Draws a round rectangle with a glow. The glowWidth indicates the depth
  1965. * of the glow.
  1966. *
  1967. * @param drawContext the context of the canvas to draw to
  1968. * @param x the x coordinate of the round rectangle
  1969. * @param y the y coordinate of the round rectangle
  1970. * @param w the width of the round rectangle
  1971. * @param h the height of the round rectangle
  1972. * @param glowColor the color of the glow
  1973. * @param glowWidth the width of the glow
  1974. */
  1975. my.drawRoundRectGlow
  1976. = function(drawContext, x, y, w, h, r, glowColor, glowWidth) {
  1977. // Save the previous state of the context.
  1978. drawContext.save();
  1979. if (w < 2 * r) r = w / 2;
  1980. if (h < 2 * r) r = h / 2;
  1981. // Draw a round rectangle.
  1982. drawContext.beginPath();
  1983. drawContext.moveTo(x+r, y);
  1984. drawContext.arcTo(x+w, y, x+w, y+h, r);
  1985. drawContext.arcTo(x+w, y+h, x, y+h, r);
  1986. drawContext.arcTo(x, y+h, x, y, r);
  1987. drawContext.arcTo(x, y, x+w, y, r);
  1988. drawContext.closePath();
  1989. // Add a shadow around the rectangle
  1990. drawContext.shadowColor = glowColor;
  1991. drawContext.shadowBlur = glowWidth;
  1992. drawContext.shadowOffsetX = 0;
  1993. drawContext.shadowOffsetY = 0;
  1994. // Fill the shape.
  1995. drawContext.fill();
  1996. drawContext.save();
  1997. drawContext.restore();
  1998. // 1) Uncomment this line to use Composite Operation, which is doing the
  1999. // same as the clip function below and is also antialiasing the round
  2000. // border, but is said to be less fast performance wise.
  2001. // drawContext.globalCompositeOperation='destination-out';
  2002. drawContext.beginPath();
  2003. drawContext.moveTo(x+r, y);
  2004. drawContext.arcTo(x+w, y, x+w, y+h, r);
  2005. drawContext.arcTo(x+w, y+h, x, y+h, r);
  2006. drawContext.arcTo(x, y+h, x, y, r);
  2007. drawContext.arcTo(x, y, x+w, y, r);
  2008. drawContext.closePath();
  2009. // 2) Uncomment this line to use Composite Operation, which is doing the
  2010. // same as the clip function below and is also antialiasing the round
  2011. // border, but is said to be less fast performance wise.
  2012. // drawContext.fill();
  2013. // Comment these two lines if choosing to do the same with composite
  2014. // operation above 1 and 2.
  2015. drawContext.clip();
  2016. drawContext.clearRect(0, 0, 277, 200);
  2017. // Restore the previous context state.
  2018. drawContext.restore();
  2019. };
  2020. /**
  2021. * Clones the given canvas.
  2022. *
  2023. * @return the new cloned canvas.
  2024. */
  2025. my.cloneCanvas = function (oldCanvas) {
  2026. /*
  2027. * FIXME Testing has shown that oldCanvas may not exist. In such a case,
  2028. * the method CanvasUtil.cloneCanvas may throw an error. Since audio
  2029. * levels are frequently updated, the errors have been observed to pile
  2030. * into the console, strain the CPU.
  2031. */
  2032. if (!oldCanvas)
  2033. return oldCanvas;
  2034. //create a new canvas
  2035. var newCanvas = document.createElement('canvas');
  2036. var context = newCanvas.getContext('2d');
  2037. //set dimensions
  2038. newCanvas.width = oldCanvas.width;
  2039. newCanvas.height = oldCanvas.height;
  2040. //apply the old canvas to the new one
  2041. context.drawImage(oldCanvas, 0, 0);
  2042. //return the new canvas
  2043. return newCanvas;
  2044. };
  2045. return my;
  2046. })(CanvasUtil || {});
  2047. module.exports = CanvasUtil;
  2048. },{}],11:[function(require,module,exports){
  2049. /* Initial "authentication required" dialog */
  2050. var authDialog = null;
  2051. /* Loop retry ID that wits for other user to create the room */
  2052. var authRetryId = null;
  2053. var authenticationWindow = null;
  2054. var Authentication = {
  2055. openAuthenticationDialog: function (roomName, intervalCallback, callback) {
  2056. // This is the loop that will wait for the room to be created by
  2057. // someone else. 'auth_required.moderator' will bring us back here.
  2058. authRetryId = window.setTimeout(intervalCallback , 5000);
  2059. // Show prompt only if it's not open
  2060. if (authDialog !== null) {
  2061. return;
  2062. }
  2063. // extract room name from 'room@muc.server.net'
  2064. var room = roomName.substr(0, roomName.indexOf('@'));
  2065. var title = APP.translation.generateTranslatonHTML("dialog.Stop");
  2066. var msg = APP.translation.generateTranslatonHTML("dialog.AuthMsg",
  2067. {room: room});
  2068. var button = APP.translation.generateTranslatonHTML(
  2069. "dialog.Authenticate");
  2070. var buttons = {};
  2071. buttons.authenticate = {title: button, value: "authNow"};
  2072. authDialog = APP.UI.messageHandler.openDialog(
  2073. title,
  2074. msg,
  2075. true,
  2076. buttons,
  2077. function (onSubmitEvent, submitValue) {
  2078. // Do not close the dialog yet
  2079. onSubmitEvent.preventDefault();
  2080. // Open login popup
  2081. if (submitValue === 'authNow') {
  2082. callback();
  2083. }
  2084. }
  2085. );
  2086. },
  2087. closeAuthenticationWindow:function () {
  2088. if (authenticationWindow) {
  2089. authenticationWindow.close();
  2090. authenticationWindow = null;
  2091. }
  2092. },
  2093. focusAuthenticationWindow: function () {
  2094. // If auth window exists just bring it to the front
  2095. if (authenticationWindow) {
  2096. authenticationWindow.focus();
  2097. return;
  2098. }
  2099. },
  2100. closeAuthenticationDialog: function () {
  2101. // Close authentication dialog if opened
  2102. if (authDialog) {
  2103. APP.UI.messageHandler.closeDialog();
  2104. authDialog = null;
  2105. }
  2106. },
  2107. createAuthenticationWindow: function (callback, url) {
  2108. authenticationWindow = APP.UI.messageHandler.openCenteredPopup(
  2109. url, 910, 660,
  2110. // On closed
  2111. function () {
  2112. // Close authentication dialog if opened
  2113. if (authDialog) {
  2114. messageHandler.closeDialog();
  2115. authDialog = null;
  2116. }
  2117. callback();
  2118. authenticationWindow = null;
  2119. });
  2120. return authenticationWindow;
  2121. },
  2122. stopInterval: function () {
  2123. // Clear retry interval, so that we don't call 'doJoinAfterFocus' twice
  2124. if (authRetryId) {
  2125. window.clearTimeout(authRetryId);
  2126. authRetryId = null;
  2127. }
  2128. }
  2129. };
  2130. module.exports = Authentication;
  2131. },{}],12:[function(require,module,exports){
  2132. var Settings = require("../../settings/Settings");
  2133. var MediaStreamType = require("../../../service/RTC/MediaStreamTypes");
  2134. var users = {};
  2135. var activeSpeakerJid;
  2136. function setVisibility(selector, show) {
  2137. if (selector && selector.length > 0) {
  2138. selector.css("visibility", show ? "visible" : "hidden");
  2139. }
  2140. }
  2141. function isUserMuted(jid) {
  2142. // XXX(gp) we may want to rename this method to something like
  2143. // isUserStreaming, for example.
  2144. if (jid && jid != APP.xmpp.myJid()) {
  2145. var resource = Strophe.getResourceFromJid(jid);
  2146. if (!require("../videolayout/VideoLayout").isInLastN(resource)) {
  2147. return true;
  2148. }
  2149. }
  2150. if (!APP.RTC.remoteStreams[jid] || !APP.RTC.remoteStreams[jid][MediaStreamType.VIDEO_TYPE]) {
  2151. return null;
  2152. }
  2153. return APP.RTC.remoteStreams[jid][MediaStreamType.VIDEO_TYPE].muted;
  2154. }
  2155. function getGravatarUrl(id, size) {
  2156. if(id === APP.xmpp.myJid() || !id) {
  2157. id = Settings.getSettings().uid;
  2158. }
  2159. return 'https://www.gravatar.com/avatar/' +
  2160. MD5.hexdigest(id.trim().toLowerCase()) +
  2161. "?d=wavatar&size=" + (size || "30");
  2162. }
  2163. var Avatar = {
  2164. /**
  2165. * Sets the user's avatar in the settings menu(if local user), contact list
  2166. * and thumbnail
  2167. * @param jid jid of the user
  2168. * @param id email or userID to be used as a hash
  2169. */
  2170. setUserAvatar: function (jid, id) {
  2171. if (id) {
  2172. if (users[jid] === id) {
  2173. return;
  2174. }
  2175. users[jid] = id;
  2176. }
  2177. var thumbUrl = getGravatarUrl(users[jid] || jid, 100);
  2178. var contactListUrl = getGravatarUrl(users[jid] || jid);
  2179. var resourceJid = Strophe.getResourceFromJid(jid);
  2180. var thumbnail = $('#participant_' + resourceJid);
  2181. var avatar = $('#avatar_' + resourceJid);
  2182. // set the avatar in the settings menu if it is local user and get the
  2183. // local video container
  2184. if (jid === APP.xmpp.myJid()) {
  2185. $('#avatar').get(0).src = thumbUrl;
  2186. thumbnail = $('#localVideoContainer');
  2187. }
  2188. // set the avatar in the contact list
  2189. var contact = $('#' + resourceJid + '>img');
  2190. if (contact && contact.length > 0) {
  2191. contact.get(0).src = contactListUrl;
  2192. }
  2193. // set the avatar in the thumbnail
  2194. if (avatar && avatar.length > 0) {
  2195. avatar[0].src = thumbUrl;
  2196. } else {
  2197. if (thumbnail && thumbnail.length > 0) {
  2198. avatar = document.createElement('img');
  2199. avatar.id = 'avatar_' + resourceJid;
  2200. avatar.className = 'userAvatar';
  2201. avatar.src = thumbUrl;
  2202. thumbnail.append(avatar);
  2203. }
  2204. }
  2205. //if the user is the current active speaker - update the active speaker
  2206. // avatar
  2207. if (jid === activeSpeakerJid) {
  2208. this.updateActiveSpeakerAvatarSrc(jid);
  2209. }
  2210. },
  2211. /**
  2212. * Hides or shows the user's avatar
  2213. * @param jid jid of the user
  2214. * @param show whether we should show the avatar or not
  2215. * video because there is no dominant speaker and no focused speaker
  2216. */
  2217. showUserAvatar: function (jid, show) {
  2218. if (users[jid]) {
  2219. var resourceJid = Strophe.getResourceFromJid(jid);
  2220. var video = $('#participant_' + resourceJid + '>video');
  2221. var avatar = $('#avatar_' + resourceJid);
  2222. if (jid === APP.xmpp.myJid()) {
  2223. video = $('#localVideoWrapper>video');
  2224. }
  2225. if (show === undefined || show === null) {
  2226. show = isUserMuted(jid);
  2227. }
  2228. //if the user is the currently focused, the dominant speaker or if
  2229. //there is no focused and no dominant speaker and the large video is
  2230. //currently shown
  2231. if (activeSpeakerJid === jid && require("../videolayout/VideoLayout").isLargeVideoOnTop()) {
  2232. setVisibility($("#largeVideo"), !show);
  2233. setVisibility($('#activeSpeaker'), show);
  2234. setVisibility(avatar, false);
  2235. setVisibility(video, false);
  2236. } else {
  2237. if (video && video.length > 0) {
  2238. setVisibility(video, !show);
  2239. setVisibility(avatar, show);
  2240. }
  2241. }
  2242. }
  2243. },
  2244. /**
  2245. * Updates the src of the active speaker avatar
  2246. * @param jid of the current active speaker
  2247. */
  2248. updateActiveSpeakerAvatarSrc: function (jid) {
  2249. if (!jid) {
  2250. jid = APP.xmpp.findJidFromResource(
  2251. require("../videolayout/VideoLayout").getLargeVideoState().userResourceJid);
  2252. }
  2253. var avatar = $("#activeSpeakerAvatar")[0];
  2254. var url = getGravatarUrl(users[jid],
  2255. interfaceConfig.ACTIVE_SPEAKER_AVATAR_SIZE);
  2256. if (jid === activeSpeakerJid && avatar.src === url) {
  2257. return;
  2258. }
  2259. activeSpeakerJid = jid;
  2260. var isMuted = isUserMuted(jid);
  2261. if (jid && isMuted !== null) {
  2262. avatar.src = url;
  2263. setVisibility($("#largeVideo"), !isMuted);
  2264. Avatar.showUserAvatar(jid, isMuted);
  2265. }
  2266. }
  2267. };
  2268. module.exports = Avatar;
  2269. },{"../../../service/RTC/MediaStreamTypes":86,"../../settings/Settings":37,"../videolayout/VideoLayout":31}],13:[function(require,module,exports){
  2270. /* global $, config,
  2271. setLargeVideoVisible, Util */
  2272. var VideoLayout = require("../videolayout/VideoLayout");
  2273. var Prezi = require("../prezi/Prezi");
  2274. var UIUtil = require("../util/UIUtil");
  2275. var etherpadName = null;
  2276. var etherpadIFrame = null;
  2277. var domain = null;
  2278. var options = "?showControls=true&showChat=false&showLineNumbers=true&useMonospaceFont=false";
  2279. /**
  2280. * Resizes the etherpad.
  2281. */
  2282. function resize() {
  2283. if ($('#etherpad>iframe').length) {
  2284. var remoteVideos = $('#remoteVideos');
  2285. var availableHeight
  2286. = window.innerHeight - remoteVideos.outerHeight();
  2287. var availableWidth = UIUtil.getAvailableVideoWidth();
  2288. $('#etherpad>iframe').width(availableWidth);
  2289. $('#etherpad>iframe').height(availableHeight);
  2290. }
  2291. }
  2292. /**
  2293. * Shares the Etherpad name with other participants.
  2294. */
  2295. function shareEtherpad() {
  2296. APP.xmpp.addToPresence("etherpad", etherpadName);
  2297. }
  2298. /**
  2299. * Creates the Etherpad button and adds it to the toolbar.
  2300. */
  2301. function enableEtherpadButton() {
  2302. if (!$('#etherpadButton').is(":visible"))
  2303. $('#etherpadButton').css({display: 'inline-block'});
  2304. }
  2305. /**
  2306. * Creates the IFrame for the etherpad.
  2307. */
  2308. function createIFrame() {
  2309. etherpadIFrame = document.createElement('iframe');
  2310. etherpadIFrame.src = domain + etherpadName + options;
  2311. etherpadIFrame.frameBorder = 0;
  2312. etherpadIFrame.scrolling = "no";
  2313. etherpadIFrame.width = $('#largeVideoContainer').width() || 640;
  2314. etherpadIFrame.height = $('#largeVideoContainer').height() || 480;
  2315. etherpadIFrame.setAttribute('style', 'visibility: hidden;');
  2316. document.getElementById('etherpad').appendChild(etherpadIFrame);
  2317. etherpadIFrame.onload = function() {
  2318. document.domain = document.domain;
  2319. bubbleIframeMouseMove(etherpadIFrame);
  2320. setTimeout(function() {
  2321. // the iframes inside of the etherpad are
  2322. // not yet loaded when the etherpad iframe is loaded
  2323. var outer = etherpadIFrame.
  2324. contentDocument.getElementsByName("ace_outer")[0];
  2325. bubbleIframeMouseMove(outer);
  2326. var inner = outer.
  2327. contentDocument.getElementsByName("ace_inner")[0];
  2328. bubbleIframeMouseMove(inner);
  2329. }, 2000);
  2330. };
  2331. }
  2332. function bubbleIframeMouseMove(iframe){
  2333. var existingOnMouseMove = iframe.contentWindow.onmousemove;
  2334. iframe.contentWindow.onmousemove = function(e){
  2335. if(existingOnMouseMove) existingOnMouseMove(e);
  2336. var evt = document.createEvent("MouseEvents");
  2337. var boundingClientRect = iframe.getBoundingClientRect();
  2338. evt.initMouseEvent(
  2339. "mousemove",
  2340. true, // bubbles
  2341. false, // not cancelable
  2342. window,
  2343. e.detail,
  2344. e.screenX,
  2345. e.screenY,
  2346. e.clientX + boundingClientRect.left,
  2347. e.clientY + boundingClientRect.top,
  2348. e.ctrlKey,
  2349. e.altKey,
  2350. e.shiftKey,
  2351. e.metaKey,
  2352. e.button,
  2353. null // no related element
  2354. );
  2355. iframe.dispatchEvent(evt);
  2356. };
  2357. }
  2358. /**
  2359. * On video selected event.
  2360. */
  2361. $(document).bind('video.selected', function (event, isPresentation) {
  2362. if (config.etherpad_base && etherpadIFrame && etherpadIFrame.style.visibility !== 'hidden')
  2363. Etherpad.toggleEtherpad(isPresentation);
  2364. });
  2365. var Etherpad = {
  2366. /**
  2367. * Initializes the etherpad.
  2368. */
  2369. init: function (name) {
  2370. if (config.etherpad_base && !etherpadName) {
  2371. domain = config.etherpad_base;
  2372. if (!name) {
  2373. // In case we're the focus we generate the name.
  2374. etherpadName = Math.random().toString(36).substring(7) +
  2375. '_' + (new Date().getTime()).toString();
  2376. shareEtherpad();
  2377. }
  2378. else
  2379. etherpadName = name;
  2380. enableEtherpadButton();
  2381. /**
  2382. * Resizes the etherpad, when the window is resized.
  2383. */
  2384. $(window).resize(function () {
  2385. resize();
  2386. });
  2387. }
  2388. },
  2389. /**
  2390. * Opens/hides the Etherpad.
  2391. */
  2392. toggleEtherpad: function (isPresentation) {
  2393. if (!etherpadIFrame)
  2394. createIFrame();
  2395. var largeVideo = null;
  2396. if (Prezi.isPresentationVisible())
  2397. largeVideo = $('#presentation>iframe');
  2398. else
  2399. largeVideo = $('#largeVideo');
  2400. if ($('#etherpad>iframe').css('visibility') === 'hidden') {
  2401. $('#activeSpeaker').css('visibility', 'hidden');
  2402. largeVideo.fadeOut(300, function () {
  2403. if (Prezi.isPresentationVisible()) {
  2404. largeVideo.css({opacity: '0'});
  2405. } else {
  2406. VideoLayout.setLargeVideoVisible(false);
  2407. }
  2408. });
  2409. $('#etherpad>iframe').fadeIn(300, function () {
  2410. document.body.style.background = '#eeeeee';
  2411. $('#etherpad>iframe').css({visibility: 'visible'});
  2412. $('#etherpad').css({zIndex: 2});
  2413. });
  2414. }
  2415. else if ($('#etherpad>iframe')) {
  2416. $('#etherpad>iframe').fadeOut(300, function () {
  2417. $('#etherpad>iframe').css({visibility: 'hidden'});
  2418. $('#etherpad').css({zIndex: 0});
  2419. document.body.style.background = 'black';
  2420. });
  2421. if (!isPresentation) {
  2422. $('#largeVideo').fadeIn(300, function () {
  2423. VideoLayout.setLargeVideoVisible(true);
  2424. });
  2425. }
  2426. }
  2427. resize();
  2428. },
  2429. isVisible: function() {
  2430. var etherpadIframe = $('#etherpad>iframe');
  2431. return etherpadIframe && etherpadIframe.is(':visible');
  2432. }
  2433. };
  2434. module.exports = Etherpad;
  2435. },{"../prezi/Prezi":14,"../util/UIUtil":29,"../videolayout/VideoLayout":31}],14:[function(require,module,exports){
  2436. var ToolbarToggler = require("../toolbars/ToolbarToggler");
  2437. var UIUtil = require("../util/UIUtil");
  2438. var VideoLayout = require("../videolayout/VideoLayout");
  2439. var messageHandler = require("../util/MessageHandler");
  2440. var PreziPlayer = require("./PreziPlayer");
  2441. var preziPlayer = null;
  2442. var Prezi = {
  2443. /**
  2444. * Reloads the current presentation.
  2445. */
  2446. reloadPresentation: function() {
  2447. var iframe = document.getElementById(preziPlayer.options.preziId);
  2448. iframe.src = iframe.src;
  2449. },
  2450. /**
  2451. * Returns <tt>true</tt> if the presentation is visible, <tt>false</tt> -
  2452. * otherwise.
  2453. */
  2454. isPresentationVisible: function () {
  2455. return ($('#presentation>iframe') != null
  2456. && $('#presentation>iframe').css('opacity') == 1);
  2457. },
  2458. /**
  2459. * Opens the Prezi dialog, from which the user could choose a presentation
  2460. * to load.
  2461. */
  2462. openPreziDialog: function() {
  2463. var myprezi = APP.xmpp.getPrezi();
  2464. if (myprezi) {
  2465. messageHandler.openTwoButtonDialog("dialog.removePreziTitle",
  2466. null,
  2467. "dialog.removePreziMsg",
  2468. null,
  2469. false,
  2470. "dialog.Remove",
  2471. function(e,v,m,f) {
  2472. if(v) {
  2473. APP.xmpp.removePreziFromPresence();
  2474. }
  2475. }
  2476. );
  2477. }
  2478. else if (preziPlayer != null) {
  2479. messageHandler.openTwoButtonDialog("dialog.sharePreziTitle",
  2480. null, "dialog.sharePreziMsg",
  2481. null,
  2482. false,
  2483. "dialog.Ok",
  2484. function(e,v,m,f) {
  2485. $.prompt.close();
  2486. }
  2487. );
  2488. }
  2489. else {
  2490. var html = APP.translation.generateTranslatonHTML(
  2491. "dialog.sharePreziTitle");
  2492. var cancelButton = APP.translation.generateTranslatonHTML(
  2493. "dialog.Cancel");
  2494. var shareButton = APP.translation.generateTranslatonHTML(
  2495. "dialog.Share");
  2496. var backButton = APP.translation.generateTranslatonHTML(
  2497. "dialog.Back");
  2498. var buttons = {};
  2499. var buttons1 = {};
  2500. buttons1.button1 = buttons.button1 = {title: cancelButton, value: false};
  2501. buttons.button2 = {title: shareButton, value: true};
  2502. buttons1.button2 = {title: backButton, value: true};
  2503. var linkError = APP.translation.generateTranslatonHTML(
  2504. "dialog.preziLinkError");
  2505. var defaultUrl = APP.translation.translateString("defaultPreziLink",
  2506. {url: "http://prezi.com/wz7vhjycl7e6/my-prezi"});
  2507. var openPreziState = {
  2508. state0: {
  2509. html: '<h2>' + html + '</h2>' +
  2510. '<input id="preziUrl" type="text" ' +
  2511. 'data-i18n="[placeholder]defaultPreziLink" data-i18n-options=\'' +
  2512. JSON.stringify({"url": "http://prezi.com/wz7vhjycl7e6/my-prezi"}) +
  2513. '\' placeholder="' + defaultUrl + '" autofocus>',
  2514. persistent: false,
  2515. buttons: buttons,
  2516. defaultButton: 1,
  2517. submit: function(e,v,m,f){
  2518. e.preventDefault();
  2519. if(v)
  2520. {
  2521. var preziUrl = document.getElementById('preziUrl');
  2522. if (preziUrl.value)
  2523. {
  2524. var urlValue
  2525. = encodeURI(UIUtil.escapeHtml(preziUrl.value));
  2526. if (urlValue.indexOf('http://prezi.com/') != 0
  2527. && urlValue.indexOf('https://prezi.com/') != 0)
  2528. {
  2529. $.prompt.goToState('state1');
  2530. return false;
  2531. }
  2532. else {
  2533. var presIdTmp = urlValue.substring(
  2534. urlValue.indexOf("prezi.com/") + 10);
  2535. if (!isAlphanumeric(presIdTmp)
  2536. || presIdTmp.indexOf('/') < 2) {
  2537. $.prompt.goToState('state1');
  2538. return false;
  2539. }
  2540. else {
  2541. APP.xmpp.addToPresence("prezi", urlValue);
  2542. $.prompt.close();
  2543. }
  2544. }
  2545. }
  2546. }
  2547. else
  2548. $.prompt.close();
  2549. }
  2550. },
  2551. state1: {
  2552. html: '<h2>' + html + '</h2>' +
  2553. linkError,
  2554. persistent: false,
  2555. buttons: buttons1,
  2556. defaultButton: 1,
  2557. submit:function(e,v,m,f) {
  2558. e.preventDefault();
  2559. if(v==0)
  2560. $.prompt.close();
  2561. else
  2562. $.prompt.goToState('state0');
  2563. }
  2564. }
  2565. };
  2566. var focusPreziUrl = function(e) {
  2567. document.getElementById('preziUrl').focus();
  2568. };
  2569. messageHandler.openDialogWithStates(openPreziState, focusPreziUrl, focusPreziUrl);
  2570. }
  2571. }
  2572. };
  2573. /**
  2574. * A new presentation has been added.
  2575. *
  2576. * @param event the event indicating the add of a presentation
  2577. * @param jid the jid from which the presentation was added
  2578. * @param presUrl url of the presentation
  2579. * @param currentSlide the current slide to which we should move
  2580. */
  2581. function presentationAdded(event, jid, presUrl, currentSlide) {
  2582. console.log("presentation added", presUrl);
  2583. var presId = getPresentationId(presUrl);
  2584. var elementId = 'participant_'
  2585. + Strophe.getResourceFromJid(jid)
  2586. + '_' + presId;
  2587. // We explicitly don't specify the peer jid here, because we don't want
  2588. // this video to be dealt with as a peer related one (for example we
  2589. // don't want to show a mute/kick menu for this one, etc.).
  2590. VideoLayout.addRemoteVideoContainer(null, elementId);
  2591. VideoLayout.resizeThumbnails();
  2592. var controlsEnabled = false;
  2593. if (jid === APP.xmpp.myJid())
  2594. controlsEnabled = true;
  2595. setPresentationVisible(true);
  2596. $('#largeVideoContainer').hover(
  2597. function (event) {
  2598. if (Prezi.isPresentationVisible()) {
  2599. var reloadButtonRight = window.innerWidth
  2600. - $('#presentation>iframe').offset().left
  2601. - $('#presentation>iframe').width();
  2602. $('#reloadPresentation').css({ right: reloadButtonRight,
  2603. display:'inline-block'});
  2604. }
  2605. },
  2606. function (event) {
  2607. if (!Prezi.isPresentationVisible())
  2608. $('#reloadPresentation').css({display:'none'});
  2609. else {
  2610. var e = event.toElement || event.relatedTarget;
  2611. if (e && e.id != 'reloadPresentation' && e.id != 'header')
  2612. $('#reloadPresentation').css({display:'none'});
  2613. }
  2614. });
  2615. preziPlayer = new PreziPlayer(
  2616. 'presentation',
  2617. {preziId: presId,
  2618. width: getPresentationWidth(),
  2619. height: getPresentationHeihgt(),
  2620. controls: controlsEnabled,
  2621. debug: true
  2622. });
  2623. $('#presentation>iframe').attr('id', preziPlayer.options.preziId);
  2624. preziPlayer.on(PreziPlayer.EVENT_STATUS, function(event) {
  2625. console.log("prezi status", event.value);
  2626. if (event.value == PreziPlayer.STATUS_CONTENT_READY) {
  2627. if (jid != APP.xmpp.myJid())
  2628. preziPlayer.flyToStep(currentSlide);
  2629. }
  2630. });
  2631. preziPlayer.on(PreziPlayer.EVENT_CURRENT_STEP, function(event) {
  2632. console.log("event value", event.value);
  2633. APP.xmpp.addToPresence("preziSlide", event.value);
  2634. });
  2635. $("#" + elementId).css( 'background-image',
  2636. 'url(../images/avatarprezi.png)');
  2637. $("#" + elementId).click(
  2638. function () {
  2639. setPresentationVisible(true);
  2640. }
  2641. );
  2642. };
  2643. /**
  2644. * A presentation has been removed.
  2645. *
  2646. * @param event the event indicating the remove of a presentation
  2647. * @param jid the jid for which the presentation was removed
  2648. * @param the url of the presentation
  2649. */
  2650. function presentationRemoved(event, jid, presUrl) {
  2651. console.log('presentation removed', presUrl);
  2652. var presId = getPresentationId(presUrl);
  2653. setPresentationVisible(false);
  2654. $('#participant_'
  2655. + Strophe.getResourceFromJid(jid)
  2656. + '_' + presId).remove();
  2657. $('#presentation>iframe').remove();
  2658. if (preziPlayer != null) {
  2659. preziPlayer.destroy();
  2660. preziPlayer = null;
  2661. }
  2662. };
  2663. /**
  2664. * Indicates if the given string is an alphanumeric string.
  2665. * Note that some special characters are also allowed (-, _ , /, &, ?, =, ;) for the
  2666. * purpose of checking URIs.
  2667. */
  2668. function isAlphanumeric(unsafeText) {
  2669. var regex = /^[a-z0-9-_\/&\?=;]+$/i;
  2670. return regex.test(unsafeText);
  2671. }
  2672. /**
  2673. * Returns the presentation id from the given url.
  2674. */
  2675. function getPresentationId (presUrl) {
  2676. var presIdTmp = presUrl.substring(presUrl.indexOf("prezi.com/") + 10);
  2677. return presIdTmp.substring(0, presIdTmp.indexOf('/'));
  2678. }
  2679. /**
  2680. * Returns the presentation width.
  2681. */
  2682. function getPresentationWidth() {
  2683. var availableWidth = UIUtil.getAvailableVideoWidth();
  2684. var availableHeight = getPresentationHeihgt();
  2685. var aspectRatio = 16.0 / 9.0;
  2686. if (availableHeight < availableWidth / aspectRatio) {
  2687. availableWidth = Math.floor(availableHeight * aspectRatio);
  2688. }
  2689. return availableWidth;
  2690. }
  2691. /**
  2692. * Returns the presentation height.
  2693. */
  2694. function getPresentationHeihgt() {
  2695. var remoteVideos = $('#remoteVideos');
  2696. return window.innerHeight - remoteVideos.outerHeight();
  2697. }
  2698. /**
  2699. * Resizes the presentation iframe.
  2700. */
  2701. function resize() {
  2702. if ($('#presentation>iframe')) {
  2703. $('#presentation>iframe').width(getPresentationWidth());
  2704. $('#presentation>iframe').height(getPresentationHeihgt());
  2705. }
  2706. }
  2707. /**
  2708. * Shows/hides a presentation.
  2709. */
  2710. function setPresentationVisible(visible) {
  2711. var prezi = $('#presentation>iframe');
  2712. if (visible) {
  2713. // Trigger the video.selected event to indicate a change in the
  2714. // large video.
  2715. $(document).trigger("video.selected", [true]);
  2716. $('#largeVideo').fadeOut(300);
  2717. prezi.fadeIn(300, function() {
  2718. prezi.css({opacity:'1'});
  2719. ToolbarToggler.dockToolbar(true);
  2720. VideoLayout.setLargeVideoVisible(false);
  2721. });
  2722. $('#activeSpeaker').css('visibility', 'hidden');
  2723. }
  2724. else {
  2725. if (prezi.css('opacity') == '1') {
  2726. prezi.fadeOut(300, function () {
  2727. prezi.css({opacity:'0'});
  2728. $('#reloadPresentation').css({display:'none'});
  2729. $('#largeVideo').fadeIn(300, function() {
  2730. VideoLayout.setLargeVideoVisible(true);
  2731. ToolbarToggler.dockToolbar(false);
  2732. });
  2733. });
  2734. }
  2735. }
  2736. }
  2737. /**
  2738. * Presentation has been removed.
  2739. */
  2740. $(document).bind('presentationremoved.muc', presentationRemoved);
  2741. /**
  2742. * Presentation has been added.
  2743. */
  2744. $(document).bind('presentationadded.muc', presentationAdded);
  2745. /*
  2746. * Indicates presentation slide change.
  2747. */
  2748. $(document).bind('gotoslide.muc', function (event, jid, presUrl, current) {
  2749. if (preziPlayer && preziPlayer.getCurrentStep() != current) {
  2750. preziPlayer.flyToStep(current);
  2751. var animationStepsArray = preziPlayer.getAnimationCountOnSteps();
  2752. for (var i = 0; i < parseInt(animationStepsArray[current]); i++) {
  2753. preziPlayer.flyToStep(current, i);
  2754. }
  2755. }
  2756. });
  2757. /**
  2758. * On video selected event.
  2759. */
  2760. $(document).bind('video.selected', function (event, isPresentation) {
  2761. if (!isPresentation && $('#presentation>iframe')) {
  2762. setPresentationVisible(false);
  2763. }
  2764. });
  2765. $(window).resize(function () {
  2766. resize();
  2767. });
  2768. module.exports = Prezi;
  2769. },{"../toolbars/ToolbarToggler":25,"../util/MessageHandler":27,"../util/UIUtil":29,"../videolayout/VideoLayout":31,"./PreziPlayer":15}],15:[function(require,module,exports){
  2770. (function() {
  2771. "use strict";
  2772. var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; };
  2773. window.PreziPlayer = (function() {
  2774. PreziPlayer.API_VERSION = 1;
  2775. PreziPlayer.CURRENT_STEP = 'currentStep';
  2776. PreziPlayer.CURRENT_ANIMATION_STEP = 'currentAnimationStep';
  2777. PreziPlayer.CURRENT_OBJECT = 'currentObject';
  2778. PreziPlayer.STATUS_LOADING = 'loading';
  2779. PreziPlayer.STATUS_READY = 'ready';
  2780. PreziPlayer.STATUS_CONTENT_READY = 'contentready';
  2781. PreziPlayer.EVENT_CURRENT_STEP = "currentStepChange";
  2782. PreziPlayer.EVENT_CURRENT_ANIMATION_STEP = "currentAnimationStepChange";
  2783. PreziPlayer.EVENT_CURRENT_OBJECT = "currentObjectChange";
  2784. PreziPlayer.EVENT_STATUS = "statusChange";
  2785. PreziPlayer.EVENT_PLAYING = "isAutoPlayingChange";
  2786. PreziPlayer.EVENT_IS_MOVING = "isMovingChange";
  2787. PreziPlayer.domain = "https://prezi.com";
  2788. PreziPlayer.path = "/player/";
  2789. PreziPlayer.players = {};
  2790. PreziPlayer.binded_methods = ['changesHandler'];
  2791. PreziPlayer.createMultiplePlayers = function(optionArray){
  2792. for(var i=0; i<optionArray.length; i++) {
  2793. var optionSet = optionArray[i];
  2794. new PreziPlayer(optionSet.id, optionSet);
  2795. };
  2796. };
  2797. PreziPlayer.messageReceived = function(event){
  2798. var message, item, player;
  2799. try {
  2800. message = JSON.parse(event.data);
  2801. if (message.id && (player = PreziPlayer.players[message.id])) {
  2802. if (player.options.debug === true) {
  2803. if (console && console.log)
  2804. console.log('received', message);
  2805. }
  2806. if (message.type === "changes") {
  2807. player.changesHandler(message);
  2808. }
  2809. for (var i = 0; i < player.callbacks.length; i++) {
  2810. item = player.callbacks[i];
  2811. if (item && message.type === item.event) {
  2812. item.callback(message);
  2813. }
  2814. }
  2815. }
  2816. } catch (e) { }
  2817. };
  2818. function PreziPlayer(id, options) {
  2819. var params, paramString = "", _this = this;
  2820. if (PreziPlayer.players[id]){
  2821. PreziPlayer.players[id].destroy();
  2822. }
  2823. for(var i=0; i<PreziPlayer.binded_methods.length; i++) {
  2824. var method_name = PreziPlayer.binded_methods[i];
  2825. _this[method_name] = __bind(_this[method_name], _this);
  2826. };
  2827. options = options || {};
  2828. this.options = options;
  2829. this.values = {'status': PreziPlayer.STATUS_LOADING};
  2830. this.values[PreziPlayer.CURRENT_STEP] = 0;
  2831. this.values[PreziPlayer.CURRENT_ANIMATION_STEP] = 0;
  2832. this.values[PreziPlayer.CURRENT_OBJECT] = null;
  2833. this.callbacks = [];
  2834. this.id = id;
  2835. this.embedTo = document.getElementById(id);
  2836. if (!this.embedTo) {
  2837. throw "The element id is not available.";
  2838. }
  2839. this.iframe = document.createElement('iframe');
  2840. params = [
  2841. { name: 'oid', value: options.preziId },
  2842. { name: 'explorable', value: options.explorable ? 1 : 0 },
  2843. { name: 'controls', value: options.controls ? 1 : 0 }
  2844. ];
  2845. for(var i=0; i<params.length; i++) {
  2846. var param = params[i];
  2847. paramString += (i===0 ? "?" : "&") + param.name + "=" + param.value;
  2848. };
  2849. this.iframe.src = PreziPlayer.domain + PreziPlayer.path + paramString;
  2850. this.iframe.frameBorder = 0;
  2851. this.iframe.scrolling = "no";
  2852. this.iframe.width = options.width || 640;
  2853. this.iframe.height = options.height || 480;
  2854. this.embedTo.innerHTML = '';
  2855. // JITSI: IN CASE SOMETHING GOES WRONG.
  2856. try {
  2857. this.embedTo.appendChild(this.iframe);
  2858. }
  2859. catch (err) {
  2860. console.log("CATCH ERROR");
  2861. }
  2862. // JITSI: Increase interval from 200 to 500, which fixes prezi
  2863. // crashes for us.
  2864. this.initPollInterval = setInterval(function(){
  2865. _this.sendMessage({'action': 'init'});
  2866. }, 500);
  2867. PreziPlayer.players[id] = this;
  2868. }
  2869. PreziPlayer.prototype.changesHandler = function(message) {
  2870. var key, value, j, item;
  2871. if (this.initPollInterval) {
  2872. clearInterval(this.initPollInterval);
  2873. this.initPollInterval = false;
  2874. }
  2875. for (key in message.data) {
  2876. if (message.data.hasOwnProperty(key)){
  2877. value = message.data[key];
  2878. this.values[key] = value;
  2879. for (j=0; j<this.callbacks.length; j++) {
  2880. item = this.callbacks[j];
  2881. if (item && item.event === key + "Change"){
  2882. item.callback({type: item.event, value: value});
  2883. }
  2884. }
  2885. }
  2886. }
  2887. };
  2888. PreziPlayer.prototype.destroy = function() {
  2889. if (this.initPollInterval) {
  2890. clearInterval(this.initPollInterval);
  2891. this.initPollInterval = false;
  2892. }
  2893. this.embedTo.innerHTML = '';
  2894. };
  2895. PreziPlayer.prototype.sendMessage = function(message) {
  2896. if (this.options.debug === true) {
  2897. if (console && console.log) console.log('sent', message);
  2898. }
  2899. message.version = PreziPlayer.API_VERSION;
  2900. message.id = this.id;
  2901. return this.iframe.contentWindow.postMessage(JSON.stringify(message), '*');
  2902. };
  2903. PreziPlayer.prototype.nextStep = /* nextStep is DEPRECATED */
  2904. PreziPlayer.prototype.flyToNextStep = function() {
  2905. return this.sendMessage({
  2906. 'action': 'present',
  2907. 'data': ['moveToNextStep']
  2908. });
  2909. };
  2910. PreziPlayer.prototype.previousStep = /* previousStep is DEPRECATED */
  2911. PreziPlayer.prototype.flyToPreviousStep = function() {
  2912. return this.sendMessage({
  2913. 'action': 'present',
  2914. 'data': ['moveToPrevStep']
  2915. });
  2916. };
  2917. PreziPlayer.prototype.toStep = /* toStep is DEPRECATED */
  2918. PreziPlayer.prototype.flyToStep = function(step, animation_step) {
  2919. var obj = this;
  2920. // check animation_step
  2921. if (animation_step > 0 &&
  2922. obj.values.animationCountOnSteps &&
  2923. obj.values.animationCountOnSteps[step] <= animation_step) {
  2924. animation_step = obj.values.animationCountOnSteps[step];
  2925. }
  2926. // jump to animation steps by calling flyToNextStep()
  2927. function doAnimationSteps() {
  2928. if (obj.values.isMoving == true) {
  2929. setTimeout(doAnimationSteps, 100); // wait until the flight ends
  2930. return;
  2931. }
  2932. while (animation_step-- > 0) {
  2933. obj.flyToNextStep(); // do the animation steps
  2934. }
  2935. }
  2936. setTimeout(doAnimationSteps, 200); // 200ms is the internal "reporting" time
  2937. // jump to the step
  2938. return this.sendMessage({
  2939. 'action': 'present',
  2940. 'data': ['moveToStep', step]
  2941. });
  2942. };
  2943. PreziPlayer.prototype.toObject = /* toObject is DEPRECATED */
  2944. PreziPlayer.prototype.flyToObject = function(objectId) {
  2945. return this.sendMessage({
  2946. 'action': 'present',
  2947. 'data': ['moveToObject', objectId]
  2948. });
  2949. };
  2950. PreziPlayer.prototype.play = function(defaultDelay) {
  2951. return this.sendMessage({
  2952. 'action': 'present',
  2953. 'data': ['startAutoPlay', defaultDelay]
  2954. });
  2955. };
  2956. PreziPlayer.prototype.stop = function() {
  2957. return this.sendMessage({
  2958. 'action': 'present',
  2959. 'data': ['stopAutoPlay']
  2960. });
  2961. };
  2962. PreziPlayer.prototype.pause = function(defaultDelay) {
  2963. return this.sendMessage({
  2964. 'action': 'present',
  2965. 'data': ['pauseAutoPlay', defaultDelay]
  2966. });
  2967. };
  2968. PreziPlayer.prototype.getCurrentStep = function() {
  2969. return this.values.currentStep;
  2970. };
  2971. PreziPlayer.prototype.getCurrentAnimationStep = function() {
  2972. return this.values.currentAnimationStep;
  2973. };
  2974. PreziPlayer.prototype.getCurrentObject = function() {
  2975. return this.values.currentObject;
  2976. };
  2977. PreziPlayer.prototype.getStatus = function() {
  2978. return this.values.status;
  2979. };
  2980. PreziPlayer.prototype.isPlaying = function() {
  2981. return this.values.isAutoPlaying;
  2982. };
  2983. PreziPlayer.prototype.getStepCount = function() {
  2984. return this.values.stepCount;
  2985. };
  2986. PreziPlayer.prototype.getAnimationCountOnSteps = function() {
  2987. return this.values.animationCountOnSteps;
  2988. };
  2989. PreziPlayer.prototype.getTitle = function() {
  2990. return this.values.title;
  2991. };
  2992. PreziPlayer.prototype.setDimensions = function(dims) {
  2993. for (var parameter in dims) {
  2994. this.iframe[parameter] = dims[parameter];
  2995. }
  2996. }
  2997. PreziPlayer.prototype.getDimensions = function() {
  2998. return {
  2999. width: parseInt(this.iframe.width, 10),
  3000. height: parseInt(this.iframe.height, 10)
  3001. }
  3002. }
  3003. PreziPlayer.prototype.on = function(event, callback) {
  3004. this.callbacks.push({
  3005. event: event,
  3006. callback: callback
  3007. });
  3008. };
  3009. PreziPlayer.prototype.off = function(event, callback) {
  3010. var j, item;
  3011. if (event === undefined) {
  3012. this.callbacks = [];
  3013. }
  3014. j = this.callbacks.length;
  3015. while (j--) {
  3016. item = this.callbacks[j];
  3017. if (item && item.event === event && (callback === undefined || item.callback === callback)){
  3018. this.callbacks.splice(j, 1);
  3019. }
  3020. }
  3021. };
  3022. if (window.addEventListener) {
  3023. window.addEventListener('message', PreziPlayer.messageReceived, false);
  3024. } else {
  3025. window.attachEvent('onmessage', PreziPlayer.messageReceived);
  3026. }
  3027. return PreziPlayer;
  3028. })();
  3029. })();
  3030. module.exports = PreziPlayer;
  3031. },{}],16:[function(require,module,exports){
  3032. var Chat = require("./chat/Chat");
  3033. var ContactList = require("./contactlist/ContactList");
  3034. var Settings = require("./../../settings/Settings");
  3035. var SettingsMenu = require("./settings/SettingsMenu");
  3036. var VideoLayout = require("../videolayout/VideoLayout");
  3037. var ToolbarToggler = require("../toolbars/ToolbarToggler");
  3038. var UIUtil = require("../util/UIUtil");
  3039. /**
  3040. * Toggler for the chat, contact list, settings menu, etc..
  3041. */
  3042. var PanelToggler = (function(my) {
  3043. var currentlyOpen = null;
  3044. var buttons = {
  3045. '#chatspace': '#chatBottomButton',
  3046. '#contactlist': '#contactListButton',
  3047. '#settingsmenu': '#settingsButton'
  3048. };
  3049. /**
  3050. * Resizes the video area
  3051. * @param isClosing whether the side panel is going to be closed or is going to open / remain opened
  3052. * @param completeFunction a function to be called when the video space is resized
  3053. */
  3054. var resizeVideoArea = function(isClosing, completeFunction) {
  3055. var videospace = $('#videospace');
  3056. var panelSize = isClosing ? [0, 0] : PanelToggler.getPanelSize();
  3057. var videospaceWidth = window.innerWidth - panelSize[0];
  3058. var videospaceHeight = window.innerHeight;
  3059. var videoSize
  3060. = VideoLayout.getVideoSize(null, null, videospaceWidth, videospaceHeight);
  3061. var videoWidth = videoSize[0];
  3062. var videoHeight = videoSize[1];
  3063. var videoPosition = VideoLayout.getVideoPosition(videoWidth,
  3064. videoHeight,
  3065. videospaceWidth,
  3066. videospaceHeight);
  3067. var horizontalIndent = videoPosition[0];
  3068. var verticalIndent = videoPosition[1];
  3069. var thumbnailSize = VideoLayout.calculateThumbnailSize(videospaceWidth);
  3070. var thumbnailsWidth = thumbnailSize[0];
  3071. var thumbnailsHeight = thumbnailSize[1];
  3072. //for chat
  3073. videospace.animate({
  3074. right: panelSize[0],
  3075. width: videospaceWidth,
  3076. height: videospaceHeight
  3077. },
  3078. {
  3079. queue: false,
  3080. duration: 500,
  3081. complete: completeFunction
  3082. });
  3083. $('#remoteVideos').animate({
  3084. height: thumbnailsHeight
  3085. },
  3086. {
  3087. queue: false,
  3088. duration: 500
  3089. });
  3090. $('#remoteVideos>span').animate({
  3091. height: thumbnailsHeight,
  3092. width: thumbnailsWidth
  3093. },
  3094. {
  3095. queue: false,
  3096. duration: 500,
  3097. complete: function () {
  3098. $(document).trigger(
  3099. "remotevideo.resized",
  3100. [thumbnailsWidth,
  3101. thumbnailsHeight]);
  3102. }
  3103. });
  3104. $('#largeVideoContainer').animate({
  3105. width: videospaceWidth,
  3106. height: videospaceHeight
  3107. },
  3108. {
  3109. queue: false,
  3110. duration: 500
  3111. });
  3112. $('#largeVideo').animate({
  3113. width: videoWidth,
  3114. height: videoHeight,
  3115. top: verticalIndent,
  3116. bottom: verticalIndent,
  3117. left: horizontalIndent,
  3118. right: horizontalIndent
  3119. },
  3120. {
  3121. queue: false,
  3122. duration: 500
  3123. });
  3124. };
  3125. /**
  3126. * Toggles the windows in the side panel
  3127. * @param object the window that should be shown
  3128. * @param selector the selector for the element containing the panel
  3129. * @param onOpenComplete function to be called when the panel is opened
  3130. * @param onOpen function to be called if the window is going to be opened
  3131. * @param onClose function to be called if the window is going to be closed
  3132. */
  3133. var toggle = function(object, selector, onOpenComplete, onOpen, onClose) {
  3134. UIUtil.buttonClick(buttons[selector], "active");
  3135. if (object.isVisible()) {
  3136. $("#toast-container").animate({
  3137. right: '5px'
  3138. },
  3139. {
  3140. queue: false,
  3141. duration: 500
  3142. });
  3143. $(selector).hide("slide", {
  3144. direction: "right",
  3145. queue: false,
  3146. duration: 500
  3147. });
  3148. if(typeof onClose === "function") {
  3149. onClose();
  3150. }
  3151. currentlyOpen = null;
  3152. }
  3153. else {
  3154. // Undock the toolbar when the chat is shown and if we're in a
  3155. // video mode.
  3156. if (VideoLayout.isLargeVideoVisible()) {
  3157. ToolbarToggler.dockToolbar(false);
  3158. }
  3159. if(currentlyOpen) {
  3160. var current = $(currentlyOpen);
  3161. UIUtil.buttonClick(buttons[currentlyOpen], "active");
  3162. current.css('z-index', 4);
  3163. setTimeout(function () {
  3164. current.css('display', 'none');
  3165. current.css('z-index', 5);
  3166. }, 500);
  3167. }
  3168. $("#toast-container").animate({
  3169. right: (PanelToggler.getPanelSize()[0] + 5) + 'px'
  3170. },
  3171. {
  3172. queue: false,
  3173. duration: 500
  3174. });
  3175. $(selector).show("slide", {
  3176. direction: "right",
  3177. queue: false,
  3178. duration: 500,
  3179. complete: onOpenComplete
  3180. });
  3181. if(typeof onOpen === "function") {
  3182. onOpen();
  3183. }
  3184. currentlyOpen = selector;
  3185. }
  3186. };
  3187. /**
  3188. * Opens / closes the chat area.
  3189. */
  3190. my.toggleChat = function() {
  3191. var chatCompleteFunction = Chat.isVisible() ?
  3192. function() {} : function () {
  3193. Chat.scrollChatToBottom();
  3194. $('#chatspace').trigger('shown');
  3195. };
  3196. resizeVideoArea(Chat.isVisible(), chatCompleteFunction);
  3197. toggle(Chat,
  3198. '#chatspace',
  3199. function () {
  3200. // Request the focus in the nickname field or the chat input field.
  3201. if ($('#nickname').css('visibility') === 'visible') {
  3202. $('#nickinput').focus();
  3203. } else {
  3204. $('#usermsg').focus();
  3205. }
  3206. },
  3207. null,
  3208. Chat.resizeChat,
  3209. null);
  3210. };
  3211. /**
  3212. * Opens / closes the contact list area.
  3213. */
  3214. my.toggleContactList = function () {
  3215. var completeFunction = ContactList.isVisible() ?
  3216. function() {} : function () { $('#contactlist').trigger('shown');};
  3217. resizeVideoArea(ContactList.isVisible(), completeFunction);
  3218. toggle(ContactList,
  3219. '#contactlist',
  3220. null,
  3221. function() {
  3222. ContactList.setVisualNotification(false);
  3223. },
  3224. null);
  3225. };
  3226. /**
  3227. * Opens / closes the settings menu
  3228. */
  3229. my.toggleSettingsMenu = function() {
  3230. resizeVideoArea(SettingsMenu.isVisible(), function (){});
  3231. toggle(SettingsMenu,
  3232. '#settingsmenu',
  3233. null,
  3234. function() {
  3235. var settings = Settings.getSettings();
  3236. $('#setDisplayName').get(0).value = settings.displayName;
  3237. $('#setEmail').get(0).value = settings.email;
  3238. },
  3239. null);
  3240. };
  3241. /**
  3242. * Returns the size of the side panel.
  3243. */
  3244. my.getPanelSize = function () {
  3245. var availableHeight = window.innerHeight;
  3246. var availableWidth = window.innerWidth;
  3247. var panelWidth = 200;
  3248. if (availableWidth * 0.2 < 200) {
  3249. panelWidth = availableWidth * 0.2;
  3250. }
  3251. return [panelWidth, availableHeight];
  3252. };
  3253. my.isVisible = function() {
  3254. return (Chat.isVisible() || ContactList.isVisible() || SettingsMenu.isVisible());
  3255. };
  3256. return my;
  3257. }(PanelToggler || {}));
  3258. module.exports = PanelToggler;
  3259. },{"../toolbars/ToolbarToggler":25,"../util/UIUtil":29,"../videolayout/VideoLayout":31,"./../../settings/Settings":37,"./chat/Chat":17,"./contactlist/ContactList":21,"./settings/SettingsMenu":22}],17:[function(require,module,exports){
  3260. /* global $, Util, nickname:true */
  3261. var Replacement = require("./Replacement");
  3262. var CommandsProcessor = require("./Commands");
  3263. var ToolbarToggler = require("../../toolbars/ToolbarToggler");
  3264. var smileys = require("./smileys.json").smileys;
  3265. var NicknameHandler = require("../../util/NicknameHandler");
  3266. var UIUtil = require("../../util/UIUtil");
  3267. var UIEvents = require("../../../../service/UI/UIEvents");
  3268. var notificationInterval = false;
  3269. var unreadMessages = 0;
  3270. /**
  3271. * Shows/hides a visual notification, indicating that a message has arrived.
  3272. */
  3273. function setVisualNotification(show) {
  3274. var unreadMsgElement = document.getElementById('unreadMessages');
  3275. var unreadMsgBottomElement
  3276. = document.getElementById('bottomUnreadMessages');
  3277. var glower = $('#chatButton');
  3278. var bottomGlower = $('#chatBottomButton');
  3279. if (unreadMessages) {
  3280. unreadMsgElement.innerHTML = unreadMessages.toString();
  3281. unreadMsgBottomElement.innerHTML = unreadMessages.toString();
  3282. ToolbarToggler.dockToolbar(true);
  3283. var chatButtonElement
  3284. = document.getElementById('chatButton').parentNode;
  3285. var leftIndent = (UIUtil.getTextWidth(chatButtonElement) -
  3286. UIUtil.getTextWidth(unreadMsgElement)) / 2;
  3287. var topIndent = (UIUtil.getTextHeight(chatButtonElement) -
  3288. UIUtil.getTextHeight(unreadMsgElement)) / 2 - 3;
  3289. unreadMsgElement.setAttribute(
  3290. 'style',
  3291. 'top:' + topIndent +
  3292. '; left:' + leftIndent + ';');
  3293. var chatBottomButtonElement
  3294. = document.getElementById('chatBottomButton').parentNode;
  3295. var bottomLeftIndent = (UIUtil.getTextWidth(chatBottomButtonElement) -
  3296. UIUtil.getTextWidth(unreadMsgBottomElement)) / 2;
  3297. var bottomTopIndent = (UIUtil.getTextHeight(chatBottomButtonElement) -
  3298. UIUtil.getTextHeight(unreadMsgBottomElement)) / 2 - 2;
  3299. unreadMsgBottomElement.setAttribute(
  3300. 'style',
  3301. 'top:' + bottomTopIndent +
  3302. '; left:' + bottomLeftIndent + ';');
  3303. if (!glower.hasClass('icon-chat-simple')) {
  3304. glower.removeClass('icon-chat');
  3305. glower.addClass('icon-chat-simple');
  3306. }
  3307. }
  3308. else {
  3309. unreadMsgElement.innerHTML = '';
  3310. unreadMsgBottomElement.innerHTML = '';
  3311. glower.removeClass('icon-chat-simple');
  3312. glower.addClass('icon-chat');
  3313. }
  3314. if (show && !notificationInterval) {
  3315. notificationInterval = window.setInterval(function () {
  3316. glower.toggleClass('active');
  3317. bottomGlower.toggleClass('active glowing');
  3318. }, 800);
  3319. }
  3320. else if (!show && notificationInterval) {
  3321. window.clearInterval(notificationInterval);
  3322. notificationInterval = false;
  3323. glower.removeClass('active');
  3324. bottomGlower.removeClass('glowing');
  3325. bottomGlower.addClass('active');
  3326. }
  3327. }
  3328. /**
  3329. * Returns the current time in the format it is shown to the user
  3330. * @returns {string}
  3331. */
  3332. function getCurrentTime() {
  3333. var now = new Date();
  3334. var hour = now.getHours();
  3335. var minute = now.getMinutes();
  3336. var second = now.getSeconds();
  3337. if(hour.toString().length === 1) {
  3338. hour = '0'+hour;
  3339. }
  3340. if(minute.toString().length === 1) {
  3341. minute = '0'+minute;
  3342. }
  3343. if(second.toString().length === 1) {
  3344. second = '0'+second;
  3345. }
  3346. return hour+':'+minute+':'+second;
  3347. }
  3348. function toggleSmileys()
  3349. {
  3350. var smileys = $('#smileysContainer');
  3351. if(!smileys.is(':visible')) {
  3352. smileys.show("slide", { direction: "down", duration: 300});
  3353. } else {
  3354. smileys.hide("slide", { direction: "down", duration: 300});
  3355. }
  3356. $('#usermsg').focus();
  3357. }
  3358. function addClickFunction(smiley, number) {
  3359. smiley.onclick = function addSmileyToMessage() {
  3360. var usermsg = $('#usermsg');
  3361. var message = usermsg.val();
  3362. message += smileys['smiley' + number];
  3363. usermsg.val(message);
  3364. usermsg.get(0).setSelectionRange(message.length, message.length);
  3365. toggleSmileys();
  3366. usermsg.focus();
  3367. };
  3368. }
  3369. /**
  3370. * Adds the smileys container to the chat
  3371. */
  3372. function addSmileys() {
  3373. var smileysContainer = document.createElement('div');
  3374. smileysContainer.id = 'smileysContainer';
  3375. for(var i = 1; i <= 21; i++) {
  3376. var smileyContainer = document.createElement('div');
  3377. smileyContainer.id = 'smiley' + i;
  3378. smileyContainer.className = 'smileyContainer';
  3379. var smiley = document.createElement('img');
  3380. smiley.src = 'images/smileys/smiley' + i + '.svg';
  3381. smiley.className = 'smiley';
  3382. addClickFunction(smiley, i);
  3383. smileyContainer.appendChild(smiley);
  3384. smileysContainer.appendChild(smileyContainer);
  3385. }
  3386. $("#chatspace").append(smileysContainer);
  3387. }
  3388. /**
  3389. * Resizes the chat conversation.
  3390. */
  3391. function resizeChatConversation() {
  3392. var msgareaHeight = $('#usermsg').outerHeight();
  3393. var chatspace = $('#chatspace');
  3394. var width = chatspace.width();
  3395. var chat = $('#chatconversation');
  3396. var smileys = $('#smileysarea');
  3397. smileys.height(msgareaHeight);
  3398. $("#smileys").css('bottom', (msgareaHeight - 26) / 2);
  3399. $('#smileysContainer').css('bottom', msgareaHeight);
  3400. chat.width(width - 10);
  3401. chat.height(window.innerHeight - 15 - msgareaHeight);
  3402. }
  3403. /**
  3404. * Chat related user interface.
  3405. */
  3406. var Chat = (function (my) {
  3407. /**
  3408. * Initializes chat related interface.
  3409. */
  3410. my.init = function () {
  3411. if(NicknameHandler.getNickname())
  3412. Chat.setChatConversationMode(true);
  3413. NicknameHandler.addListener(UIEvents.NICKNAME_CHANGED,
  3414. function (nickname) {
  3415. Chat.setChatConversationMode(true);
  3416. });
  3417. $('#nickinput').keydown(function (event) {
  3418. if (event.keyCode === 13) {
  3419. event.preventDefault();
  3420. var val = UIUtil.escapeHtml(this.value);
  3421. this.value = '';
  3422. if (!NicknameHandler.getNickname()) {
  3423. NicknameHandler.setNickname(val);
  3424. return;
  3425. }
  3426. }
  3427. });
  3428. $('#usermsg').keydown(function (event) {
  3429. if (event.keyCode === 13) {
  3430. event.preventDefault();
  3431. var value = this.value;
  3432. $('#usermsg').val('').trigger('autosize.resize');
  3433. this.focus();
  3434. var command = new CommandsProcessor(value);
  3435. if(command.isCommand())
  3436. {
  3437. command.processCommand();
  3438. }
  3439. else
  3440. {
  3441. var message = UIUtil.escapeHtml(value);
  3442. APP.xmpp.sendChatMessage(message, NicknameHandler.getNickname());
  3443. }
  3444. }
  3445. });
  3446. var onTextAreaResize = function () {
  3447. resizeChatConversation();
  3448. Chat.scrollChatToBottom();
  3449. };
  3450. $('#usermsg').autosize({callback: onTextAreaResize});
  3451. $("#chatspace").bind("shown",
  3452. function () {
  3453. unreadMessages = 0;
  3454. setVisualNotification(false);
  3455. });
  3456. addSmileys();
  3457. };
  3458. /**
  3459. * Appends the given message to the chat conversation.
  3460. */
  3461. my.updateChatConversation = function (from, displayName, message) {
  3462. var divClassName = '';
  3463. if (APP.xmpp.myJid() === from) {
  3464. divClassName = "localuser";
  3465. }
  3466. else {
  3467. divClassName = "remoteuser";
  3468. if (!Chat.isVisible()) {
  3469. unreadMessages++;
  3470. UIUtil.playSoundNotification('chatNotification');
  3471. setVisualNotification(true);
  3472. }
  3473. }
  3474. // replace links and smileys
  3475. // Strophe already escapes special symbols on sending,
  3476. // so we escape here only tags to avoid double &amp;
  3477. var escMessage = message.replace(/</g, '&lt;').
  3478. replace(/>/g, '&gt;').replace(/\n/g, '<br/>');
  3479. var escDisplayName = UIUtil.escapeHtml(displayName);
  3480. message = Replacement.processReplacements(escMessage);
  3481. var messageContainer =
  3482. '<div class="chatmessage">'+
  3483. '<img src="../images/chatArrow.svg" class="chatArrow">' +
  3484. '<div class="username ' + divClassName +'">' + escDisplayName +
  3485. '</div>' + '<div class="timestamp">' + getCurrentTime() +
  3486. '</div>' + '<div class="usermessage">' + message + '</div>' +
  3487. '</div>';
  3488. $('#chatconversation').append(messageContainer);
  3489. $('#chatconversation').animate(
  3490. { scrollTop: $('#chatconversation')[0].scrollHeight}, 1000);
  3491. };
  3492. /**
  3493. * Appends error message to the conversation
  3494. * @param errorMessage the received error message.
  3495. * @param originalText the original message.
  3496. */
  3497. my.chatAddError = function(errorMessage, originalText)
  3498. {
  3499. errorMessage = UIUtil.escapeHtml(errorMessage);
  3500. originalText = UIUtil.escapeHtml(originalText);
  3501. $('#chatconversation').append(
  3502. '<div class="errorMessage"><b>Error: </b>' + 'Your message' +
  3503. (originalText? (' \"'+ originalText + '\"') : "") +
  3504. ' was not sent.' +
  3505. (errorMessage? (' Reason: ' + errorMessage) : '') + '</div>');
  3506. $('#chatconversation').animate(
  3507. { scrollTop: $('#chatconversation')[0].scrollHeight}, 1000);
  3508. };
  3509. /**
  3510. * Sets the subject to the UI
  3511. * @param subject the subject
  3512. */
  3513. my.chatSetSubject = function(subject)
  3514. {
  3515. if(subject)
  3516. subject = subject.trim();
  3517. $('#subject').html(Replacement.linkify(UIUtil.escapeHtml(subject)));
  3518. if(subject === "")
  3519. {
  3520. $("#subject").css({display: "none"});
  3521. }
  3522. else
  3523. {
  3524. $("#subject").css({display: "block"});
  3525. }
  3526. };
  3527. /**
  3528. * Sets the chat conversation mode.
  3529. */
  3530. my.setChatConversationMode = function (isConversationMode) {
  3531. if (isConversationMode) {
  3532. $('#nickname').css({visibility: 'hidden'});
  3533. $('#chatconversation').css({visibility: 'visible'});
  3534. $('#usermsg').css({visibility: 'visible'});
  3535. $('#smileysarea').css({visibility: 'visible'});
  3536. $('#usermsg').focus();
  3537. }
  3538. };
  3539. /**
  3540. * Resizes the chat area.
  3541. */
  3542. my.resizeChat = function () {
  3543. var chatSize = require("../SidePanelToggler").getPanelSize();
  3544. $('#chatspace').width(chatSize[0]);
  3545. $('#chatspace').height(chatSize[1]);
  3546. resizeChatConversation();
  3547. };
  3548. /**
  3549. * Indicates if the chat is currently visible.
  3550. */
  3551. my.isVisible = function () {
  3552. return $('#chatspace').is(":visible");
  3553. };
  3554. /**
  3555. * Shows and hides the window with the smileys
  3556. */
  3557. my.toggleSmileys = toggleSmileys;
  3558. /**
  3559. * Scrolls chat to the bottom.
  3560. */
  3561. my.scrollChatToBottom = function() {
  3562. setTimeout(function () {
  3563. $('#chatconversation').scrollTop(
  3564. $('#chatconversation')[0].scrollHeight);
  3565. }, 5);
  3566. };
  3567. return my;
  3568. }(Chat || {}));
  3569. module.exports = Chat;
  3570. },{"../../../../service/UI/UIEvents":91,"../../toolbars/ToolbarToggler":25,"../../util/NicknameHandler":28,"../../util/UIUtil":29,"../SidePanelToggler":16,"./Commands":18,"./Replacement":19,"./smileys.json":20}],18:[function(require,module,exports){
  3571. var UIUtil = require("../../util/UIUtil");
  3572. /**
  3573. * List with supported commands. The keys are the names of the commands and
  3574. * the value is the function that processes the message.
  3575. * @type {{String: function}}
  3576. */
  3577. var commands = {
  3578. "topic" : processTopic
  3579. };
  3580. /**
  3581. * Extracts the command from the message.
  3582. * @param message the received message
  3583. * @returns {string} the command
  3584. */
  3585. function getCommand(message)
  3586. {
  3587. if(message)
  3588. {
  3589. for(var command in commands)
  3590. {
  3591. if(message.indexOf("/" + command) == 0)
  3592. return command;
  3593. }
  3594. }
  3595. return "";
  3596. };
  3597. /**
  3598. * Processes the data for topic command.
  3599. * @param commandArguments the arguments of the topic command.
  3600. */
  3601. function processTopic(commandArguments)
  3602. {
  3603. var topic = UIUtil.escapeHtml(commandArguments);
  3604. APP.xmpp.setSubject(topic);
  3605. }
  3606. /**
  3607. * Constructs new CommandProccessor instance from a message that
  3608. * handles commands received via chat messages.
  3609. * @param message the message
  3610. * @constructor
  3611. */
  3612. function CommandsProcessor(message)
  3613. {
  3614. var command = getCommand(message);
  3615. /**
  3616. * Returns the name of the command.
  3617. * @returns {String} the command
  3618. */
  3619. this.getCommand = function()
  3620. {
  3621. return command;
  3622. };
  3623. var messageArgument = message.substr(command.length + 2);
  3624. /**
  3625. * Returns the arguments of the command.
  3626. * @returns {string}
  3627. */
  3628. this.getArgument = function()
  3629. {
  3630. return messageArgument;
  3631. };
  3632. }
  3633. /**
  3634. * Checks whether this instance is valid command or not.
  3635. * @returns {boolean}
  3636. */
  3637. CommandsProcessor.prototype.isCommand = function()
  3638. {
  3639. if(this.getCommand())
  3640. return true;
  3641. return false;
  3642. };
  3643. /**
  3644. * Processes the command.
  3645. */
  3646. CommandsProcessor.prototype.processCommand = function()
  3647. {
  3648. if(!this.isCommand())
  3649. return;
  3650. commands[this.getCommand()](this.getArgument());
  3651. };
  3652. module.exports = CommandsProcessor;
  3653. },{"../../util/UIUtil":29}],19:[function(require,module,exports){
  3654. var Smileys = require("./smileys.json");
  3655. /**
  3656. * Processes links and smileys in "body"
  3657. */
  3658. function processReplacements(body)
  3659. {
  3660. //make links clickable
  3661. body = linkify(body);
  3662. //add smileys
  3663. body = smilify(body);
  3664. return body;
  3665. }
  3666. /**
  3667. * Finds and replaces all links in the links in "body"
  3668. * with their <a href=""></a>
  3669. */
  3670. function linkify(inputText)
  3671. {
  3672. var replacedText, replacePattern1, replacePattern2, replacePattern3;
  3673. //URLs starting with http://, https://, or ftp://
  3674. replacePattern1 = /(\b(https?|ftp):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/gim;
  3675. replacedText = inputText.replace(replacePattern1, '<a href="$1" target="_blank">$1</a>');
  3676. //URLs starting with "www." (without // before it, or it'd re-link the ones done above).
  3677. replacePattern2 = /(^|[^\/])(www\.[\S]+(\b|$))/gim;
  3678. replacedText = replacedText.replace(replacePattern2, '$1<a href="http://$2" target="_blank">$2</a>');
  3679. //Change email addresses to mailto:: links.
  3680. replacePattern3 = /(([a-zA-Z0-9\-\_\.])+@[a-zA-Z\_]+?(\.[a-zA-Z]{2,6})+)/gim;
  3681. replacedText = replacedText.replace(replacePattern3, '<a href="mailto:$1">$1</a>');
  3682. return replacedText;
  3683. }
  3684. /**
  3685. * Replaces common smiley strings with images
  3686. */
  3687. function smilify(body)
  3688. {
  3689. if(!body) {
  3690. return body;
  3691. }
  3692. var regexs = Smileys["regexs"];
  3693. for(var smiley in regexs) {
  3694. if(regexs.hasOwnProperty(smiley)) {
  3695. body = body.replace(regexs[smiley],
  3696. '<img class="smiley" src="images/smileys/' + smiley + '.svg">');
  3697. }
  3698. }
  3699. return body;
  3700. }
  3701. module.exports = {
  3702. processReplacements: processReplacements,
  3703. linkify: linkify
  3704. };
  3705. },{"./smileys.json":20}],20:[function(require,module,exports){
  3706. module.exports={
  3707. "smileys": {
  3708. "smiley1": ":)",
  3709. "smiley2": ":(",
  3710. "smiley3": ":D",
  3711. "smiley4": "(y)",
  3712. "smiley5": " :P",
  3713. "smiley6": "(wave)",
  3714. "smiley7": "(blush)",
  3715. "smiley8": "(chuckle)",
  3716. "smiley9": "(shocked)",
  3717. "smiley10": ":*",
  3718. "smiley11": "(n)",
  3719. "smiley12": "(search)",
  3720. "smiley13": " <3",
  3721. "smiley14": "(oops)",
  3722. "smiley15": "(angry)",
  3723. "smiley16": "(angel)",
  3724. "smiley17": "(sick)",
  3725. "smiley18": ";(",
  3726. "smiley19": "(bomb)",
  3727. "smiley20": "(clap)",
  3728. "smiley21": " ;)"
  3729. },
  3730. "regexs": {
  3731. "smiley2": /(:-\(\(|:-\(|:\(\(|:\(|\(sad\))/gi,
  3732. "smiley3": /(:-\)\)|:\)\)|\(lol\)|:-D|:D)/gi,
  3733. "smiley1": /(:-\)|:\))/gi,
  3734. "smiley4": /(\(y\)|\(Y\)|\(ok\))/gi,
  3735. "smiley5": /(:-P|:P|:-p|:p)/gi,
  3736. "smiley6": /(\(wave\))/gi,
  3737. "smiley7": /(\(blush\))/gi,
  3738. "smiley8": /(\(chuckle\))/gi,
  3739. "smiley9": /(:-0|\(shocked\))/gi,
  3740. "smiley10": /(:-\*|:\*|\(kiss\))/gi,
  3741. "smiley11": /(\(n\))/gi,
  3742. "smiley12": /(\(search\))/g,
  3743. "smiley13": /(<3|&lt;3|&amp;lt;3|\(L\)|\(l\)|\(H\)|\(h\))/gi,
  3744. "smiley14": /(\(oops\))/gi,
  3745. "smiley15": /(\(angry\))/gi,
  3746. "smiley16": /(\(angel\))/gi,
  3747. "smiley17": /(\(sick\))/gi,
  3748. "smiley18": /(;-\(\(|;\(\(|;-\(|;\(|:"\(|:"-\(|:~-\(|:~\(|\(upset\))/gi,
  3749. "smiley19": /(\(bomb\))/gi,
  3750. "smiley20": /(\(clap\))/gi,
  3751. "smiley21": /(;-\)|;\)|;-\)\)|;\)\)|;-D|;D|\(wink\))/gi
  3752. }
  3753. }
  3754. },{}],21:[function(require,module,exports){
  3755. var numberOfContacts = 0;
  3756. var notificationInterval;
  3757. /**
  3758. * Updates the number of participants in the contact list button and sets
  3759. * the glow
  3760. * @param delta indicates whether a new user has joined (1) or someone has
  3761. * left(-1)
  3762. */
  3763. function updateNumberOfParticipants(delta) {
  3764. //when the user is alone we don't show the number of participants
  3765. if(numberOfContacts === 0) {
  3766. $("#numberOfParticipants").text('');
  3767. numberOfContacts += delta;
  3768. } else if(numberOfContacts !== 0 && !ContactList.isVisible()) {
  3769. ContactList.setVisualNotification(true);
  3770. numberOfContacts += delta;
  3771. $("#numberOfParticipants").text(numberOfContacts);
  3772. }
  3773. }
  3774. /**
  3775. * Creates the avatar element.
  3776. *
  3777. * @return the newly created avatar element
  3778. */
  3779. function createAvatar(id) {
  3780. var avatar = document.createElement('img');
  3781. avatar.className = "icon-avatar avatar";
  3782. avatar.src = "https://www.gravatar.com/avatar/" + id + "?d=wavatar&size=30";
  3783. return avatar;
  3784. }
  3785. /**
  3786. * Creates the display name paragraph.
  3787. *
  3788. * @param displayName the display name to set
  3789. */
  3790. function createDisplayNameParagraph(key, displayName) {
  3791. var p = document.createElement('p');
  3792. if(displayName)
  3793. p.innerText = displayName;
  3794. else if(key)
  3795. {
  3796. p.setAttribute("data-i18n",key);
  3797. p.innerText = APP.translation.translateString(key);
  3798. }
  3799. return p;
  3800. }
  3801. function stopGlowing(glower) {
  3802. window.clearInterval(notificationInterval);
  3803. notificationInterval = false;
  3804. glower.removeClass('glowing');
  3805. if (!ContactList.isVisible()) {
  3806. glower.removeClass('active');
  3807. }
  3808. }
  3809. /**
  3810. * Contact list.
  3811. */
  3812. var ContactList = {
  3813. /**
  3814. * Indicates if the chat is currently visible.
  3815. *
  3816. * @return <tt>true</tt> if the chat is currently visible, <tt>false</tt> -
  3817. * otherwise
  3818. */
  3819. isVisible: function () {
  3820. return $('#contactlist').is(":visible");
  3821. },
  3822. /**
  3823. * Adds a contact for the given peerJid if such doesn't yet exist.
  3824. *
  3825. * @param peerJid the peerJid corresponding to the contact
  3826. * @param id the user's email or userId used to get the user's avatar
  3827. */
  3828. ensureAddContact: function (peerJid, id) {
  3829. var resourceJid = Strophe.getResourceFromJid(peerJid);
  3830. var contact = $('#contactlist>ul>li[id="' + resourceJid + '"]');
  3831. if (!contact || contact.length <= 0)
  3832. ContactList.addContact(peerJid, id);
  3833. },
  3834. /**
  3835. * Adds a contact for the given peer jid.
  3836. *
  3837. * @param peerJid the jid of the contact to add
  3838. * @param id the email or userId of the user
  3839. */
  3840. addContact: function (peerJid, id) {
  3841. var resourceJid = Strophe.getResourceFromJid(peerJid);
  3842. var contactlist = $('#contactlist>ul');
  3843. var newContact = document.createElement('li');
  3844. newContact.id = resourceJid;
  3845. newContact.className = "clickable";
  3846. newContact.onclick = function (event) {
  3847. if (event.currentTarget.className === "clickable") {
  3848. $(ContactList).trigger('contactclicked', [peerJid]);
  3849. }
  3850. };
  3851. newContact.appendChild(createAvatar(id));
  3852. newContact.appendChild(createDisplayNameParagraph("participant"));
  3853. var clElement = contactlist.get(0);
  3854. if (resourceJid === APP.xmpp.myResource()
  3855. && $('#contactlist>ul .title')[0].nextSibling.nextSibling) {
  3856. clElement.insertBefore(newContact,
  3857. $('#contactlist>ul .title')[0].nextSibling.nextSibling);
  3858. }
  3859. else {
  3860. clElement.appendChild(newContact);
  3861. }
  3862. updateNumberOfParticipants(1);
  3863. },
  3864. /**
  3865. * Removes a contact for the given peer jid.
  3866. *
  3867. * @param peerJid the peerJid corresponding to the contact to remove
  3868. */
  3869. removeContact: function (peerJid) {
  3870. var resourceJid = Strophe.getResourceFromJid(peerJid);
  3871. var contact = $('#contactlist>ul>li[id="' + resourceJid + '"]');
  3872. if (contact && contact.length > 0) {
  3873. var contactlist = $('#contactlist>ul');
  3874. contactlist.get(0).removeChild(contact.get(0));
  3875. updateNumberOfParticipants(-1);
  3876. }
  3877. },
  3878. setVisualNotification: function (show, stopGlowingIn) {
  3879. var glower = $('#contactListButton');
  3880. if (show && !notificationInterval) {
  3881. notificationInterval = window.setInterval(function () {
  3882. glower.toggleClass('active glowing');
  3883. }, 800);
  3884. }
  3885. else if (!show && notificationInterval) {
  3886. stopGlowing(glower);
  3887. }
  3888. if (stopGlowingIn) {
  3889. setTimeout(function () {
  3890. stopGlowing(glower);
  3891. }, stopGlowingIn);
  3892. }
  3893. },
  3894. setClickable: function (resourceJid, isClickable) {
  3895. var contact = $('#contactlist>ul>li[id="' + resourceJid + '"]');
  3896. if (isClickable) {
  3897. contact.addClass('clickable');
  3898. } else {
  3899. contact.removeClass('clickable');
  3900. }
  3901. },
  3902. onDisplayNameChange: function (peerJid, displayName) {
  3903. if (peerJid === 'localVideoContainer')
  3904. peerJid = APP.xmpp.myJid();
  3905. var resourceJid = Strophe.getResourceFromJid(peerJid);
  3906. var contactName = $('#contactlist #' + resourceJid + '>p');
  3907. if (contactName && displayName && displayName.length > 0)
  3908. contactName.html(displayName);
  3909. }
  3910. };
  3911. module.exports = ContactList;
  3912. },{}],22:[function(require,module,exports){
  3913. var Avatar = require("../../avatar/Avatar");
  3914. var Settings = require("./../../../settings/Settings");
  3915. var UIUtil = require("../../util/UIUtil");
  3916. var languages = require("../../../../service/translation/languages");
  3917. function generateLanguagesSelectBox()
  3918. {
  3919. var currentLang = APP.translation.getCurrentLanguage();
  3920. var html = "<select id=\"languages_selectbox\">";
  3921. var langArray = languages.getLanguages();
  3922. for(var i = 0; i < langArray.length; i++)
  3923. {
  3924. var lang = langArray[i];
  3925. html += "<option ";
  3926. if(lang === currentLang)
  3927. html += "selected ";
  3928. html += "value=\"" + lang + "\" data-i18n='languages:" + lang + "'>";
  3929. html += "</option>";
  3930. }
  3931. return html + "</select>";
  3932. }
  3933. var SettingsMenu = {
  3934. init: function () {
  3935. $("#updateSettings").before(generateLanguagesSelectBox());
  3936. APP.translation.translateElement($("#languages_selectbox"));
  3937. $('#settingsmenu>input').keyup(function(event){
  3938. if(event.keyCode === 13) {//enter
  3939. SettingsMenu.update();
  3940. }
  3941. });
  3942. $("#updateSettings").click(function () {
  3943. SettingsMenu.update();
  3944. });
  3945. },
  3946. update: function() {
  3947. var newDisplayName = UIUtil.escapeHtml($('#setDisplayName').get(0).value);
  3948. var newEmail = UIUtil.escapeHtml($('#setEmail').get(0).value);
  3949. if(newDisplayName) {
  3950. var displayName = Settings.setDisplayName(newDisplayName);
  3951. APP.xmpp.addToPresence("displayName", displayName, true);
  3952. }
  3953. var language = $("#languages_selectbox").val();
  3954. APP.translation.setLanguage(language);
  3955. Settings.setLanguage(language);
  3956. APP.xmpp.addToPresence("email", newEmail);
  3957. var email = Settings.setEmail(newEmail);
  3958. Avatar.setUserAvatar(APP.xmpp.myJid(), email);
  3959. },
  3960. isVisible: function() {
  3961. return $('#settingsmenu').is(':visible');
  3962. },
  3963. setDisplayName: function(newDisplayName) {
  3964. var displayName = Settings.setDisplayName(newDisplayName);
  3965. $('#setDisplayName').get(0).value = displayName;
  3966. },
  3967. onDisplayNameChange: function(peerJid, newDisplayName) {
  3968. if(peerJid === 'localVideoContainer' ||
  3969. peerJid === APP.xmpp.myJid()) {
  3970. this.setDisplayName(newDisplayName);
  3971. }
  3972. }
  3973. };
  3974. module.exports = SettingsMenu;
  3975. },{"../../../../service/translation/languages":95,"../../avatar/Avatar":12,"../../util/UIUtil":29,"./../../../settings/Settings":37}],23:[function(require,module,exports){
  3976. var PanelToggler = require("../side_pannels/SidePanelToggler");
  3977. var buttonHandlers = {
  3978. "bottom_toolbar_contact_list": function () {
  3979. BottomToolbar.toggleContactList();
  3980. },
  3981. "bottom_toolbar_film_strip": function () {
  3982. BottomToolbar.toggleFilmStrip();
  3983. },
  3984. "bottom_toolbar_chat": function () {
  3985. BottomToolbar.toggleChat();
  3986. }
  3987. };
  3988. var BottomToolbar = (function (my) {
  3989. my.init = function () {
  3990. for(var k in buttonHandlers)
  3991. $("#" + k).click(buttonHandlers[k]);
  3992. };
  3993. my.toggleChat = function() {
  3994. PanelToggler.toggleChat();
  3995. };
  3996. my.toggleContactList = function() {
  3997. PanelToggler.toggleContactList();
  3998. };
  3999. my.toggleFilmStrip = function() {
  4000. var filmstrip = $("#remoteVideos");
  4001. filmstrip.toggleClass("hidden");
  4002. };
  4003. $(document).bind("remotevideo.resized", function (event, width, height) {
  4004. var bottom = (height - $('#bottomToolbar').outerHeight())/2 + 18;
  4005. $('#bottomToolbar').css({bottom: bottom + 'px'});
  4006. });
  4007. return my;
  4008. }(BottomToolbar || {}));
  4009. module.exports = BottomToolbar;
  4010. },{"../side_pannels/SidePanelToggler":16}],24:[function(require,module,exports){
  4011. /* global APP,$, buttonClick, config, lockRoom,
  4012. setSharedKey, Util */
  4013. var messageHandler = require("../util/MessageHandler");
  4014. var BottomToolbar = require("./BottomToolbar");
  4015. var Prezi = require("../prezi/Prezi");
  4016. var Etherpad = require("../etherpad/Etherpad");
  4017. var PanelToggler = require("../side_pannels/SidePanelToggler");
  4018. var Authentication = require("../authentication/Authentication");
  4019. var UIUtil = require("../util/UIUtil");
  4020. var AuthenticationEvents
  4021. = require("../../../service/authentication/AuthenticationEvents");
  4022. var roomUrl = null;
  4023. var sharedKey = '';
  4024. var UI = null;
  4025. var buttonHandlers =
  4026. {
  4027. "toolbar_button_mute": function () {
  4028. return APP.UI.toggleAudio();
  4029. },
  4030. "toolbar_button_camera": function () {
  4031. return APP.UI.toggleVideo();
  4032. },
  4033. /*"toolbar_button_authentication": function () {
  4034. return Toolbar.authenticateClicked();
  4035. },*/
  4036. "toolbar_button_record": function () {
  4037. return toggleRecording();
  4038. },
  4039. "toolbar_button_security": function () {
  4040. return Toolbar.openLockDialog();
  4041. },
  4042. "toolbar_button_link": function () {
  4043. return Toolbar.openLinkDialog();
  4044. },
  4045. "toolbar_button_chat": function () {
  4046. return BottomToolbar.toggleChat();
  4047. },
  4048. "toolbar_button_prezi": function () {
  4049. return Prezi.openPreziDialog();
  4050. },
  4051. "toolbar_button_etherpad": function () {
  4052. return Etherpad.toggleEtherpad(0);
  4053. },
  4054. "toolbar_button_desktopsharing": function () {
  4055. return APP.desktopsharing.toggleScreenSharing();
  4056. },
  4057. "toolbar_button_fullScreen": function()
  4058. {
  4059. UIUtil.buttonClick("#fullScreen", "icon-full-screen icon-exit-full-screen");
  4060. return Toolbar.toggleFullScreen();
  4061. },
  4062. "toolbar_button_sip": function () {
  4063. return callSipButtonClicked();
  4064. },
  4065. "toolbar_button_settings": function () {
  4066. PanelToggler.toggleSettingsMenu();
  4067. },
  4068. "toolbar_button_hangup": function () {
  4069. return hangup();
  4070. },
  4071. "toolbar_button_login": function () {
  4072. Toolbar.authenticateClicked();
  4073. },
  4074. "toolbar_button_logout": function () {
  4075. // Ask for confirmation
  4076. messageHandler.openTwoButtonDialog(
  4077. "dialog.logoutTitle",
  4078. null,
  4079. "dialog.logoutQuestion",
  4080. null,
  4081. false,
  4082. "dialog.Yes",
  4083. function (evt, yes) {
  4084. if (yes) {
  4085. APP.xmpp.logout(function (url) {
  4086. if (url) {
  4087. window.location.href = url;
  4088. } else {
  4089. hangup();
  4090. }
  4091. });
  4092. }
  4093. });
  4094. }
  4095. };
  4096. function hangup() {
  4097. APP.xmpp.disposeConference();
  4098. if(config.enableWelcomePage)
  4099. {
  4100. setTimeout(function()
  4101. {
  4102. window.localStorage.welcomePageDisabled = false;
  4103. window.location.pathname = "/";
  4104. }, 10000);
  4105. }
  4106. var title = APP.translation.generateTranslatonHTML(
  4107. "dialog.sessTerminated");
  4108. var msg = APP.translation.generateTranslatonHTML(
  4109. "dialog.hungUp");
  4110. var button = APP.translation.generateTranslatonHTML(
  4111. "dialog.joinAgain");
  4112. var buttons = {};
  4113. buttons.joinAgain = {title: button, value: true};
  4114. UI.messageHandler.openDialog(
  4115. title,
  4116. msg,
  4117. true,
  4118. buttons,
  4119. function(event, value, message, formVals)
  4120. {
  4121. window.location.reload();
  4122. return false;
  4123. }
  4124. );
  4125. }
  4126. /**
  4127. * Starts or stops the recording for the conference.
  4128. */
  4129. function toggleRecording() {
  4130. APP.xmpp.toggleRecording(function (callback) {
  4131. var msg = APP.translation.generateTranslatonHTML(
  4132. "dialog.recordingToken");
  4133. var token = APP.translation.translateString("dialog.token");
  4134. APP.UI.messageHandler.openTwoButtonDialog(null, null, null,
  4135. '<h2>' + msg + '</h2>' +
  4136. '<input id="recordingToken" type="text" ' +
  4137. ' data-i18n="[placeholder]dialog.token" ' +
  4138. 'placeholder="' + token + '" autofocus>',
  4139. false,
  4140. "dialog.Save",
  4141. function (e, v, m, f) {
  4142. if (v) {
  4143. var token = document.getElementById('recordingToken');
  4144. if (token.value) {
  4145. callback(UIUtil.escapeHtml(token.value));
  4146. }
  4147. }
  4148. },
  4149. function (event) {
  4150. document.getElementById('recordingToken').focus();
  4151. },
  4152. function () {
  4153. }
  4154. );
  4155. }, Toolbar.setRecordingButtonState, Toolbar.setRecordingButtonState);
  4156. }
  4157. /**
  4158. * Locks / unlocks the room.
  4159. */
  4160. function lockRoom(lock) {
  4161. var currentSharedKey = '';
  4162. if (lock)
  4163. currentSharedKey = sharedKey;
  4164. APP.xmpp.lockRoom(currentSharedKey, function (res) {
  4165. // password is required
  4166. if (sharedKey)
  4167. {
  4168. console.log('set room password');
  4169. Toolbar.lockLockButton();
  4170. }
  4171. else
  4172. {
  4173. console.log('removed room password');
  4174. Toolbar.unlockLockButton();
  4175. }
  4176. }, function (err) {
  4177. console.warn('setting password failed', err);
  4178. messageHandler.showError("dialog.lockTitle",
  4179. "dialog.lockMessage");
  4180. Toolbar.setSharedKey('');
  4181. }, function () {
  4182. console.warn('room passwords not supported');
  4183. messageHandler.showError("dialog.warning",
  4184. "dialog.passwordNotSupported");
  4185. Toolbar.setSharedKey('');
  4186. });
  4187. };
  4188. /**
  4189. * Invite participants to conference.
  4190. */
  4191. function inviteParticipants() {
  4192. if (roomUrl === null)
  4193. return;
  4194. var sharedKeyText = "";
  4195. if (sharedKey && sharedKey.length > 0) {
  4196. sharedKeyText =
  4197. APP.translation.translateString("email.sharedKey",
  4198. {sharedKey: sharedKey});
  4199. }
  4200. var conferenceName = roomUrl.substring(roomUrl.lastIndexOf('/') + 1);
  4201. var subject = APP.translation.translateString("email.subject",
  4202. {appName:interfaceConfig.APP_NAME, conferenceName: conferenceName});
  4203. var body = APP.translation.translateString("email.body",
  4204. {appName:interfaceConfig.APP_NAME, sharedKeyText: sharedKeyText,
  4205. roomUrl: roomUrl});
  4206. if (window.localStorage.displayname) {
  4207. body += "%0D%0A%0D%0A" + window.localStorage.displayname;
  4208. }
  4209. if (interfaceConfig.INVITATION_POWERED_BY) {
  4210. body += "%0D%0A%0D%0A--%0D%0Apowered by jitsi.org";
  4211. }
  4212. window.open("mailto:?subject=" + subject + "&body=" + body, '_blank');
  4213. }
  4214. function callSipButtonClicked()
  4215. {
  4216. var defaultNumber
  4217. = config.defaultSipNumber ? config.defaultSipNumber : '';
  4218. var sipMsg = APP.translation.generateTranslatonHTML(
  4219. "dialog.sipMsg");
  4220. messageHandler.openTwoButtonDialog(null, null, null,
  4221. '<h2>' + sipMsg + '</h2>' +
  4222. '<input id="sipNumber" type="text"' +
  4223. ' value="' + defaultNumber + '" autofocus>',
  4224. false,
  4225. "dialog.Dial",
  4226. function (e, v, m, f) {
  4227. if (v) {
  4228. var numberInput = document.getElementById('sipNumber');
  4229. if (numberInput.value) {
  4230. APP.xmpp.dial(numberInput.value, 'fromnumber',
  4231. UI.getRoomName(), sharedKey);
  4232. }
  4233. }
  4234. },
  4235. function (event) {
  4236. document.getElementById('sipNumber').focus();
  4237. }
  4238. );
  4239. }
  4240. var Toolbar = (function (my) {
  4241. my.init = function (ui) {
  4242. for(var k in buttonHandlers)
  4243. $("#" + k).click(buttonHandlers[k]);
  4244. UI = ui;
  4245. // Update login info
  4246. APP.xmpp.addListener(
  4247. AuthenticationEvents.IDENTITY_UPDATED,
  4248. function (authenticationEnabled, userIdentity) {
  4249. var loggedIn = false;
  4250. if (userIdentity) {
  4251. loggedIn = true;
  4252. }
  4253. //FIXME: XMPP authentication need improvements for "live" login
  4254. if (!APP.xmpp.isExternalAuthEnabled() && !loggedIn)
  4255. {
  4256. authenticationEnabled = false;
  4257. }
  4258. Toolbar.showAuthenticateButton(authenticationEnabled);
  4259. if (authenticationEnabled) {
  4260. Toolbar.setAuthenticatedIdentity(userIdentity);
  4261. Toolbar.showLoginButton(!loggedIn);
  4262. Toolbar.showLogoutButton(loggedIn);
  4263. }
  4264. }
  4265. );
  4266. },
  4267. /**
  4268. * Sets shared key
  4269. * @param sKey the shared key
  4270. */
  4271. my.setSharedKey = function (sKey) {
  4272. sharedKey = sKey;
  4273. };
  4274. my.authenticateClicked = function () {
  4275. Authentication.focusAuthenticationWindow();
  4276. // Get authentication URL
  4277. if (!APP.xmpp.getMUCJoined()) {
  4278. APP.xmpp.getLoginUrl(UI.getRoomName(), function (url) {
  4279. // If conference has not been started yet - redirect to login page
  4280. window.location.href = url;
  4281. });
  4282. } else {
  4283. APP.xmpp.getPopupLoginUrl(UI.getRoomName(), function (url) {
  4284. // Otherwise - open popup with authentication URL
  4285. var authenticationWindow = Authentication.createAuthenticationWindow(
  4286. function () {
  4287. // On popup closed - retry room allocation
  4288. APP.xmpp.allocateConferenceFocus(
  4289. APP.UI.getRoomName(),
  4290. function () { console.info("AUTH DONE"); }
  4291. );
  4292. }, url);
  4293. if (!authenticationWindow) {
  4294. messageHandler.openMessageDialog(
  4295. null, "dialog.popupError");
  4296. }
  4297. });
  4298. }
  4299. };
  4300. /**
  4301. * Updates the room invite url.
  4302. */
  4303. my.updateRoomUrl = function (newRoomUrl) {
  4304. roomUrl = newRoomUrl;
  4305. // If the invite dialog has been already opened we update the information.
  4306. var inviteLink = document.getElementById('inviteLinkRef');
  4307. if (inviteLink) {
  4308. inviteLink.value = roomUrl;
  4309. inviteLink.select();
  4310. document.getElementById('jqi_state0_buttonInvite').disabled = false;
  4311. }
  4312. };
  4313. /**
  4314. * Disables and enables some of the buttons.
  4315. */
  4316. my.setupButtonsFromConfig = function () {
  4317. if (config.disablePrezi)
  4318. {
  4319. $("#prezi_button").css({display: "none"});
  4320. }
  4321. };
  4322. /**
  4323. * Opens the lock room dialog.
  4324. */
  4325. my.openLockDialog = function () {
  4326. // Only the focus is able to set a shared key.
  4327. if (!APP.xmpp.isModerator()) {
  4328. if (sharedKey) {
  4329. messageHandler.openMessageDialog(null,
  4330. "dialog.passwordError");
  4331. } else {
  4332. messageHandler.openMessageDialog(null, "dialog.passwordError2");
  4333. }
  4334. } else {
  4335. if (sharedKey) {
  4336. messageHandler.openTwoButtonDialog(null, null,
  4337. "dialog.passwordCheck",
  4338. null,
  4339. false,
  4340. "dialog.Remove",
  4341. function (e, v) {
  4342. if (v) {
  4343. Toolbar.setSharedKey('');
  4344. lockRoom(false);
  4345. }
  4346. });
  4347. } else {
  4348. var msg = APP.translation.generateTranslatonHTML(
  4349. "dialog.passwordMsg");
  4350. var yourPassword = APP.translation.translateString(
  4351. "dialog.yourPassword");
  4352. messageHandler.openTwoButtonDialog(null, null, null,
  4353. '<h2>' + msg + '</h2>' +
  4354. '<input id="lockKey" type="text"' +
  4355. ' data-i18n="[placeholder]dialog.yourPassword" ' +
  4356. 'placeholder="' + yourPassword + '" autofocus>',
  4357. false,
  4358. "dialog.Save",
  4359. function (e, v) {
  4360. if (v) {
  4361. var lockKey = document.getElementById('lockKey');
  4362. if (lockKey.value) {
  4363. Toolbar.setSharedKey(UIUtil.escapeHtml(lockKey.value));
  4364. lockRoom(true);
  4365. }
  4366. }
  4367. },
  4368. function () {
  4369. document.getElementById('lockKey').focus();
  4370. }
  4371. );
  4372. }
  4373. }
  4374. };
  4375. /**
  4376. * Opens the invite link dialog.
  4377. */
  4378. my.openLinkDialog = function () {
  4379. var inviteAttreibutes;
  4380. if (roomUrl === null) {
  4381. inviteAttreibutes = 'data-i18n="[value]roomUrlDefaultMsg" value="' +
  4382. APP.translation.translateString("roomUrlDefaultMsg") + '"';
  4383. } else {
  4384. inviteAttreibutes = "value=\"" + encodeURI(roomUrl) + "\"";
  4385. }
  4386. messageHandler.openTwoButtonDialog("dialog.shareLink",
  4387. null, null,
  4388. '<input id="inviteLinkRef" type="text" ' +
  4389. inviteAttreibutes + ' onclick="this.select();" readonly>',
  4390. false,
  4391. "dialog.Invite",
  4392. function (e, v) {
  4393. if (v) {
  4394. if (roomUrl) {
  4395. inviteParticipants();
  4396. }
  4397. }
  4398. },
  4399. function () {
  4400. if (roomUrl) {
  4401. document.getElementById('inviteLinkRef').select();
  4402. } else {
  4403. document.getElementById('jqi_state0_buttonInvite')
  4404. .disabled = true;
  4405. }
  4406. }
  4407. );
  4408. };
  4409. /**
  4410. * Opens the settings dialog.
  4411. */
  4412. my.openSettingsDialog = function () {
  4413. var settings1 = APP.translation.generateTranslatonHTML(
  4414. "dialog.settings1");
  4415. var settings2 = APP.translation.generateTranslatonHTML(
  4416. "dialog.settings2");
  4417. var settings3 = APP.translation.generateTranslatonHTML(
  4418. "dialog.settings3");
  4419. var yourPassword = APP.translation.translateString(
  4420. "dialog.yourPassword");
  4421. messageHandler.openTwoButtonDialog(null,
  4422. '<h2>' + settings1 + '</h2>' +
  4423. '<input type="checkbox" id="initMuted">' +
  4424. settings2 + '<br/>' +
  4425. '<input type="checkbox" id="requireNicknames">' +
  4426. settings3 +
  4427. '<input id="lockKey" type="text" placeholder="' + yourPassword +
  4428. '" data-i18n="[placeholder]dialog.yourPassword" autofocus>',
  4429. null,
  4430. null,
  4431. false,
  4432. "dialog.Save",
  4433. function () {
  4434. document.getElementById('lockKey').focus();
  4435. },
  4436. function (e, v) {
  4437. if (v) {
  4438. if ($('#initMuted').is(":checked")) {
  4439. // it is checked
  4440. }
  4441. if ($('#requireNicknames').is(":checked")) {
  4442. // it is checked
  4443. }
  4444. /*
  4445. var lockKey = document.getElementById('lockKey');
  4446. if (lockKey.value) {
  4447. setSharedKey(lockKey.value);
  4448. lockRoom(true);
  4449. }
  4450. */
  4451. }
  4452. }
  4453. );
  4454. };
  4455. /**
  4456. * Toggles the application in and out of full screen mode
  4457. * (a.k.a. presentation mode in Chrome).
  4458. */
  4459. my.toggleFullScreen = function () {
  4460. var fsElement = document.documentElement;
  4461. if (!document.mozFullScreen && !document.webkitIsFullScreen) {
  4462. //Enter Full Screen
  4463. if (fsElement.mozRequestFullScreen) {
  4464. fsElement.mozRequestFullScreen();
  4465. }
  4466. else {
  4467. fsElement.webkitRequestFullScreen(Element.ALLOW_KEYBOARD_INPUT);
  4468. }
  4469. } else {
  4470. //Exit Full Screen
  4471. if (document.mozCancelFullScreen) {
  4472. document.mozCancelFullScreen();
  4473. } else {
  4474. document.webkitCancelFullScreen();
  4475. }
  4476. }
  4477. };
  4478. /**
  4479. * Unlocks the lock button state.
  4480. */
  4481. my.unlockLockButton = function () {
  4482. if ($("#lockIcon").hasClass("icon-security-locked"))
  4483. UIUtil.buttonClick("#lockIcon", "icon-security icon-security-locked");
  4484. };
  4485. /**
  4486. * Updates the lock button state to locked.
  4487. */
  4488. my.lockLockButton = function () {
  4489. if ($("#lockIcon").hasClass("icon-security"))
  4490. UIUtil.buttonClick("#lockIcon", "icon-security icon-security-locked");
  4491. };
  4492. /**
  4493. * Shows or hides authentication button
  4494. * @param show <tt>true</tt> to show or <tt>false</tt> to hide
  4495. */
  4496. my.showAuthenticateButton = function (show) {
  4497. if (show) {
  4498. $('#authentication').css({display: "inline"});
  4499. }
  4500. else {
  4501. $('#authentication').css({display: "none"});
  4502. }
  4503. };
  4504. // Shows or hides the 'recording' button.
  4505. my.showRecordingButton = function (show) {
  4506. if (!config.enableRecording) {
  4507. return;
  4508. }
  4509. if (show) {
  4510. $('#recording').css({display: "inline"});
  4511. }
  4512. else {
  4513. $('#recording').css({display: "none"});
  4514. }
  4515. };
  4516. // Sets the state of the recording button
  4517. my.setRecordingButtonState = function (isRecording) {
  4518. if (isRecording) {
  4519. $('#recordButton').removeClass("icon-recEnable");
  4520. $('#recordButton').addClass("icon-recEnable active");
  4521. } else {
  4522. $('#recordButton').removeClass("icon-recEnable active");
  4523. $('#recordButton').addClass("icon-recEnable");
  4524. }
  4525. };
  4526. // Shows or hides SIP calls button
  4527. my.showSipCallButton = function (show) {
  4528. if (APP.xmpp.isSipGatewayEnabled() && show) {
  4529. $('#sipCallButton').css({display: "inline-block"});
  4530. } else {
  4531. $('#sipCallButton').css({display: "none"});
  4532. }
  4533. };
  4534. /**
  4535. * Displays user authenticated identity name(login).
  4536. * @param authIdentity identity name to be displayed.
  4537. */
  4538. my.setAuthenticatedIdentity = function (authIdentity) {
  4539. if (authIdentity) {
  4540. $('#toolbar_auth_identity').css({display: "list-item"});
  4541. $('#toolbar_auth_identity').text(authIdentity);
  4542. } else {
  4543. $('#toolbar_auth_identity').css({display: "none"});
  4544. }
  4545. };
  4546. /**
  4547. * Shows/hides login button.
  4548. * @param show <tt>true</tt> to show
  4549. */
  4550. my.showLoginButton = function (show) {
  4551. if (show) {
  4552. $('#toolbar_button_login').css({display: "list-item"});
  4553. } else {
  4554. $('#toolbar_button_login').css({display: "none"});
  4555. }
  4556. };
  4557. /**
  4558. * Shows/hides logout button.
  4559. * @param show <tt>true</tt> to show
  4560. */
  4561. my.showLogoutButton = function (show) {
  4562. if (show) {
  4563. $('#toolbar_button_logout').css({display: "list-item"});
  4564. } else {
  4565. $('#toolbar_button_logout').css({display: "none"});
  4566. }
  4567. };
  4568. /**
  4569. * Sets the state of the button. The button has blue glow if desktop
  4570. * streaming is active.
  4571. * @param active the state of the desktop streaming.
  4572. */
  4573. my.changeDesktopSharingButtonState = function (active) {
  4574. var button = $("#desktopsharing > a");
  4575. if (active)
  4576. {
  4577. button.addClass("glow");
  4578. }
  4579. else
  4580. {
  4581. button.removeClass("glow");
  4582. }
  4583. };
  4584. return my;
  4585. }(Toolbar || {}));
  4586. module.exports = Toolbar;
  4587. },{"../../../service/authentication/AuthenticationEvents":92,"../authentication/Authentication":11,"../etherpad/Etherpad":13,"../prezi/Prezi":14,"../side_pannels/SidePanelToggler":16,"../util/MessageHandler":27,"../util/UIUtil":29,"./BottomToolbar":23}],25:[function(require,module,exports){
  4588. /* global $, interfaceConfig, Moderator, DesktopStreaming.showDesktopSharingButton */
  4589. var toolbarTimeoutObject,
  4590. toolbarTimeout = interfaceConfig.INITIAL_TOOLBAR_TIMEOUT;
  4591. function showDesktopSharingButton() {
  4592. if (APP.desktopsharing.isDesktopSharingEnabled()) {
  4593. $('#desktopsharing').css({display: "inline"});
  4594. } else {
  4595. $('#desktopsharing').css({display: "none"});
  4596. }
  4597. }
  4598. /**
  4599. * Hides the toolbar.
  4600. */
  4601. function hideToolbar() {
  4602. var header = $("#header"),
  4603. bottomToolbar = $("#bottomToolbar");
  4604. var isToolbarHover = false;
  4605. header.find('*').each(function () {
  4606. var id = $(this).attr('id');
  4607. if ($("#" + id + ":hover").length > 0) {
  4608. isToolbarHover = true;
  4609. }
  4610. });
  4611. if ($("#bottomToolbar:hover").length > 0) {
  4612. isToolbarHover = true;
  4613. }
  4614. clearTimeout(toolbarTimeoutObject);
  4615. toolbarTimeoutObject = null;
  4616. if (!isToolbarHover) {
  4617. header.hide("slide", { direction: "up", duration: 300});
  4618. $('#subject').animate({top: "-=40"}, 300);
  4619. if ($("#remoteVideos").hasClass("hidden")) {
  4620. bottomToolbar.hide(
  4621. "slide", {direction: "right", duration: 300});
  4622. }
  4623. }
  4624. else {
  4625. toolbarTimeoutObject = setTimeout(hideToolbar, toolbarTimeout);
  4626. }
  4627. }
  4628. var ToolbarToggler = {
  4629. /**
  4630. * Shows the main toolbar.
  4631. */
  4632. showToolbar: function () {
  4633. var header = $("#header"),
  4634. bottomToolbar = $("#bottomToolbar");
  4635. if (!header.is(':visible') || !bottomToolbar.is(":visible")) {
  4636. header.show("slide", { direction: "up", duration: 300});
  4637. $('#subject').animate({top: "+=40"}, 300);
  4638. if (!bottomToolbar.is(":visible")) {
  4639. bottomToolbar.show(
  4640. "slide", {direction: "right", duration: 300});
  4641. }
  4642. if (toolbarTimeoutObject) {
  4643. clearTimeout(toolbarTimeoutObject);
  4644. toolbarTimeoutObject = null;
  4645. }
  4646. toolbarTimeoutObject = setTimeout(hideToolbar, toolbarTimeout);
  4647. toolbarTimeout = interfaceConfig.TOOLBAR_TIMEOUT;
  4648. }
  4649. if (APP.xmpp.isModerator())
  4650. {
  4651. // TODO: Enable settings functionality.
  4652. // Need to uncomment the settings button in index.html.
  4653. // $('#settingsButton').css({visibility:"visible"});
  4654. }
  4655. // Show/hide desktop sharing button
  4656. showDesktopSharingButton();
  4657. },
  4658. /**
  4659. * Docks/undocks the toolbar.
  4660. *
  4661. * @param isDock indicates what operation to perform
  4662. */
  4663. dockToolbar: function (isDock) {
  4664. if (isDock) {
  4665. // First make sure the toolbar is shown.
  4666. if (!$('#header').is(':visible')) {
  4667. this.showToolbar();
  4668. }
  4669. // Then clear the time out, to dock the toolbar.
  4670. if (toolbarTimeoutObject) {
  4671. clearTimeout(toolbarTimeoutObject);
  4672. toolbarTimeoutObject = null;
  4673. }
  4674. }
  4675. else {
  4676. if (!$('#header').is(':visible')) {
  4677. this.showToolbar();
  4678. }
  4679. else {
  4680. toolbarTimeoutObject = setTimeout(hideToolbar, toolbarTimeout);
  4681. }
  4682. }
  4683. },
  4684. showDesktopSharingButton: showDesktopSharingButton
  4685. };
  4686. module.exports = ToolbarToggler;
  4687. },{}],26:[function(require,module,exports){
  4688. var JitsiPopover = (function () {
  4689. /**
  4690. * Constructs new JitsiPopover and attaches it to the element
  4691. * @param element jquery selector
  4692. * @param options the options for the popover.
  4693. * @constructor
  4694. */
  4695. function JitsiPopover(element, options)
  4696. {
  4697. this.options = {
  4698. skin: "white",
  4699. content: ""
  4700. };
  4701. if(options)
  4702. {
  4703. if(options.skin)
  4704. this.options.skin = options.skin;
  4705. if(options.content)
  4706. this.options.content = options.content;
  4707. }
  4708. this.elementIsHovered = false;
  4709. this.popoverIsHovered = false;
  4710. this.popoverShown = false;
  4711. element.data("jitsi_popover", this);
  4712. this.element = element;
  4713. this.template = ' <div class="jitsipopover ' + this.options.skin +
  4714. '"><div class="arrow"></div><div class="jitsipopover-content"></div>' +
  4715. '<div class="jitsiPopupmenuPadding"></div></div>';
  4716. var self = this;
  4717. this.element.on("mouseenter", function () {
  4718. self.elementIsHovered = true;
  4719. self.show();
  4720. }).on("mouseleave", function () {
  4721. self.elementIsHovered = false;
  4722. setTimeout(function () {
  4723. self.hide();
  4724. }, 10);
  4725. });
  4726. }
  4727. /**
  4728. * Shows the popover
  4729. */
  4730. JitsiPopover.prototype.show = function () {
  4731. this.createPopover();
  4732. this.popoverShown = true;
  4733. };
  4734. /**
  4735. * Hides the popover
  4736. */
  4737. JitsiPopover.prototype.hide = function () {
  4738. if(!this.elementIsHovered && !this.popoverIsHovered && this.popoverShown)
  4739. {
  4740. this.forceHide();
  4741. }
  4742. };
  4743. /**
  4744. * Hides the popover
  4745. */
  4746. JitsiPopover.prototype.forceHide = function () {
  4747. $(".jitsipopover").remove();
  4748. this.popoverShown = false;
  4749. };
  4750. /**
  4751. * Creates the popover html
  4752. */
  4753. JitsiPopover.prototype.createPopover = function () {
  4754. $("body").append(this.template);
  4755. $(".jitsipopover > .jitsipopover-content").html(this.options.content);
  4756. var self = this;
  4757. $(".jitsipopover").on("mouseenter", function () {
  4758. self.popoverIsHovered = true;
  4759. }).on("mouseleave", function () {
  4760. self.popoverIsHovered = false;
  4761. self.hide();
  4762. });
  4763. this.refreshPosition();
  4764. };
  4765. /**
  4766. * Refreshes the position of the popover
  4767. */
  4768. JitsiPopover.prototype.refreshPosition = function () {
  4769. $(".jitsipopover").position({
  4770. my: "bottom",
  4771. at: "top",
  4772. collision: "fit",
  4773. of: this.element,
  4774. using: function (position, elements) {
  4775. var calcLeft = elements.target.left - elements.element.left + elements.target.width/2;
  4776. $(".jitsipopover").css({top: position.top, left: position.left, display: "table"});
  4777. $(".jitsipopover > .arrow").css({left: calcLeft});
  4778. $(".jitsipopover > .jitsiPopupmenuPadding").css({left: calcLeft - 50});
  4779. }
  4780. });
  4781. };
  4782. /**
  4783. * Updates the content of popover.
  4784. * @param content new content
  4785. */
  4786. JitsiPopover.prototype.updateContent = function (content) {
  4787. this.options.content = content;
  4788. if(!this.popoverShown)
  4789. return;
  4790. $(".jitsipopover").remove();
  4791. this.createPopover();
  4792. };
  4793. return JitsiPopover;
  4794. })();
  4795. module.exports = JitsiPopover;
  4796. },{}],27:[function(require,module,exports){
  4797. /* global $, jQuery */
  4798. var messageHandler = (function(my) {
  4799. /**
  4800. * Shows a message to the user.
  4801. *
  4802. * @param titleString the title of the message
  4803. * @param messageString the text of the message
  4804. */
  4805. my.openMessageDialog = function(titleKey, messageKey) {
  4806. var title = null;
  4807. if(titleKey)
  4808. {
  4809. title = APP.translation.generateTranslatonHTML(titleKey);
  4810. }
  4811. var message = APP.translation.generateTranslatonHTML(messageKey);
  4812. $.prompt(message,
  4813. {
  4814. title: title,
  4815. persistent: false
  4816. }
  4817. );
  4818. };
  4819. /**
  4820. * Shows a message to the user with two buttons: first is given as a parameter and the second is Cancel.
  4821. *
  4822. * @param titleString the title of the message
  4823. * @param msgString the text of the message
  4824. * @param persistent boolean value which determines whether the message is persistent or not
  4825. * @param leftButton the fist button's text
  4826. * @param submitFunction function to be called on submit
  4827. * @param loadedFunction function to be called after the prompt is fully loaded
  4828. * @param closeFunction function to be called after the prompt is closed
  4829. */
  4830. my.openTwoButtonDialog = function(titleKey, titleString, msgKey, msgString,
  4831. persistent, leftButtonKey, submitFunction, loadedFunction,
  4832. closeFunction)
  4833. {
  4834. var leftButton = APP.translation.generateTranslatonHTML(leftButtonKey);
  4835. var buttons = {};
  4836. buttons.button1 = {title: leftButton, value: true};
  4837. var cancelButton = APP.translation.generateTranslatonHTML("dialog.Cancel");
  4838. buttons.button2 = {title: cancelButton, value: false};
  4839. var message = msgString, title = titleString;
  4840. if(titleKey)
  4841. {
  4842. title = APP.translation.generateTranslatonHTML(titleKey);
  4843. }
  4844. if(msgKey) {
  4845. message = APP.translation.generateTranslatonHTML(msgKey);
  4846. }
  4847. $.prompt(message, {
  4848. title: title,
  4849. persistent: false,
  4850. buttons: buttons,
  4851. defaultButton: 1,
  4852. loaded: loadedFunction,
  4853. submit: submitFunction,
  4854. close: closeFunction
  4855. });
  4856. };
  4857. /**
  4858. * Shows a message to the user with two buttons: first is given as a parameter and the second is Cancel.
  4859. *
  4860. * @param titleString the title of the message
  4861. * @param msgString the text of the message
  4862. * @param persistent boolean value which determines whether the message is persistent or not
  4863. * @param buttons object with the buttons. The keys must be the name of the button and value is the value
  4864. * that will be passed to submitFunction
  4865. * @param submitFunction function to be called on submit
  4866. * @param loadedFunction function to be called after the prompt is fully loaded
  4867. */
  4868. my.openDialog = function (titleString, msgString, persistent, buttons,
  4869. submitFunction, loadedFunction) {
  4870. var args = {
  4871. title: titleString,
  4872. persistent: persistent,
  4873. buttons: buttons,
  4874. defaultButton: 1,
  4875. loaded: loadedFunction,
  4876. submit: submitFunction
  4877. };
  4878. if (persistent) {
  4879. args.closeText = '';
  4880. }
  4881. return $.prompt(msgString, args);
  4882. };
  4883. /**
  4884. * Closes currently opened dialog.
  4885. */
  4886. my.closeDialog = function () {
  4887. $.prompt.close();
  4888. };
  4889. /**
  4890. * Shows a dialog with different states to the user.
  4891. *
  4892. * @param statesObject object containing all the states of the dialog
  4893. * @param loadedFunction function to be called after the prompt is fully loaded
  4894. * @param stateChangedFunction function to be called when the state of the dialog is changed
  4895. */
  4896. my.openDialogWithStates = function(statesObject, loadedFunction, stateChangedFunction) {
  4897. var myPrompt = $.prompt(statesObject);
  4898. myPrompt.on('impromptu:loaded', loadedFunction);
  4899. myPrompt.on('impromptu:statechanged', stateChangedFunction);
  4900. };
  4901. /**
  4902. * Opens new popup window for given <tt>url</tt> centered over current
  4903. * window.
  4904. *
  4905. * @param url the URL to be displayed in the popup window
  4906. * @param w the width of the popup window
  4907. * @param h the height of the popup window
  4908. * @param onPopupClosed optional callback function called when popup window
  4909. * has been closed.
  4910. *
  4911. * @returns popup window object if opened successfully or undefined
  4912. * in case we failed to open it(popup blocked)
  4913. */
  4914. my.openCenteredPopup = function (url, w, h, onPopupClosed) {
  4915. var l = window.screenX + (window.innerWidth / 2) - (w / 2);
  4916. var t = window.screenY + (window.innerHeight / 2) - (h / 2);
  4917. var popup = window.open(
  4918. url, '_blank',
  4919. 'top=' + t + ', left=' + l + ', width=' + w + ', height=' + h + '');
  4920. if (popup && onPopupClosed) {
  4921. var pollTimer = window.setInterval(function () {
  4922. if (popup.closed !== false) {
  4923. window.clearInterval(pollTimer);
  4924. onPopupClosed();
  4925. }
  4926. }, 200);
  4927. }
  4928. return popup;
  4929. };
  4930. /**
  4931. * Shows a dialog prompting the user to send an error report.
  4932. *
  4933. * @param titleString the title of the message
  4934. * @param msgString the text of the message
  4935. * @param error the error that is being reported
  4936. */
  4937. my.openReportDialog = function(titleKey, msgKey, error) {
  4938. my.openMessageDialog(titleKey, msgKey);
  4939. console.log(error);
  4940. //FIXME send the error to the server
  4941. };
  4942. /**
  4943. * Shows an error dialog to the user.
  4944. * @param title the title of the message
  4945. * @param message the text of the messafe
  4946. */
  4947. my.showError = function(titleKey, msgKey) {
  4948. if(!titleKey) {
  4949. titleKey = "dialog.oops";
  4950. }
  4951. if(!msgKey)
  4952. {
  4953. msgKey = "dialog.defaultError";
  4954. }
  4955. messageHandler.openMessageDialog(titleKey, msgKey);
  4956. };
  4957. my.notify = function(displayName, displayNameKey,
  4958. cls, messageKey, messageArguments) {
  4959. var displayNameSpan = '<span class="nickname" ';
  4960. if(displayName)
  4961. {
  4962. displayNameSpan += ">" + displayName;
  4963. }
  4964. else
  4965. {
  4966. displayNameSpan += "data-i18n='" + displayNameKey +
  4967. "'>" + APP.translation.translateString(displayNameKey);
  4968. }
  4969. displayNameSpan += "</span>";
  4970. toastr.info(
  4971. displayNameSpan + '<br>' +
  4972. '<span class=' + cls + ' data-i18n="' + messageKey + '"' +
  4973. (messageArguments?
  4974. " data-i18n-options='" + JSON.stringify(messageArguments) + "'"
  4975. : "") + ">" +
  4976. APP.translation.translateString(messageKey,
  4977. messageArguments) +
  4978. '</span>');
  4979. };
  4980. return my;
  4981. }(messageHandler || {}));
  4982. module.exports = messageHandler;
  4983. },{}],28:[function(require,module,exports){
  4984. var UIEvents = require("../../../service/UI/UIEvents");
  4985. var nickname = null;
  4986. var eventEmitter = null;
  4987. var NickanameHandler = {
  4988. init: function (emitter) {
  4989. eventEmitter = emitter;
  4990. var storedDisplayName = window.localStorage.displayname;
  4991. if (storedDisplayName) {
  4992. nickname = storedDisplayName;
  4993. }
  4994. },
  4995. setNickname: function (newNickname) {
  4996. if (!newNickname || nickname === newNickname)
  4997. return;
  4998. nickname = newNickname;
  4999. window.localStorage.displayname = nickname;
  5000. eventEmitter.emit(UIEvents.NICKNAME_CHANGED, newNickname);
  5001. },
  5002. getNickname: function () {
  5003. return nickname;
  5004. },
  5005. addListener: function (type, listener) {
  5006. eventEmitter.on(type, listener);
  5007. }
  5008. };
  5009. module.exports = NickanameHandler;
  5010. },{"../../../service/UI/UIEvents":91}],29:[function(require,module,exports){
  5011. /**
  5012. * Created by hristo on 12/22/14.
  5013. */
  5014. module.exports = {
  5015. /**
  5016. * Returns the available video width.
  5017. */
  5018. getAvailableVideoWidth: function () {
  5019. var PanelToggler = require("../side_pannels/SidePanelToggler");
  5020. var rightPanelWidth
  5021. = PanelToggler.isVisible() ? PanelToggler.getPanelSize()[0] : 0;
  5022. return window.innerWidth - rightPanelWidth;
  5023. },
  5024. /**
  5025. * Changes the style class of the element given by id.
  5026. */
  5027. buttonClick: function(id, classname) {
  5028. $(id).toggleClass(classname); // add the class to the clicked element
  5029. },
  5030. /**
  5031. * Returns the text width for the given element.
  5032. *
  5033. * @param el the element
  5034. */
  5035. getTextWidth: function (el) {
  5036. return (el.clientWidth + 1);
  5037. },
  5038. /**
  5039. * Returns the text height for the given element.
  5040. *
  5041. * @param el the element
  5042. */
  5043. getTextHeight: function (el) {
  5044. return (el.clientHeight + 1);
  5045. },
  5046. /**
  5047. * Plays the sound given by id.
  5048. *
  5049. * @param id the identifier of the audio element.
  5050. */
  5051. playSoundNotification: function (id) {
  5052. document.getElementById(id).play();
  5053. },
  5054. /**
  5055. * Escapes the given text.
  5056. */
  5057. escapeHtml: function (unsafeText) {
  5058. return $('<div/>').text(unsafeText).html();
  5059. },
  5060. imageToGrayScale: function (canvas) {
  5061. var context = canvas.getContext('2d');
  5062. var imgData = context.getImageData(0, 0, canvas.width, canvas.height);
  5063. var pixels = imgData.data;
  5064. for (var i = 0, n = pixels.length; i < n; i += 4) {
  5065. var grayscale
  5066. = pixels[i] * .3 + pixels[i+1] * .59 + pixels[i+2] * .11;
  5067. pixels[i ] = grayscale; // red
  5068. pixels[i+1] = grayscale; // green
  5069. pixels[i+2] = grayscale; // blue
  5070. // pixels[i+3] is alpha
  5071. }
  5072. // redraw the image in black & white
  5073. context.putImageData(imgData, 0, 0);
  5074. },
  5075. setTooltip: function (element, key, position) {
  5076. element.setAttribute("data-i18n", "[data-content]" + key);
  5077. element.setAttribute("data-toggle", "popover");
  5078. element.setAttribute("data-placement", position);
  5079. element.setAttribute("data-html", true);
  5080. element.setAttribute("data-container", "body");
  5081. }
  5082. };
  5083. },{"../side_pannels/SidePanelToggler":16}],30:[function(require,module,exports){
  5084. var JitsiPopover = require("../util/JitsiPopover");
  5085. /**
  5086. * Constructs new connection indicator.
  5087. * @param videoContainer the video container associated with the indicator.
  5088. * @constructor
  5089. */
  5090. function ConnectionIndicator(videoContainer, jid, VideoLayout)
  5091. {
  5092. this.videoContainer = videoContainer;
  5093. this.bandwidth = null;
  5094. this.packetLoss = null;
  5095. this.bitrate = null;
  5096. this.showMoreValue = false;
  5097. this.resolution = null;
  5098. this.transport = [];
  5099. this.popover = null;
  5100. this.jid = jid;
  5101. this.create();
  5102. this.videoLayout = VideoLayout;
  5103. }
  5104. /**
  5105. * Values for the connection quality
  5106. * @type {{98: string,
  5107. * 81: string,
  5108. * 64: string,
  5109. * 47: string,
  5110. * 30: string,
  5111. * 0: string}}
  5112. */
  5113. ConnectionIndicator.connectionQualityValues = {
  5114. 98: "18px", //full
  5115. 81: "15px",//4 bars
  5116. 64: "11px",//3 bars
  5117. 47: "7px",//2 bars
  5118. 30: "3px",//1 bar
  5119. 0: "0px"//empty
  5120. };
  5121. ConnectionIndicator.getIP = function(value)
  5122. {
  5123. return value.substring(0, value.lastIndexOf(":"));
  5124. };
  5125. ConnectionIndicator.getPort = function(value)
  5126. {
  5127. return value.substring(value.lastIndexOf(":") + 1, value.length);
  5128. };
  5129. ConnectionIndicator.getStringFromArray = function (array) {
  5130. var res = "";
  5131. for(var i = 0; i < array.length; i++)
  5132. {
  5133. res += (i === 0? "" : ", ") + array[i];
  5134. }
  5135. return res;
  5136. };
  5137. /**
  5138. * Generates the html content.
  5139. * @returns {string} the html content.
  5140. */
  5141. ConnectionIndicator.prototype.generateText = function () {
  5142. var downloadBitrate, uploadBitrate, packetLoss, resolution, i;
  5143. var translate = APP.translation.translateString;
  5144. if(this.bitrate === null)
  5145. {
  5146. downloadBitrate = "N/A";
  5147. uploadBitrate = "N/A";
  5148. }
  5149. else
  5150. {
  5151. downloadBitrate =
  5152. this.bitrate.download? this.bitrate.download + " Kbps" : "N/A";
  5153. uploadBitrate =
  5154. this.bitrate.upload? this.bitrate.upload + " Kbps" : "N/A";
  5155. }
  5156. if(this.packetLoss === null)
  5157. {
  5158. packetLoss = "N/A";
  5159. }
  5160. else
  5161. {
  5162. packetLoss = "<span class='jitsipopover_green'>&darr;</span>" +
  5163. (this.packetLoss.download !== null? this.packetLoss.download : "N/A") +
  5164. "% <span class='jitsipopover_orange'>&uarr;</span>" +
  5165. (this.packetLoss.upload !== null? this.packetLoss.upload : "N/A") + "%";
  5166. }
  5167. var resolutionValue = null;
  5168. if(this.resolution && this.jid != null)
  5169. {
  5170. var keys = Object.keys(this.resolution);
  5171. if(keys.length == 1)
  5172. {
  5173. for(var ssrc in this.resolution)
  5174. {
  5175. resolutionValue = this.resolution[ssrc];
  5176. }
  5177. }
  5178. else if(keys.length > 1)
  5179. {
  5180. var displayedSsrc = APP.simulcast.getReceivingSSRC(this.jid);
  5181. resolutionValue = this.resolution[displayedSsrc];
  5182. }
  5183. }
  5184. if(this.jid === null)
  5185. {
  5186. resolution = "";
  5187. if(this.resolution === null || !Object.keys(this.resolution) ||
  5188. Object.keys(this.resolution).length === 0)
  5189. {
  5190. resolution = "N/A";
  5191. }
  5192. else
  5193. for(i in this.resolution)
  5194. {
  5195. resolutionValue = this.resolution[i];
  5196. if(resolutionValue)
  5197. {
  5198. if(resolutionValue.height &&
  5199. resolutionValue.width)
  5200. {
  5201. resolution += (resolution === ""? "" : ", ") +
  5202. resolutionValue.width + "x" +
  5203. resolutionValue.height;
  5204. }
  5205. }
  5206. }
  5207. }
  5208. else if(!resolutionValue ||
  5209. !resolutionValue.height ||
  5210. !resolutionValue.width)
  5211. {
  5212. resolution = "N/A";
  5213. }
  5214. else
  5215. {
  5216. resolution = resolutionValue.width + "x" + resolutionValue.height;
  5217. }
  5218. var result = "<table style='width:100%'>" +
  5219. "<tr>" +
  5220. "<td><span class='jitsipopover_blue' data-i18n='connectionindicator.bitrate'>" +
  5221. translate("connectionindicator.bitrate") + "</span></td>" +
  5222. "<td><span class='jitsipopover_green'>&darr;</span>" +
  5223. downloadBitrate + " <span class='jitsipopover_orange'>&uarr;</span>" +
  5224. uploadBitrate + "</td>" +
  5225. "</tr><tr>" +
  5226. "<td><span class='jitsipopover_blue' data-i18n='connectionindicator.packetloss'>" +
  5227. translate("connectionindicator.packetloss") + "</span></td>" +
  5228. "<td>" + packetLoss + "</td>" +
  5229. "</tr><tr>" +
  5230. "<td><span class='jitsipopover_blue' data-i18n='connectionindicator.resolution'>" +
  5231. translate("connectionindicator.resolution") + "</span></td>" +
  5232. "<td>" + resolution + "</td></tr></table>";
  5233. if(this.videoContainer.id == "localVideoContainer") {
  5234. result += "<div class=\"jitsipopover_showmore\" " +
  5235. "onclick = \"APP.UI.connectionIndicatorShowMore('" +
  5236. this.videoContainer.id + "')\" data-i18n='connectionindicator." +
  5237. (this.showMoreValue ? "less" : "more") + "'>" +
  5238. translate("connectionindicator." + (this.showMoreValue ? "less" : "more")) +
  5239. "</div><br />";
  5240. }
  5241. if(this.showMoreValue)
  5242. {
  5243. var downloadBandwidth, uploadBandwidth, transport;
  5244. if(this.bandwidth === null)
  5245. {
  5246. downloadBandwidth = "N/A";
  5247. uploadBandwidth = "N/A";
  5248. }
  5249. else
  5250. {
  5251. downloadBandwidth = this.bandwidth.download?
  5252. this.bandwidth.download + " Kbps" :
  5253. "N/A";
  5254. uploadBandwidth = this.bandwidth.upload?
  5255. this.bandwidth.upload + " Kbps" :
  5256. "N/A";
  5257. }
  5258. if(!this.transport || this.transport.length === 0)
  5259. {
  5260. transport = "<tr>" +
  5261. "<td><span class='jitsipopover_blue' " +
  5262. "data-i18n='connectionindicator.address'>" +
  5263. translate("connectionindicator.address") + "</span></td>" +
  5264. "<td> N/A</td></tr>";
  5265. }
  5266. else
  5267. {
  5268. var data = {remoteIP: [], localIP:[], remotePort:[], localPort:[]};
  5269. for(i = 0; i < this.transport.length; i++)
  5270. {
  5271. var ip = ConnectionIndicator.getIP(this.transport[i].ip);
  5272. var port = ConnectionIndicator.getPort(this.transport[i].ip);
  5273. var localIP =
  5274. ConnectionIndicator.getIP(this.transport[i].localip);
  5275. var localPort =
  5276. ConnectionIndicator.getPort(this.transport[i].localip);
  5277. if(data.remoteIP.indexOf(ip) == -1)
  5278. {
  5279. data.remoteIP.push(ip);
  5280. }
  5281. if(data.remotePort.indexOf(port) == -1)
  5282. {
  5283. data.remotePort.push(port);
  5284. }
  5285. if(data.localIP.indexOf(localIP) == -1)
  5286. {
  5287. data.localIP.push(localIP);
  5288. }
  5289. if(data.localPort.indexOf(localPort) == -1)
  5290. {
  5291. data.localPort.push(localPort);
  5292. }
  5293. }
  5294. var local_address_key = "connectionindicator.localaddress";
  5295. var remote_address_key = "connectionindicator.remoteaddress";
  5296. var localTransport =
  5297. "<tr><td><span class='jitsipopover_blue' data-i18n='" +
  5298. local_address_key +"' data-i18n-options='" +
  5299. JSON.stringify({count: data.localIP.length}) + "'>" +
  5300. translate(local_address_key, {count: data.localIP.length}) +
  5301. "</span></td><td> " +
  5302. ConnectionIndicator.getStringFromArray(data.localIP) +
  5303. "</td></tr>";
  5304. transport =
  5305. "<tr><td><span class='jitsipopover_blue' data-i18n='" +
  5306. remote_address_key + "' data-i18n-options='" +
  5307. JSON.stringify({count: data.remoteIP.length}) + "'>" +
  5308. translate(remote_address_key,
  5309. {count: data.remoteIP.length}) +
  5310. "</span></td><td> " +
  5311. ConnectionIndicator.getStringFromArray(data.remoteIP) +
  5312. "</td></tr>";
  5313. var key_remote = "connectionindicator.remoteport",
  5314. key_local = "connectionindicator.localport";
  5315. transport += "<tr>" +
  5316. "<td>" +
  5317. "<span class='jitsipopover_blue' data-i18n='" + key_remote +
  5318. "' data-i18n-options='" +
  5319. JSON.stringify({count: this.transport.length}) + "'>" +
  5320. translate(key_remote, {count: this.transport.length}) +
  5321. "</span></td><td>";
  5322. localTransport += "<tr>" +
  5323. "<td>" +
  5324. "<span class='jitsipopover_blue' data-i18n='" + key_local +
  5325. "' data-i18n-options='" +
  5326. JSON.stringify({count: this.transport.length}) + "'>" +
  5327. translate(key_local, {count: this.transport.length}) +
  5328. "</span></td><td>";
  5329. transport +=
  5330. ConnectionIndicator.getStringFromArray(data.remotePort);
  5331. localTransport +=
  5332. ConnectionIndicator.getStringFromArray(data.localPort);
  5333. transport += "</td></tr>";
  5334. transport += localTransport + "</td></tr>";
  5335. transport +="<tr>" +
  5336. "<td><span class='jitsipopover_blue' data-i18n='connectionindicator.transport'>" +
  5337. translate("connectionindicator.transport") + "</span></td>" +
  5338. "<td>" + this.transport[0].type + "</td></tr>";
  5339. }
  5340. result += "<table style='width:100%'>" +
  5341. "<tr>" +
  5342. "<td>" +
  5343. "<span class='jitsipopover_blue' data-i18n='connectionindicator.bandwidth'>" +
  5344. translate("connectionindicator.bandwidth") + "</span>" +
  5345. "</td><td>" +
  5346. "<span class='jitsipopover_green'>&darr;</span>" +
  5347. downloadBandwidth +
  5348. " <span class='jitsipopover_orange'>&uarr;</span>" +
  5349. uploadBandwidth + "</td></tr>";
  5350. result += transport + "</table>";
  5351. }
  5352. return result;
  5353. };
  5354. /**
  5355. * Shows or hide the additional information.
  5356. */
  5357. ConnectionIndicator.prototype.showMore = function () {
  5358. this.showMoreValue = !this.showMoreValue;
  5359. this.updatePopoverData();
  5360. };
  5361. function createIcon(classes)
  5362. {
  5363. var icon = document.createElement("span");
  5364. for(var i in classes)
  5365. {
  5366. icon.classList.add(classes[i]);
  5367. }
  5368. icon.appendChild(
  5369. document.createElement("i")).classList.add("icon-connection");
  5370. return icon;
  5371. }
  5372. /**
  5373. * Creates the indicator
  5374. */
  5375. ConnectionIndicator.prototype.create = function () {
  5376. this.connectionIndicatorContainer = document.createElement("div");
  5377. this.connectionIndicatorContainer.className = "connectionindicator";
  5378. this.connectionIndicatorContainer.style.display = "none";
  5379. this.videoContainer.appendChild(this.connectionIndicatorContainer);
  5380. this.popover = new JitsiPopover(
  5381. $("#" + this.videoContainer.id + " > .connectionindicator"),
  5382. {content: "<div class=\"connection_info\" data-i18n='connectionindicator.na'>" +
  5383. APP.translation.translateString("connectionindicator.na") + "</div>",
  5384. skin: "black"});
  5385. this.emptyIcon = this.connectionIndicatorContainer.appendChild(
  5386. createIcon(["connection", "connection_empty"]));
  5387. this.fullIcon = this.connectionIndicatorContainer.appendChild(
  5388. createIcon(["connection", "connection_full"]));
  5389. };
  5390. /**
  5391. * Removes the indicator
  5392. */
  5393. ConnectionIndicator.prototype.remove = function()
  5394. {
  5395. this.connectionIndicatorContainer.remove();
  5396. this.popover.forceHide();
  5397. };
  5398. /**
  5399. * Updates the data of the indicator
  5400. * @param percent the percent of connection quality
  5401. * @param object the statistics data.
  5402. */
  5403. ConnectionIndicator.prototype.updateConnectionQuality =
  5404. function (percent, object) {
  5405. if(percent === null)
  5406. {
  5407. this.connectionIndicatorContainer.style.display = "none";
  5408. this.popover.forceHide();
  5409. return;
  5410. }
  5411. else
  5412. {
  5413. if(this.connectionIndicatorContainer.style.display == "none") {
  5414. this.connectionIndicatorContainer.style.display = "block";
  5415. this.videoLayout.updateMutePosition(this.videoContainer.id);
  5416. }
  5417. }
  5418. this.bandwidth = object.bandwidth;
  5419. this.bitrate = object.bitrate;
  5420. this.packetLoss = object.packetLoss;
  5421. this.transport = object.transport;
  5422. if(object.resolution)
  5423. {
  5424. this.resolution = object.resolution;
  5425. }
  5426. for(var quality in ConnectionIndicator.connectionQualityValues)
  5427. {
  5428. if(percent >= quality)
  5429. {
  5430. this.fullIcon.style.width =
  5431. ConnectionIndicator.connectionQualityValues[quality];
  5432. }
  5433. }
  5434. this.updatePopoverData();
  5435. };
  5436. /**
  5437. * Updates the resolution
  5438. * @param resolution the new resolution
  5439. */
  5440. ConnectionIndicator.prototype.updateResolution = function (resolution) {
  5441. this.resolution = resolution;
  5442. this.updatePopoverData();
  5443. };
  5444. /**
  5445. * Updates the content of the popover
  5446. */
  5447. ConnectionIndicator.prototype.updatePopoverData = function () {
  5448. this.popover.updateContent(
  5449. "<div class=\"connection_info\">" + this.generateText() + "</div>");
  5450. APP.translation.translateElement($(".connection_info"));
  5451. };
  5452. /**
  5453. * Hides the popover
  5454. */
  5455. ConnectionIndicator.prototype.hide = function () {
  5456. this.popover.forceHide();
  5457. };
  5458. /**
  5459. * Hides the indicator
  5460. */
  5461. ConnectionIndicator.prototype.hideIndicator = function () {
  5462. this.connectionIndicatorContainer.style.display = "none";
  5463. if(this.popover)
  5464. this.popover.forceHide();
  5465. };
  5466. module.exports = ConnectionIndicator;
  5467. },{"../util/JitsiPopover":26}],31:[function(require,module,exports){
  5468. var AudioLevels = require("../audio_levels/AudioLevels");
  5469. var Avatar = require("../avatar/Avatar");
  5470. var Chat = require("../side_pannels/chat/Chat");
  5471. var ContactList = require("../side_pannels/contactlist/ContactList");
  5472. var UIUtil = require("../util/UIUtil");
  5473. var ConnectionIndicator = require("./ConnectionIndicator");
  5474. var NicknameHandler = require("../util/NicknameHandler");
  5475. var MediaStreamType = require("../../../service/RTC/MediaStreamTypes");
  5476. var UIEvents = require("../../../service/UI/UIEvents");
  5477. var currentDominantSpeaker = null;
  5478. var lastNCount = config.channelLastN;
  5479. var localLastNCount = config.channelLastN;
  5480. var localLastNSet = [];
  5481. var lastNEndpointsCache = [];
  5482. var lastNPickupJid = null;
  5483. var largeVideoState = {
  5484. updateInProgress: false,
  5485. newSrc: ''
  5486. };
  5487. var eventEmitter = null;
  5488. /**
  5489. * Currently focused video "src"(displayed in large video).
  5490. * @type {String}
  5491. */
  5492. var focusedVideoInfo = null;
  5493. /**
  5494. * Indicates if we have muted our audio before the conference has started.
  5495. * @type {boolean}
  5496. */
  5497. var preMuted = false;
  5498. var mutedAudios = {};
  5499. var flipXLocalVideo = true;
  5500. var currentVideoWidth = null;
  5501. var currentVideoHeight = null;
  5502. var localVideoSrc = null;
  5503. function videoactive( videoelem) {
  5504. if (videoelem.attr('id').indexOf('mixedmslabel') === -1) {
  5505. // ignore mixedmslabela0 and v0
  5506. videoelem.show();
  5507. VideoLayout.resizeThumbnails();
  5508. var videoParent = videoelem.parent();
  5509. var parentResourceJid = null;
  5510. if (videoParent)
  5511. parentResourceJid
  5512. = VideoLayout.getPeerContainerResourceJid(videoParent[0]);
  5513. // Update the large video to the last added video only if there's no
  5514. // current dominant, focused speaker or prezi playing or update it to
  5515. // the current dominant speaker.
  5516. if ((!focusedVideoInfo &&
  5517. !VideoLayout.getDominantSpeakerResourceJid() &&
  5518. !require("../prezi/Prezi").isPresentationVisible()) ||
  5519. (parentResourceJid &&
  5520. VideoLayout.getDominantSpeakerResourceJid() === parentResourceJid)) {
  5521. VideoLayout.updateLargeVideo(
  5522. APP.RTC.getVideoSrc(videoelem[0]),
  5523. 1,
  5524. parentResourceJid);
  5525. }
  5526. VideoLayout.showModeratorIndicator();
  5527. }
  5528. }
  5529. function waitForRemoteVideo(selector, ssrc, stream, jid) {
  5530. // XXX(gp) so, every call to this function is *always* preceded by a call
  5531. // to the RTC.attachMediaStream() function but that call is *not* followed
  5532. // by an update to the videoSrcToSsrc map!
  5533. //
  5534. // The above way of doing things results in video SRCs that don't correspond
  5535. // to any SSRC for a short period of time (to be more precise, for as long
  5536. // the waitForRemoteVideo takes to complete). This causes problems (see
  5537. // bellow).
  5538. //
  5539. // I'm wondering why we need to do that; i.e. why call RTC.attachMediaStream()
  5540. // a second time in here and only then update the videoSrcToSsrc map? Why
  5541. // not simply update the videoSrcToSsrc map when the RTC.attachMediaStream()
  5542. // is called the first time? I actually do that in the lastN changed event
  5543. // handler because the "orphan" video SRC is causing troubles there. The
  5544. // purpose of this method would then be to fire the "videoactive.jingle".
  5545. //
  5546. // Food for though I guess :-)
  5547. if (selector.removed || !selector.parent().is(":visible")) {
  5548. console.warn("Media removed before had started", selector);
  5549. return;
  5550. }
  5551. if (stream.id === 'mixedmslabel') return;
  5552. if (selector[0].currentTime > 0) {
  5553. var videoStream = APP.simulcast.getReceivingVideoStream(stream);
  5554. APP.RTC.attachMediaStream(selector, videoStream); // FIXME: why do i have to do this for FF?
  5555. videoactive(selector);
  5556. } else {
  5557. setTimeout(function () {
  5558. waitForRemoteVideo(selector, ssrc, stream, jid);
  5559. }, 250);
  5560. }
  5561. }
  5562. /**
  5563. * Returns an array of the video horizontal and vertical indents,
  5564. * so that if fits its parent.
  5565. *
  5566. * @return an array with 2 elements, the horizontal indent and the vertical
  5567. * indent
  5568. */
  5569. function getCameraVideoPosition(videoWidth,
  5570. videoHeight,
  5571. videoSpaceWidth,
  5572. videoSpaceHeight) {
  5573. // Parent height isn't completely calculated when we position the video in
  5574. // full screen mode and this is why we use the screen height in this case.
  5575. // Need to think it further at some point and implement it properly.
  5576. var isFullScreen = document.fullScreen ||
  5577. document.mozFullScreen ||
  5578. document.webkitIsFullScreen;
  5579. if (isFullScreen)
  5580. videoSpaceHeight = window.innerHeight;
  5581. var horizontalIndent = (videoSpaceWidth - videoWidth) / 2;
  5582. var verticalIndent = (videoSpaceHeight - videoHeight) / 2;
  5583. return [horizontalIndent, verticalIndent];
  5584. }
  5585. /**
  5586. * Returns an array of the video horizontal and vertical indents.
  5587. * Centers horizontally and top aligns vertically.
  5588. *
  5589. * @return an array with 2 elements, the horizontal indent and the vertical
  5590. * indent
  5591. */
  5592. function getDesktopVideoPosition(videoWidth,
  5593. videoHeight,
  5594. videoSpaceWidth,
  5595. videoSpaceHeight) {
  5596. var horizontalIndent = (videoSpaceWidth - videoWidth) / 2;
  5597. var verticalIndent = 0;// Top aligned
  5598. return [horizontalIndent, verticalIndent];
  5599. }
  5600. /**
  5601. * Returns an array of the video dimensions, so that it covers the screen.
  5602. * It leaves no empty areas, but some parts of the video might not be visible.
  5603. *
  5604. * @return an array with 2 elements, the video width and the video height
  5605. */
  5606. function getCameraVideoSize(videoWidth,
  5607. videoHeight,
  5608. videoSpaceWidth,
  5609. videoSpaceHeight) {
  5610. if (!videoWidth)
  5611. videoWidth = currentVideoWidth;
  5612. if (!videoHeight)
  5613. videoHeight = currentVideoHeight;
  5614. var aspectRatio = videoWidth / videoHeight;
  5615. var availableWidth = Math.max(videoWidth, videoSpaceWidth);
  5616. var availableHeight = Math.max(videoHeight, videoSpaceHeight);
  5617. if (availableWidth / aspectRatio < videoSpaceHeight) {
  5618. availableHeight = videoSpaceHeight;
  5619. availableWidth = availableHeight * aspectRatio;
  5620. }
  5621. if (availableHeight * aspectRatio < videoSpaceWidth) {
  5622. availableWidth = videoSpaceWidth;
  5623. availableHeight = availableWidth / aspectRatio;
  5624. }
  5625. return [availableWidth, availableHeight];
  5626. }
  5627. /**
  5628. * Sets the display name for the given video span id.
  5629. */
  5630. function setDisplayName(videoSpanId, displayName, key) {
  5631. var nameSpan = $('#' + videoSpanId + '>span.displayname');
  5632. var defaultLocalDisplayName = APP.translation.generateTranslatonHTML(
  5633. interfaceConfig.DEFAULT_LOCAL_DISPLAY_NAME);
  5634. // If we already have a display name for this video.
  5635. if (nameSpan.length > 0) {
  5636. var nameSpanElement = nameSpan.get(0);
  5637. if (nameSpanElement.id === 'localDisplayName' &&
  5638. $('#localDisplayName').text() !== displayName) {
  5639. if (displayName && displayName.length > 0)
  5640. {
  5641. var meHTML = APP.translation.generateTranslatonHTML("me");
  5642. $('#localDisplayName').html(displayName + ' (' + meHTML + ')');
  5643. }
  5644. else
  5645. $('#localDisplayName').html(defaultLocalDisplayName);
  5646. } else {
  5647. if (displayName && displayName.length > 0)
  5648. {
  5649. $('#' + videoSpanId + '_name').html(displayName);
  5650. }
  5651. else if (key && key.length > 0)
  5652. {
  5653. var nameHtml = APP.translation.generateTranslatonHTML(key);
  5654. $('#' + videoSpanId + '_name').html(nameHtml);
  5655. }
  5656. else
  5657. $('#' + videoSpanId + '_name').text(
  5658. interfaceConfig.DEFAULT_REMOTE_DISPLAY_NAME);
  5659. }
  5660. } else {
  5661. var editButton = null;
  5662. nameSpan = document.createElement('span');
  5663. nameSpan.className = 'displayname';
  5664. $('#' + videoSpanId)[0].appendChild(nameSpan);
  5665. if (videoSpanId === 'localVideoContainer') {
  5666. editButton = createEditDisplayNameButton();
  5667. if (displayName && displayName.length > 0) {
  5668. var meHTML = APP.translation.generateTranslatonHTML("me");
  5669. nameSpan.innerHTML = displayName + meHTML;
  5670. }
  5671. else
  5672. nameSpan.innerHTML = defaultLocalDisplayName;
  5673. }
  5674. else {
  5675. if (displayName && displayName.length > 0) {
  5676. nameSpan.innerText = displayName;
  5677. }
  5678. else
  5679. nameSpan.innerText = interfaceConfig.DEFAULT_REMOTE_DISPLAY_NAME;
  5680. }
  5681. if (!editButton) {
  5682. nameSpan.id = videoSpanId + '_name';
  5683. } else {
  5684. nameSpan.id = 'localDisplayName';
  5685. $('#' + videoSpanId)[0].appendChild(editButton);
  5686. //translates popover of edit button
  5687. APP.translation.translateElement($("a.displayname"));
  5688. var editableText = document.createElement('input');
  5689. editableText.className = 'displayname';
  5690. editableText.type = 'text';
  5691. editableText.id = 'editDisplayName';
  5692. if (displayName && displayName.length) {
  5693. editableText.value
  5694. = displayName;
  5695. }
  5696. var defaultNickname = APP.translation.translateString(
  5697. "defaultNickname", {name: "Jane Pink"});
  5698. editableText.setAttribute('style', 'display:none;');
  5699. editableText.setAttribute('data-18n',
  5700. '[placeholder]defaultNickname');
  5701. editableText.setAttribute("data-i18n-options",
  5702. JSON.stringify({name: "Jane Pink"}));
  5703. editableText.setAttribute("placeholder", defaultNickname);
  5704. $('#' + videoSpanId)[0].appendChild(editableText);
  5705. $('#localVideoContainer .displayname')
  5706. .bind("click", function (e) {
  5707. e.preventDefault();
  5708. e.stopPropagation();
  5709. $('#localDisplayName').hide();
  5710. $('#editDisplayName').show();
  5711. $('#editDisplayName').focus();
  5712. $('#editDisplayName').select();
  5713. $('#editDisplayName').one("focusout", function (e) {
  5714. VideoLayout.inputDisplayNameHandler(this.value);
  5715. });
  5716. $('#editDisplayName').on('keydown', function (e) {
  5717. if (e.keyCode === 13) {
  5718. e.preventDefault();
  5719. VideoLayout.inputDisplayNameHandler(this.value);
  5720. }
  5721. });
  5722. });
  5723. }
  5724. }
  5725. }
  5726. /**
  5727. * Gets the selector of video thumbnail container for the user identified by
  5728. * given <tt>userJid</tt>
  5729. * @param resourceJid user's Jid for whom we want to get the video container.
  5730. */
  5731. function getParticipantContainer(resourceJid)
  5732. {
  5733. if (!resourceJid)
  5734. return null;
  5735. if (resourceJid === APP.xmpp.myResource())
  5736. return $("#localVideoContainer");
  5737. else
  5738. return $("#participant_" + resourceJid);
  5739. }
  5740. /**
  5741. * Sets the size and position of the given video element.
  5742. *
  5743. * @param video the video element to position
  5744. * @param width the desired video width
  5745. * @param height the desired video height
  5746. * @param horizontalIndent the left and right indent
  5747. * @param verticalIndent the top and bottom indent
  5748. */
  5749. function positionVideo(video,
  5750. width,
  5751. height,
  5752. horizontalIndent,
  5753. verticalIndent) {
  5754. video.width(width);
  5755. video.height(height);
  5756. video.css({ top: verticalIndent + 'px',
  5757. bottom: verticalIndent + 'px',
  5758. left: horizontalIndent + 'px',
  5759. right: horizontalIndent + 'px'});
  5760. }
  5761. /**
  5762. * Adds the remote video menu element for the given <tt>jid</tt> in the
  5763. * given <tt>parentElement</tt>.
  5764. *
  5765. * @param jid the jid indicating the video for which we're adding a menu.
  5766. * @param parentElement the parent element where this menu will be added
  5767. */
  5768. function addRemoteVideoMenu(jid, parentElement) {
  5769. var spanElement = document.createElement('span');
  5770. spanElement.className = 'remotevideomenu';
  5771. parentElement.appendChild(spanElement);
  5772. var menuElement = document.createElement('i');
  5773. menuElement.className = 'fa fa-angle-down';
  5774. menuElement.title = 'Remote user controls';
  5775. spanElement.appendChild(menuElement);
  5776. // <ul class="popupmenu">
  5777. // <li><a href="#">Mute</a></li>
  5778. // <li><a href="#">Eject</a></li>
  5779. // </ul>
  5780. var popupmenuElement = document.createElement('ul');
  5781. popupmenuElement.className = 'popupmenu';
  5782. popupmenuElement.id
  5783. = 'remote_popupmenu_' + Strophe.getResourceFromJid(jid);
  5784. spanElement.appendChild(popupmenuElement);
  5785. var muteMenuItem = document.createElement('li');
  5786. var muteLinkItem = document.createElement('a');
  5787. var mutedIndicator = "<i style='float:left;' class='icon-mic-disabled'></i>";
  5788. if (!mutedAudios[jid]) {
  5789. muteLinkItem.innerHTML = mutedIndicator +
  5790. " <div style='width: 90px;margin-left: 20px;' data-i18n='videothumbnail.domute'></div>";
  5791. muteLinkItem.className = 'mutelink';
  5792. }
  5793. else {
  5794. muteLinkItem.innerHTML = mutedIndicator +
  5795. " <div style='width: 90px;margin-left: 20px;' data-i18n='videothumbnail.muted'></div>";
  5796. muteLinkItem.className = 'mutelink disabled';
  5797. }
  5798. muteLinkItem.onclick = function(){
  5799. if ($(this).attr('disabled') != undefined) {
  5800. event.preventDefault();
  5801. }
  5802. var isMute = mutedAudios[jid] == true;
  5803. APP.xmpp.setMute(jid, !isMute);
  5804. popupmenuElement.setAttribute('style', 'display:none;');
  5805. if (isMute) {
  5806. this.innerHTML = mutedIndicator +
  5807. " <div style='width: 90px;margin-left: 20px;' data-i18n='videothumbnail.muted'></div>";
  5808. this.className = 'mutelink disabled';
  5809. }
  5810. else {
  5811. this.innerHTML = mutedIndicator +
  5812. " <div style='width: 90px;margin-left: 20px;' data-i18n='videothumbnail.domute'></div>";
  5813. this.className = 'mutelink';
  5814. }
  5815. };
  5816. muteMenuItem.appendChild(muteLinkItem);
  5817. popupmenuElement.appendChild(muteMenuItem);
  5818. var ejectIndicator = "<i style='float:left;' class='fa fa-eject'></i>";
  5819. var ejectMenuItem = document.createElement('li');
  5820. var ejectLinkItem = document.createElement('a');
  5821. var ejectText = "<div style='width: 90px;margin-left: 20px;' data-i18n='videothumbnail.kick'>&nbsp;</div>";
  5822. ejectLinkItem.innerHTML = ejectIndicator + ' ' + ejectText;
  5823. ejectLinkItem.onclick = function(){
  5824. APP.xmpp.eject(jid);
  5825. popupmenuElement.setAttribute('style', 'display:none;');
  5826. };
  5827. ejectMenuItem.appendChild(ejectLinkItem);
  5828. popupmenuElement.appendChild(ejectMenuItem);
  5829. var paddingSpan = document.createElement('span');
  5830. paddingSpan.className = 'popupmenuPadding';
  5831. popupmenuElement.appendChild(paddingSpan);
  5832. APP.translation.translateElement($("#" + popupmenuElement.id + " > li > a > div"));
  5833. }
  5834. /**
  5835. * Removes remote video menu element from video element identified by
  5836. * given <tt>videoElementId</tt>.
  5837. *
  5838. * @param videoElementId the id of local or remote video element.
  5839. */
  5840. function removeRemoteVideoMenu(videoElementId) {
  5841. var menuSpan = $('#' + videoElementId + '>span.remotevideomenu');
  5842. if (menuSpan.length) {
  5843. menuSpan.remove();
  5844. }
  5845. }
  5846. /**
  5847. * Updates the data for the indicator
  5848. * @param id the id of the indicator
  5849. * @param percent the percent for connection quality
  5850. * @param object the data
  5851. */
  5852. function updateStatsIndicator(id, percent, object) {
  5853. if(VideoLayout.connectionIndicators[id])
  5854. VideoLayout.connectionIndicators[id].updateConnectionQuality(percent, object);
  5855. }
  5856. /**
  5857. * Returns an array of the video dimensions, so that it keeps it's aspect
  5858. * ratio and fits available area with it's larger dimension. This method
  5859. * ensures that whole video will be visible and can leave empty areas.
  5860. *
  5861. * @return an array with 2 elements, the video width and the video height
  5862. */
  5863. function getDesktopVideoSize(videoWidth,
  5864. videoHeight,
  5865. videoSpaceWidth,
  5866. videoSpaceHeight) {
  5867. if (!videoWidth)
  5868. videoWidth = currentVideoWidth;
  5869. if (!videoHeight)
  5870. videoHeight = currentVideoHeight;
  5871. var aspectRatio = videoWidth / videoHeight;
  5872. var availableWidth = Math.max(videoWidth, videoSpaceWidth);
  5873. var availableHeight = Math.max(videoHeight, videoSpaceHeight);
  5874. videoSpaceHeight -= $('#remoteVideos').outerHeight();
  5875. if (availableWidth / aspectRatio >= videoSpaceHeight)
  5876. {
  5877. availableHeight = videoSpaceHeight;
  5878. availableWidth = availableHeight * aspectRatio;
  5879. }
  5880. if (availableHeight * aspectRatio >= videoSpaceWidth)
  5881. {
  5882. availableWidth = videoSpaceWidth;
  5883. availableHeight = availableWidth / aspectRatio;
  5884. }
  5885. return [availableWidth, availableHeight];
  5886. }
  5887. /**
  5888. * Creates the edit display name button.
  5889. *
  5890. * @returns the edit button
  5891. */
  5892. function createEditDisplayNameButton() {
  5893. var editButton = document.createElement('a');
  5894. editButton.className = 'displayname';
  5895. UIUtil.setTooltip(editButton,
  5896. "videothumbnail.editnickname",
  5897. "top");
  5898. editButton.innerHTML = '<i class="fa fa-pencil"></i>';
  5899. return editButton;
  5900. }
  5901. /**
  5902. * Creates the element indicating the moderator(owner) of the conference.
  5903. *
  5904. * @param parentElement the parent element where the owner indicator will
  5905. * be added
  5906. */
  5907. function createModeratorIndicatorElement(parentElement) {
  5908. var moderatorIndicator = document.createElement('i');
  5909. moderatorIndicator.className = 'fa fa-star';
  5910. parentElement.appendChild(moderatorIndicator);
  5911. UIUtil.setTooltip(parentElement,
  5912. "videothumbnail.moderator",
  5913. "top");
  5914. }
  5915. var VideoLayout = (function (my) {
  5916. my.connectionIndicators = {};
  5917. // By default we use camera
  5918. my.getVideoSize = getCameraVideoSize;
  5919. my.getVideoPosition = getCameraVideoPosition;
  5920. my.init = function (emitter) {
  5921. // Listen for large video size updates
  5922. document.getElementById('largeVideo')
  5923. .addEventListener('loadedmetadata', function (e) {
  5924. currentVideoWidth = this.videoWidth;
  5925. currentVideoHeight = this.videoHeight;
  5926. VideoLayout.positionLarge(currentVideoWidth, currentVideoHeight);
  5927. });
  5928. eventEmitter = emitter;
  5929. };
  5930. my.isInLastN = function(resource) {
  5931. return lastNCount < 0 // lastN is disabled, return true
  5932. || (lastNCount > 0 && lastNEndpointsCache.length == 0) // lastNEndpoints cache not built yet, return true
  5933. || (lastNEndpointsCache && lastNEndpointsCache.indexOf(resource) !== -1);
  5934. };
  5935. my.changeLocalStream = function (stream) {
  5936. VideoLayout.changeLocalVideo(stream);
  5937. };
  5938. my.changeLocalAudio = function(stream) {
  5939. APP.RTC.attachMediaStream($('#localAudio'), stream.getOriginalStream());
  5940. document.getElementById('localAudio').autoplay = true;
  5941. document.getElementById('localAudio').volume = 0;
  5942. if (preMuted) {
  5943. if(!APP.UI.setAudioMuted(true))
  5944. {
  5945. preMuted = mute;
  5946. }
  5947. preMuted = false;
  5948. }
  5949. };
  5950. my.changeLocalVideo = function(stream) {
  5951. var flipX = true;
  5952. if(stream.videoType == "screen")
  5953. flipX = false;
  5954. var localVideo = document.createElement('video');
  5955. localVideo.id = 'localVideo_' +
  5956. APP.RTC.getStreamID(stream.getOriginalStream());
  5957. localVideo.autoplay = true;
  5958. localVideo.volume = 0; // is it required if audio is separated ?
  5959. localVideo.oncontextmenu = function () { return false; };
  5960. var localVideoContainer = document.getElementById('localVideoWrapper');
  5961. localVideoContainer.appendChild(localVideo);
  5962. // Set default display name.
  5963. setDisplayName('localVideoContainer');
  5964. if(!VideoLayout.connectionIndicators["localVideoContainer"]) {
  5965. VideoLayout.connectionIndicators["localVideoContainer"]
  5966. = new ConnectionIndicator($("#localVideoContainer")[0], null, VideoLayout);
  5967. }
  5968. AudioLevels.updateAudioLevelCanvas(null, VideoLayout);
  5969. var localVideoSelector = $('#' + localVideo.id);
  5970. function localVideoClick(event) {
  5971. event.stopPropagation();
  5972. VideoLayout.handleVideoThumbClicked(
  5973. APP.RTC.getVideoSrc(localVideo),
  5974. false,
  5975. APP.xmpp.myResource());
  5976. }
  5977. // Add click handler to both video and video wrapper elements in case
  5978. // there's no video.
  5979. localVideoSelector.click(localVideoClick);
  5980. $('#localVideoContainer').click(localVideoClick);
  5981. // Add hover handler
  5982. $('#localVideoContainer').hover(
  5983. function() {
  5984. VideoLayout.showDisplayName('localVideoContainer', true);
  5985. },
  5986. function() {
  5987. if (!VideoLayout.isLargeVideoVisible()
  5988. || APP.RTC.getVideoSrc(localVideo) !== APP.RTC.getVideoSrc($('#largeVideo')[0]))
  5989. VideoLayout.showDisplayName('localVideoContainer', false);
  5990. }
  5991. );
  5992. // Add stream ended handler
  5993. stream.getOriginalStream().onended = function () {
  5994. localVideoContainer.removeChild(localVideo);
  5995. VideoLayout.updateRemovedVideo(APP.RTC.getVideoSrc(localVideo));
  5996. };
  5997. // Flip video x axis if needed
  5998. flipXLocalVideo = flipX;
  5999. if (flipX) {
  6000. localVideoSelector.addClass("flipVideoX");
  6001. }
  6002. // Attach WebRTC stream
  6003. var videoStream = APP.simulcast.getLocalVideoStream();
  6004. APP.RTC.attachMediaStream(localVideoSelector, videoStream);
  6005. localVideoSrc = APP.RTC.getVideoSrc(localVideo);
  6006. var myResourceJid = APP.xmpp.myResource();
  6007. VideoLayout.updateLargeVideo(localVideoSrc, 0,
  6008. myResourceJid);
  6009. };
  6010. /**
  6011. * Checks if removed video is currently displayed and tries to display
  6012. * another one instead.
  6013. * @param removedVideoSrc src stream identifier of the video.
  6014. */
  6015. my.updateRemovedVideo = function(removedVideoSrc) {
  6016. if (removedVideoSrc === APP.RTC.getVideoSrc($('#largeVideo')[0])) {
  6017. // this is currently displayed as large
  6018. // pick the last visible video in the row
  6019. // if nobody else is left, this picks the local video
  6020. var pick
  6021. = $('#remoteVideos>span[id!="mixedstream"]:visible:last>video')
  6022. .get(0);
  6023. if (!pick) {
  6024. console.info("Last visible video no longer exists");
  6025. pick = $('#remoteVideos>span[id!="mixedstream"]>video').get(0);
  6026. if (!pick || !APP.RTC.getVideoSrc(pick)) {
  6027. // Try local video
  6028. console.info("Fallback to local video...");
  6029. pick = $('#remoteVideos>span>span>video').get(0);
  6030. }
  6031. }
  6032. // mute if localvideo
  6033. if (pick) {
  6034. var container = pick.parentNode;
  6035. var jid = null;
  6036. if(container)
  6037. {
  6038. if(container.id == "localVideoWrapper")
  6039. {
  6040. jid = APP.xmpp.myResource();
  6041. }
  6042. else
  6043. {
  6044. jid = VideoLayout.getPeerContainerResourceJid(container);
  6045. }
  6046. }
  6047. VideoLayout.updateLargeVideo(APP.RTC.getVideoSrc(pick), pick.volume, jid);
  6048. } else {
  6049. console.warn("Failed to elect large video");
  6050. }
  6051. }
  6052. };
  6053. my.onRemoteStreamAdded = function (stream) {
  6054. var container;
  6055. var remotes = document.getElementById('remoteVideos');
  6056. if (stream.peerjid) {
  6057. VideoLayout.ensurePeerContainerExists(stream.peerjid);
  6058. container = document.getElementById(
  6059. 'participant_' + Strophe.getResourceFromJid(stream.peerjid));
  6060. } else {
  6061. var id = stream.getOriginalStream().id;
  6062. if (id !== 'mixedmslabel'
  6063. // FIXME: default stream is added always with new focus
  6064. // (to be investigated)
  6065. && id !== 'default') {
  6066. console.error('can not associate stream',
  6067. id,
  6068. 'with a participant');
  6069. // We don't want to add it here since it will cause troubles
  6070. return;
  6071. }
  6072. // FIXME: for the mixed ms we dont need a video -- currently
  6073. container = document.createElement('span');
  6074. container.id = 'mixedstream';
  6075. container.className = 'videocontainer';
  6076. remotes.appendChild(container);
  6077. UIUtil.playSoundNotification('userJoined');
  6078. }
  6079. if (container) {
  6080. VideoLayout.addRemoteStreamElement( container,
  6081. stream.sid,
  6082. stream.getOriginalStream(),
  6083. stream.peerjid,
  6084. stream.ssrc);
  6085. }
  6086. }
  6087. my.getLargeVideoState = function () {
  6088. return largeVideoState;
  6089. };
  6090. /**
  6091. * Updates the large video with the given new video source.
  6092. */
  6093. my.updateLargeVideo = function(newSrc, vol, resourceJid) {
  6094. console.log('hover in', newSrc);
  6095. if (APP.RTC.getVideoSrc($('#largeVideo')[0]) !== newSrc) {
  6096. $('#activeSpeaker').css('visibility', 'hidden');
  6097. // Due to the simulcast the localVideoSrc may have changed when the
  6098. // fadeOut event triggers. In that case the getJidFromVideoSrc and
  6099. // isVideoSrcDesktop methods will not function correctly.
  6100. //
  6101. // Also, again due to the simulcast, the updateLargeVideo method can
  6102. // be called multiple times almost simultaneously. Therefore, we
  6103. // store the state here and update only once.
  6104. largeVideoState.newSrc = newSrc;
  6105. largeVideoState.isVisible = $('#largeVideo').is(':visible');
  6106. largeVideoState.isDesktop = APP.RTC.isVideoSrcDesktop(resourceJid);
  6107. if(largeVideoState.userResourceJid) {
  6108. largeVideoState.oldResourceJid = largeVideoState.userResourceJid;
  6109. } else {
  6110. largeVideoState.oldResourceJid = null;
  6111. }
  6112. largeVideoState.userResourceJid = resourceJid;
  6113. // Screen stream is already rotated
  6114. largeVideoState.flipX = (newSrc === localVideoSrc) && flipXLocalVideo;
  6115. var userChanged = false;
  6116. if (largeVideoState.oldResourceJid !== largeVideoState.userResourceJid) {
  6117. userChanged = true;
  6118. // we want the notification to trigger even if userJid is undefined,
  6119. // or null.
  6120. eventEmitter.emit(UIEvents.SELECTED_ENDPOINT,
  6121. largeVideoState.userResourceJid);
  6122. }
  6123. if (!largeVideoState.updateInProgress) {
  6124. largeVideoState.updateInProgress = true;
  6125. var doUpdate = function () {
  6126. Avatar.updateActiveSpeakerAvatarSrc(
  6127. APP.xmpp.findJidFromResource(
  6128. largeVideoState.userResourceJid));
  6129. if (!userChanged && largeVideoState.preload &&
  6130. largeVideoState.preload !== null &&
  6131. APP.RTC.getVideoSrc($(largeVideoState.preload)[0]) === newSrc)
  6132. {
  6133. console.info('Switching to preloaded video');
  6134. var attributes = $('#largeVideo').prop("attributes");
  6135. // loop through largeVideo attributes and apply them on
  6136. // preload.
  6137. $.each(attributes, function () {
  6138. if (this.name !== 'id' && this.name !== 'src') {
  6139. largeVideoState.preload.attr(this.name, this.value);
  6140. }
  6141. });
  6142. largeVideoState.preload.appendTo($('#largeVideoContainer'));
  6143. $('#largeVideo').attr('id', 'previousLargeVideo');
  6144. largeVideoState.preload.attr('id', 'largeVideo');
  6145. $('#previousLargeVideo').remove();
  6146. largeVideoState.preload.on('loadedmetadata', function (e) {
  6147. currentVideoWidth = this.videoWidth;
  6148. currentVideoHeight = this.videoHeight;
  6149. VideoLayout.positionLarge(currentVideoWidth, currentVideoHeight);
  6150. });
  6151. largeVideoState.preload = null;
  6152. largeVideoState.preload_ssrc = 0;
  6153. } else {
  6154. APP.RTC.setVideoSrc($('#largeVideo')[0], largeVideoState.newSrc);
  6155. }
  6156. var videoTransform = document.getElementById('largeVideo')
  6157. .style.webkitTransform;
  6158. if (largeVideoState.flipX && videoTransform !== 'scaleX(-1)') {
  6159. document.getElementById('largeVideo').style.webkitTransform
  6160. = "scaleX(-1)";
  6161. }
  6162. else if (!largeVideoState.flipX && videoTransform === 'scaleX(-1)') {
  6163. document.getElementById('largeVideo').style.webkitTransform
  6164. = "none";
  6165. }
  6166. // Change the way we'll be measuring and positioning large video
  6167. VideoLayout.getVideoSize = largeVideoState.isDesktop
  6168. ? getDesktopVideoSize
  6169. : getCameraVideoSize;
  6170. VideoLayout.getVideoPosition = largeVideoState.isDesktop
  6171. ? getDesktopVideoPosition
  6172. : getCameraVideoPosition;
  6173. // Only if the large video is currently visible.
  6174. // Disable previous dominant speaker video.
  6175. if (largeVideoState.oldResourceJid) {
  6176. VideoLayout.enableDominantSpeaker(
  6177. largeVideoState.oldResourceJid,
  6178. false);
  6179. }
  6180. // Enable new dominant speaker in the remote videos section.
  6181. if (largeVideoState.userResourceJid) {
  6182. VideoLayout.enableDominantSpeaker(
  6183. largeVideoState.userResourceJid,
  6184. true);
  6185. }
  6186. if (userChanged && largeVideoState.isVisible) {
  6187. // using "this" should be ok because we're called
  6188. // from within the fadeOut event.
  6189. $(this).fadeIn(300);
  6190. }
  6191. if(userChanged) {
  6192. Avatar.showUserAvatar(
  6193. APP.xmpp.findJidFromResource(
  6194. largeVideoState.oldResourceJid));
  6195. }
  6196. largeVideoState.updateInProgress = false;
  6197. };
  6198. if (userChanged) {
  6199. $('#largeVideo').fadeOut(300, doUpdate);
  6200. } else {
  6201. doUpdate();
  6202. }
  6203. }
  6204. } else {
  6205. Avatar.showUserAvatar(
  6206. APP.xmpp.findJidFromResource(
  6207. largeVideoState.userResourceJid));
  6208. }
  6209. };
  6210. my.handleVideoThumbClicked = function(videoSrc,
  6211. noPinnedEndpointChangedEvent,
  6212. resourceJid) {
  6213. // Restore style for previously focused video
  6214. var oldContainer = null;
  6215. if(focusedVideoInfo) {
  6216. var focusResourceJid = focusedVideoInfo.resourceJid;
  6217. oldContainer = getParticipantContainer(focusResourceJid);
  6218. }
  6219. if (oldContainer) {
  6220. oldContainer.removeClass("videoContainerFocused");
  6221. }
  6222. // Unlock current focused.
  6223. if (focusedVideoInfo && focusedVideoInfo.src === videoSrc)
  6224. {
  6225. focusedVideoInfo = null;
  6226. var dominantSpeakerVideo = null;
  6227. // Enable the currently set dominant speaker.
  6228. if (currentDominantSpeaker) {
  6229. dominantSpeakerVideo
  6230. = $('#participant_' + currentDominantSpeaker + '>video')
  6231. .get(0);
  6232. if (dominantSpeakerVideo) {
  6233. VideoLayout.updateLargeVideo(
  6234. APP.RTC.getVideoSrc(dominantSpeakerVideo),
  6235. 1,
  6236. currentDominantSpeaker);
  6237. }
  6238. }
  6239. if (!noPinnedEndpointChangedEvent) {
  6240. eventEmitter.emit(UIEvents.PINNED_ENDPOINT);
  6241. }
  6242. return;
  6243. }
  6244. // Lock new video
  6245. focusedVideoInfo = {
  6246. src: videoSrc,
  6247. resourceJid: resourceJid
  6248. };
  6249. // Update focused/pinned interface.
  6250. if (resourceJid)
  6251. {
  6252. var container = getParticipantContainer(resourceJid);
  6253. container.addClass("videoContainerFocused");
  6254. if (!noPinnedEndpointChangedEvent) {
  6255. eventEmitter.emit(UIEvents.PINNED_ENDPOINT, resourceJid);
  6256. }
  6257. }
  6258. if ($('#largeVideo').attr('src') === videoSrc &&
  6259. VideoLayout.isLargeVideoOnTop()) {
  6260. return;
  6261. }
  6262. // Triggers a "video.selected" event. The "false" parameter indicates
  6263. // this isn't a prezi.
  6264. $(document).trigger("video.selected", [false]);
  6265. VideoLayout.updateLargeVideo(videoSrc, 1, resourceJid);
  6266. $('audio').each(function (idx, el) {
  6267. if (el.id.indexOf('mixedmslabel') !== -1) {
  6268. el.volume = 0;
  6269. el.volume = 1;
  6270. }
  6271. });
  6272. };
  6273. /**
  6274. * Positions the large video.
  6275. *
  6276. * @param videoWidth the stream video width
  6277. * @param videoHeight the stream video height
  6278. */
  6279. my.positionLarge = function (videoWidth, videoHeight) {
  6280. var videoSpaceWidth = $('#videospace').width();
  6281. var videoSpaceHeight = window.innerHeight;
  6282. var videoSize = VideoLayout.getVideoSize(videoWidth,
  6283. videoHeight,
  6284. videoSpaceWidth,
  6285. videoSpaceHeight);
  6286. var largeVideoWidth = videoSize[0];
  6287. var largeVideoHeight = videoSize[1];
  6288. var videoPosition = VideoLayout.getVideoPosition(largeVideoWidth,
  6289. largeVideoHeight,
  6290. videoSpaceWidth,
  6291. videoSpaceHeight);
  6292. var horizontalIndent = videoPosition[0];
  6293. var verticalIndent = videoPosition[1];
  6294. positionVideo($('#largeVideo'),
  6295. largeVideoWidth,
  6296. largeVideoHeight,
  6297. horizontalIndent, verticalIndent);
  6298. };
  6299. /**
  6300. * Shows/hides the large video.
  6301. */
  6302. my.setLargeVideoVisible = function(isVisible) {
  6303. var resourceJid = largeVideoState.userResourceJid;
  6304. if (isVisible) {
  6305. $('#largeVideo').css({visibility: 'visible'});
  6306. $('.watermark').css({visibility: 'visible'});
  6307. VideoLayout.enableDominantSpeaker(resourceJid, true);
  6308. }
  6309. else {
  6310. $('#largeVideo').css({visibility: 'hidden'});
  6311. $('#activeSpeaker').css('visibility', 'hidden');
  6312. $('.watermark').css({visibility: 'hidden'});
  6313. VideoLayout.enableDominantSpeaker(resourceJid, false);
  6314. if(focusedVideoInfo) {
  6315. var focusResourceJid = focusedVideoInfo.resourceJid;
  6316. var oldContainer = getParticipantContainer(focusResourceJid);
  6317. if (oldContainer && oldContainer.length > 0) {
  6318. oldContainer.removeClass("videoContainerFocused");
  6319. }
  6320. focusedVideoInfo = null;
  6321. if(focusResourceJid) {
  6322. Avatar.showUserAvatar(
  6323. APP.xmpp.findJidFromResource(focusResourceJid));
  6324. }
  6325. }
  6326. }
  6327. };
  6328. /**
  6329. * Indicates if the large video is currently visible.
  6330. *
  6331. * @return <tt>true</tt> if visible, <tt>false</tt> - otherwise
  6332. */
  6333. my.isLargeVideoVisible = function() {
  6334. return $('#largeVideo').is(':visible');
  6335. };
  6336. my.isLargeVideoOnTop = function () {
  6337. var Etherpad = require("../etherpad/Etherpad");
  6338. var Prezi = require("../prezi/Prezi");
  6339. return !Prezi.isPresentationVisible() && !Etherpad.isVisible();
  6340. };
  6341. /**
  6342. * Checks if container for participant identified by given peerJid exists
  6343. * in the document and creates it eventually.
  6344. *
  6345. * @param peerJid peer Jid to check.
  6346. * @param userId user email or id for setting the avatar
  6347. *
  6348. * @return Returns <tt>true</tt> if the peer container exists,
  6349. * <tt>false</tt> - otherwise
  6350. */
  6351. my.ensurePeerContainerExists = function(peerJid, userId) {
  6352. ContactList.ensureAddContact(peerJid, userId);
  6353. var resourceJid = Strophe.getResourceFromJid(peerJid);
  6354. var videoSpanId = 'participant_' + resourceJid;
  6355. if (!$('#' + videoSpanId).length) {
  6356. var container =
  6357. VideoLayout.addRemoteVideoContainer(peerJid, videoSpanId, userId);
  6358. Avatar.setUserAvatar(peerJid, userId);
  6359. // Set default display name.
  6360. setDisplayName(videoSpanId);
  6361. VideoLayout.connectionIndicators[videoSpanId] =
  6362. new ConnectionIndicator(container, peerJid, VideoLayout);
  6363. var nickfield = document.createElement('span');
  6364. nickfield.className = "nick";
  6365. nickfield.appendChild(document.createTextNode(resourceJid));
  6366. container.appendChild(nickfield);
  6367. // In case this is not currently in the last n we don't show it.
  6368. if (localLastNCount
  6369. && localLastNCount > 0
  6370. && $('#remoteVideos>span').length >= localLastNCount + 2) {
  6371. showPeerContainer(resourceJid, 'hide');
  6372. }
  6373. else
  6374. VideoLayout.resizeThumbnails();
  6375. }
  6376. };
  6377. my.addRemoteVideoContainer = function(peerJid, spanId) {
  6378. var container = document.createElement('span');
  6379. container.id = spanId;
  6380. container.className = 'videocontainer';
  6381. var remotes = document.getElementById('remoteVideos');
  6382. remotes.appendChild(container);
  6383. // If the peerJid is null then this video span couldn't be directly
  6384. // associated with a participant (this could happen in the case of prezi).
  6385. if (APP.xmpp.isModerator() && peerJid !== null)
  6386. addRemoteVideoMenu(peerJid, container);
  6387. AudioLevels.updateAudioLevelCanvas(peerJid, VideoLayout);
  6388. return container;
  6389. };
  6390. /**
  6391. * Creates an audio or video stream element.
  6392. */
  6393. my.createStreamElement = function (sid, stream) {
  6394. var isVideo = stream.getVideoTracks().length > 0;
  6395. var element = isVideo
  6396. ? document.createElement('video')
  6397. : document.createElement('audio');
  6398. var id = (isVideo ? 'remoteVideo_' : 'remoteAudio_')
  6399. + sid + '_' + APP.RTC.getStreamID(stream);
  6400. element.id = id;
  6401. element.autoplay = true;
  6402. element.oncontextmenu = function () { return false; };
  6403. return element;
  6404. };
  6405. my.addRemoteStreamElement
  6406. = function (container, sid, stream, peerJid, thessrc) {
  6407. var newElementId = null;
  6408. var isVideo = stream.getVideoTracks().length > 0;
  6409. if (container) {
  6410. var streamElement = VideoLayout.createStreamElement(sid, stream);
  6411. newElementId = streamElement.id;
  6412. container.appendChild(streamElement);
  6413. var sel = $('#' + newElementId);
  6414. sel.hide();
  6415. // If the container is currently visible we attach the stream.
  6416. if (!isVideo
  6417. || (container.offsetParent !== null && isVideo)) {
  6418. var videoStream = APP.simulcast.getReceivingVideoStream(stream);
  6419. APP.RTC.attachMediaStream(sel, videoStream);
  6420. if (isVideo)
  6421. waitForRemoteVideo(sel, thessrc, stream, peerJid);
  6422. }
  6423. stream.onended = function () {
  6424. console.log('stream ended', this);
  6425. VideoLayout.removeRemoteStreamElement(
  6426. stream, isVideo, container);
  6427. // NOTE(gp) it seems that under certain circumstances, the
  6428. // onended event is not fired and thus the contact list is not
  6429. // updated.
  6430. //
  6431. // The onended event of a stream should be fired when the SSRCs
  6432. // corresponding to that stream are removed from the SDP; but
  6433. // this doesn't seem to always be the case, resulting in ghost
  6434. // contacts.
  6435. //
  6436. // In an attempt to fix the ghost contacts problem, I'm moving
  6437. // the removeContact() method call in app.js, inside the
  6438. // 'muc.left' event handler.
  6439. //if (peerJid)
  6440. // ContactList.removeContact(peerJid);
  6441. };
  6442. // Add click handler.
  6443. container.onclick = function (event) {
  6444. /*
  6445. * FIXME It turns out that videoThumb may not exist (if there is
  6446. * no actual video).
  6447. */
  6448. var videoThumb = $('#' + container.id + '>video').get(0);
  6449. if (videoThumb) {
  6450. VideoLayout.handleVideoThumbClicked(
  6451. APP.RTC.getVideoSrc(videoThumb),
  6452. false,
  6453. Strophe.getResourceFromJid(peerJid));
  6454. }
  6455. event.stopPropagation();
  6456. event.preventDefault();
  6457. return false;
  6458. };
  6459. // Add hover handler
  6460. $(container).hover(
  6461. function() {
  6462. VideoLayout.showDisplayName(container.id, true);
  6463. },
  6464. function() {
  6465. var videoSrc = null;
  6466. if ($('#' + container.id + '>video')
  6467. && $('#' + container.id + '>video').length > 0) {
  6468. videoSrc = APP.RTC.getVideoSrc($('#' + container.id + '>video').get(0));
  6469. }
  6470. // If the video has been "pinned" by the user we want to
  6471. // keep the display name on place.
  6472. if (!VideoLayout.isLargeVideoVisible()
  6473. || videoSrc !== APP.RTC.getVideoSrc($('#largeVideo')[0]))
  6474. VideoLayout.showDisplayName(container.id, false);
  6475. }
  6476. );
  6477. }
  6478. return newElementId;
  6479. };
  6480. /**
  6481. * Removes the remote stream element corresponding to the given stream and
  6482. * parent container.
  6483. *
  6484. * @param stream the stream
  6485. * @param isVideo <tt>true</tt> if given <tt>stream</tt> is a video one.
  6486. * @param container
  6487. */
  6488. my.removeRemoteStreamElement = function (stream, isVideo, container) {
  6489. if (!container)
  6490. return;
  6491. var select = null;
  6492. var removedVideoSrc = null;
  6493. if (isVideo) {
  6494. select = $('#' + container.id + '>video');
  6495. removedVideoSrc = APP.RTC.getVideoSrc(select.get(0));
  6496. }
  6497. else
  6498. select = $('#' + container.id + '>audio');
  6499. // Mark video as removed to cancel waiting loop(if video is removed
  6500. // before has started)
  6501. select.removed = true;
  6502. select.remove();
  6503. var audioCount = $('#' + container.id + '>audio').length;
  6504. var videoCount = $('#' + container.id + '>video').length;
  6505. if (!audioCount && !videoCount) {
  6506. console.log("Remove whole user", container.id);
  6507. if(VideoLayout.connectionIndicators[container.id])
  6508. VideoLayout.connectionIndicators[container.id].remove();
  6509. // Remove whole container
  6510. container.remove();
  6511. UIUtil.playSoundNotification('userLeft');
  6512. VideoLayout.resizeThumbnails();
  6513. }
  6514. if (removedVideoSrc)
  6515. VideoLayout.updateRemovedVideo(removedVideoSrc);
  6516. };
  6517. /**
  6518. * Show/hide peer container for the given resourceJid.
  6519. */
  6520. function showPeerContainer(resourceJid, state) {
  6521. var peerContainer = $('#participant_' + resourceJid);
  6522. if (!peerContainer)
  6523. return;
  6524. var isHide = state === 'hide';
  6525. var resizeThumbnails = false;
  6526. if (!isHide) {
  6527. if (!peerContainer.is(':visible')) {
  6528. resizeThumbnails = true;
  6529. peerContainer.show();
  6530. }
  6531. var jid = APP.xmpp.findJidFromResource(resourceJid);
  6532. if (state == 'show')
  6533. {
  6534. // peerContainer.css('-webkit-filter', '');
  6535. Avatar.showUserAvatar(jid, false);
  6536. }
  6537. else // if (state == 'avatar')
  6538. {
  6539. // peerContainer.css('-webkit-filter', 'grayscale(100%)');
  6540. Avatar.showUserAvatar(jid, true);
  6541. }
  6542. }
  6543. else if (peerContainer.is(':visible') && isHide)
  6544. {
  6545. resizeThumbnails = true;
  6546. peerContainer.hide();
  6547. if(VideoLayout.connectionIndicators['participant_' + resourceJid])
  6548. VideoLayout.connectionIndicators['participant_' + resourceJid].hide();
  6549. }
  6550. if (resizeThumbnails) {
  6551. VideoLayout.resizeThumbnails();
  6552. }
  6553. // We want to be able to pin a participant from the contact list, even
  6554. // if he's not in the lastN set!
  6555. // ContactList.setClickable(resourceJid, !isHide);
  6556. };
  6557. my.inputDisplayNameHandler = function (name) {
  6558. NicknameHandler.setNickname(name);
  6559. if (!$('#localDisplayName').is(":visible")) {
  6560. if (NicknameHandler.getNickname())
  6561. {
  6562. var meHTML = APP.translation.generateTranslatonHTML("me");
  6563. $('#localDisplayName').html(NicknameHandler.getNickname() + " (" + meHTML + ")");
  6564. }
  6565. else
  6566. {
  6567. var defaultHTML = APP.translation.generateTranslatonHTML(
  6568. interfaceConfig.DEFAULT_LOCAL_DISPLAY_NAME);
  6569. $('#localDisplayName')
  6570. .html(defaultHTML);
  6571. }
  6572. $('#localDisplayName').show();
  6573. }
  6574. $('#editDisplayName').hide();
  6575. };
  6576. /**
  6577. * Shows/hides the display name on the remote video.
  6578. * @param videoSpanId the identifier of the video span element
  6579. * @param isShow indicates if the display name should be shown or hidden
  6580. */
  6581. my.showDisplayName = function(videoSpanId, isShow) {
  6582. var nameSpan = $('#' + videoSpanId + '>span.displayname').get(0);
  6583. if (isShow) {
  6584. if (nameSpan && nameSpan.innerHTML && nameSpan.innerHTML.length)
  6585. nameSpan.setAttribute("style", "display:inline-block;");
  6586. }
  6587. else {
  6588. if (nameSpan)
  6589. nameSpan.setAttribute("style", "display:none;");
  6590. }
  6591. };
  6592. /**
  6593. * Shows the presence status message for the given video.
  6594. */
  6595. my.setPresenceStatus = function (videoSpanId, statusMsg) {
  6596. if (!$('#' + videoSpanId).length) {
  6597. // No container
  6598. return;
  6599. }
  6600. var statusSpan = $('#' + videoSpanId + '>span.status');
  6601. if (!statusSpan.length) {
  6602. //Add status span
  6603. statusSpan = document.createElement('span');
  6604. statusSpan.className = 'status';
  6605. statusSpan.id = videoSpanId + '_status';
  6606. $('#' + videoSpanId)[0].appendChild(statusSpan);
  6607. statusSpan = $('#' + videoSpanId + '>span.status');
  6608. }
  6609. // Display status
  6610. if (statusMsg && statusMsg.length) {
  6611. $('#' + videoSpanId + '_status').text(statusMsg);
  6612. statusSpan.get(0).setAttribute("style", "display:inline-block;");
  6613. }
  6614. else {
  6615. // Hide
  6616. statusSpan.get(0).setAttribute("style", "display:none;");
  6617. }
  6618. };
  6619. /**
  6620. * Shows a visual indicator for the moderator of the conference.
  6621. */
  6622. my.showModeratorIndicator = function () {
  6623. var isModerator = APP.xmpp.isModerator();
  6624. if (isModerator) {
  6625. var indicatorSpan = $('#localVideoContainer .focusindicator');
  6626. if (indicatorSpan.children().length === 0)
  6627. {
  6628. createModeratorIndicatorElement(indicatorSpan[0]);
  6629. //translates text in focus indicator
  6630. APP.translation.translateElement($('#localVideoContainer .focusindicator'));
  6631. }
  6632. }
  6633. var members = APP.xmpp.getMembers();
  6634. Object.keys(members).forEach(function (jid) {
  6635. if (Strophe.getResourceFromJid(jid) === 'focus') {
  6636. // Skip server side focus
  6637. return;
  6638. }
  6639. var resourceJid = Strophe.getResourceFromJid(jid);
  6640. var videoSpanId = 'participant_' + resourceJid;
  6641. var videoContainer = document.getElementById(videoSpanId);
  6642. if (!videoContainer) {
  6643. console.error("No video container for " + jid);
  6644. return;
  6645. }
  6646. var member = members[jid];
  6647. if (member.role === 'moderator') {
  6648. // Remove menu if peer is moderator
  6649. var menuSpan = $('#' + videoSpanId + '>span.remotevideomenu');
  6650. if (menuSpan.length) {
  6651. removeRemoteVideoMenu(videoSpanId);
  6652. }
  6653. // Show moderator indicator
  6654. var indicatorSpan
  6655. = $('#' + videoSpanId + ' .focusindicator');
  6656. if (!indicatorSpan || indicatorSpan.length === 0) {
  6657. indicatorSpan = document.createElement('span');
  6658. indicatorSpan.className = 'focusindicator';
  6659. videoContainer.appendChild(indicatorSpan);
  6660. createModeratorIndicatorElement(indicatorSpan);
  6661. //translates text in focus indicators
  6662. APP.translation.translateElement($('#' + videoSpanId + ' .focusindicator'));
  6663. }
  6664. } else if (isModerator) {
  6665. // We are moderator, but user is not - add menu
  6666. if ($('#remote_popupmenu_' + resourceJid).length <= 0) {
  6667. addRemoteVideoMenu(
  6668. jid,
  6669. document.getElementById('participant_' + resourceJid));
  6670. }
  6671. }
  6672. });
  6673. };
  6674. /**
  6675. * Shows video muted indicator over small videos.
  6676. */
  6677. my.showVideoIndicator = function(videoSpanId, isMuted) {
  6678. var videoMutedSpan = $('#' + videoSpanId + '>span.videoMuted');
  6679. if (isMuted === 'false') {
  6680. if (videoMutedSpan.length > 0) {
  6681. videoMutedSpan.remove();
  6682. }
  6683. }
  6684. else {
  6685. if(videoMutedSpan.length == 0) {
  6686. videoMutedSpan = document.createElement('span');
  6687. videoMutedSpan.className = 'videoMuted';
  6688. $('#' + videoSpanId)[0].appendChild(videoMutedSpan);
  6689. var mutedIndicator = document.createElement('i');
  6690. mutedIndicator.className = 'icon-camera-disabled';
  6691. UIUtil.setTooltip(mutedIndicator,
  6692. "videothumbnail.videomute",
  6693. "top");
  6694. videoMutedSpan.appendChild(mutedIndicator);
  6695. //translate texts for muted indicator
  6696. APP.translation.translateElement($('#' + videoSpanId + " > span > i"));
  6697. }
  6698. VideoLayout.updateMutePosition(videoSpanId);
  6699. }
  6700. };
  6701. my.updateMutePosition = function (videoSpanId) {
  6702. var audioMutedSpan = $('#' + videoSpanId + '>span.audioMuted');
  6703. var connectionIndicator = $('#' + videoSpanId + '>div.connectionindicator');
  6704. var videoMutedSpan = $('#' + videoSpanId + '>span.videoMuted');
  6705. if(connectionIndicator.length > 0
  6706. && connectionIndicator[0].style.display != "none") {
  6707. audioMutedSpan.css({right: "23px"});
  6708. videoMutedSpan.css({right: ((audioMutedSpan.length > 0? 23 : 0) + 30) + "px"});
  6709. }
  6710. else
  6711. {
  6712. audioMutedSpan.css({right: "0px"});
  6713. videoMutedSpan.css({right: (audioMutedSpan.length > 0? 30 : 0) + "px"});
  6714. }
  6715. }
  6716. /**
  6717. * Shows audio muted indicator over small videos.
  6718. * @param {string} isMuted
  6719. */
  6720. my.showAudioIndicator = function(videoSpanId, isMuted) {
  6721. var audioMutedSpan = $('#' + videoSpanId + '>span.audioMuted');
  6722. if (isMuted === 'false') {
  6723. if (audioMutedSpan.length > 0) {
  6724. audioMutedSpan.popover('hide');
  6725. audioMutedSpan.remove();
  6726. }
  6727. }
  6728. else {
  6729. if(audioMutedSpan.length == 0 ) {
  6730. audioMutedSpan = document.createElement('span');
  6731. audioMutedSpan.className = 'audioMuted';
  6732. UIUtil.setTooltip(audioMutedSpan,
  6733. "videothumbnail.mute",
  6734. "top");
  6735. $('#' + videoSpanId)[0].appendChild(audioMutedSpan);
  6736. APP.translation.translateElement($('#' + videoSpanId + " > span"));
  6737. var mutedIndicator = document.createElement('i');
  6738. mutedIndicator.className = 'icon-mic-disabled';
  6739. audioMutedSpan.appendChild(mutedIndicator);
  6740. }
  6741. VideoLayout.updateMutePosition(videoSpanId);
  6742. }
  6743. };
  6744. /*
  6745. * Shows or hides the audio muted indicator over the local thumbnail video.
  6746. * @param {boolean} isMuted
  6747. */
  6748. my.showLocalAudioIndicator = function(isMuted) {
  6749. VideoLayout.showAudioIndicator('localVideoContainer', isMuted.toString());
  6750. };
  6751. /**
  6752. * Resizes the large video container.
  6753. */
  6754. my.resizeLargeVideoContainer = function () {
  6755. Chat.resizeChat();
  6756. var availableHeight = window.innerHeight;
  6757. var availableWidth = UIUtil.getAvailableVideoWidth();
  6758. if (availableWidth < 0 || availableHeight < 0) return;
  6759. $('#videospace').width(availableWidth);
  6760. $('#videospace').height(availableHeight);
  6761. $('#largeVideoContainer').width(availableWidth);
  6762. $('#largeVideoContainer').height(availableHeight);
  6763. var avatarSize = interfaceConfig.ACTIVE_SPEAKER_AVATAR_SIZE;
  6764. var top = availableHeight / 2 - avatarSize / 4 * 3;
  6765. $('#activeSpeaker').css('top', top);
  6766. VideoLayout.resizeThumbnails();
  6767. };
  6768. /**
  6769. * Resizes thumbnails.
  6770. */
  6771. my.resizeThumbnails = function() {
  6772. var videoSpaceWidth = $('#remoteVideos').width();
  6773. var thumbnailSize = VideoLayout.calculateThumbnailSize(videoSpaceWidth);
  6774. var width = thumbnailSize[0];
  6775. var height = thumbnailSize[1];
  6776. // size videos so that while keeping AR and max height, we have a
  6777. // nice fit
  6778. $('#remoteVideos').height(height);
  6779. $('#remoteVideos>span').width(width);
  6780. $('#remoteVideos>span').height(height);
  6781. $('.userAvatar').css('left', (width - height) / 2);
  6782. $(document).trigger("remotevideo.resized", [width, height]);
  6783. };
  6784. /**
  6785. * Enables the dominant speaker UI.
  6786. *
  6787. * @param resourceJid the jid indicating the video element to
  6788. * activate/deactivate
  6789. * @param isEnable indicates if the dominant speaker should be enabled or
  6790. * disabled
  6791. */
  6792. my.enableDominantSpeaker = function(resourceJid, isEnable) {
  6793. var videoSpanId = null;
  6794. var videoContainerId = null;
  6795. if (resourceJid
  6796. === APP.xmpp.myResource()) {
  6797. videoSpanId = 'localVideoWrapper';
  6798. videoContainerId = 'localVideoContainer';
  6799. }
  6800. else {
  6801. videoSpanId = 'participant_' + resourceJid;
  6802. videoContainerId = videoSpanId;
  6803. }
  6804. var displayName = resourceJid;
  6805. var nameSpan = $('#' + videoContainerId + '>span.displayname');
  6806. if (nameSpan.length > 0)
  6807. displayName = nameSpan.html();
  6808. console.log("UI enable dominant speaker",
  6809. displayName,
  6810. resourceJid,
  6811. isEnable);
  6812. videoSpan = document.getElementById(videoContainerId);
  6813. if (!videoSpan) {
  6814. return;
  6815. }
  6816. var video = $('#' + videoSpanId + '>video');
  6817. if (video && video.length > 0) {
  6818. if (isEnable) {
  6819. var isLargeVideoVisible = VideoLayout.isLargeVideoOnTop();
  6820. VideoLayout.showDisplayName(videoContainerId, isLargeVideoVisible);
  6821. if (!videoSpan.classList.contains("dominantspeaker"))
  6822. videoSpan.classList.add("dominantspeaker");
  6823. }
  6824. else {
  6825. VideoLayout.showDisplayName(videoContainerId, false);
  6826. if (videoSpan.classList.contains("dominantspeaker"))
  6827. videoSpan.classList.remove("dominantspeaker");
  6828. }
  6829. Avatar.showUserAvatar(
  6830. APP.xmpp.findJidFromResource(resourceJid));
  6831. }
  6832. };
  6833. /**
  6834. * Calculates the thumbnail size.
  6835. *
  6836. * @param videoSpaceWidth the width of the video space
  6837. */
  6838. my.calculateThumbnailSize = function (videoSpaceWidth) {
  6839. // Calculate the available height, which is the inner window height minus
  6840. // 39px for the header minus 2px for the delimiter lines on the top and
  6841. // bottom of the large video, minus the 36px space inside the remoteVideos
  6842. // container used for highlighting shadow.
  6843. var availableHeight = 100;
  6844. var numvids = $('#remoteVideos>span:visible').length;
  6845. if (localLastNCount && localLastNCount > 0) {
  6846. numvids = Math.min(localLastNCount + 1, numvids);
  6847. }
  6848. // Remove the 3px borders arround videos and border around the remote
  6849. // videos area and the 4 pixels between the local video and the others
  6850. //TODO: Find out where the 4 pixels come from and remove them
  6851. var availableWinWidth = videoSpaceWidth - 2 * 3 * numvids - 70 - 4;
  6852. var availableWidth = availableWinWidth / numvids;
  6853. var aspectRatio = 16.0 / 9.0;
  6854. var maxHeight = Math.min(160, availableHeight);
  6855. availableHeight = Math.min(maxHeight, availableWidth / aspectRatio);
  6856. if (availableHeight < availableWidth / aspectRatio) {
  6857. availableWidth = Math.floor(availableHeight * aspectRatio);
  6858. }
  6859. return [availableWidth, availableHeight];
  6860. };
  6861. /**
  6862. * Updates the remote video menu.
  6863. *
  6864. * @param jid the jid indicating the video for which we're adding a menu.
  6865. * @param isMuted indicates the current mute state
  6866. */
  6867. my.updateRemoteVideoMenu = function(jid, isMuted) {
  6868. var muteMenuItem
  6869. = $('#remote_popupmenu_'
  6870. + Strophe.getResourceFromJid(jid)
  6871. + '>li>a.mutelink');
  6872. var mutedIndicator = "<i class='icon-mic-disabled'></i>";
  6873. if (muteMenuItem.length) {
  6874. var muteLink = muteMenuItem.get(0);
  6875. if (isMuted === 'true') {
  6876. muteLink.innerHTML = mutedIndicator + ' Muted';
  6877. muteLink.className = 'mutelink disabled';
  6878. }
  6879. else {
  6880. muteLink.innerHTML = mutedIndicator + ' Mute';
  6881. muteLink.className = 'mutelink';
  6882. }
  6883. }
  6884. };
  6885. /**
  6886. * Returns the current dominant speaker resource jid.
  6887. */
  6888. my.getDominantSpeakerResourceJid = function () {
  6889. return currentDominantSpeaker;
  6890. };
  6891. /**
  6892. * Returns the corresponding resource jid to the given peer container
  6893. * DOM element.
  6894. *
  6895. * @return the corresponding resource jid to the given peer container
  6896. * DOM element
  6897. */
  6898. my.getPeerContainerResourceJid = function (containerElement) {
  6899. var i = containerElement.id.indexOf('participant_');
  6900. if (i >= 0)
  6901. return containerElement.id.substring(i + 12);
  6902. };
  6903. /**
  6904. * On contact list item clicked.
  6905. */
  6906. $(ContactList).bind('contactclicked', function(event, jid) {
  6907. if (!jid) {
  6908. return;
  6909. }
  6910. var resource = Strophe.getResourceFromJid(jid);
  6911. var videoContainer = $("#participant_" + resource);
  6912. if (videoContainer.length > 0) {
  6913. var videoThumb = $('video', videoContainer).get(0);
  6914. // It is not always the case that a videoThumb exists (if there is
  6915. // no actual video).
  6916. if (videoThumb) {
  6917. if (videoThumb.src && videoThumb.src != '') {
  6918. // We have a video src, great! Let's update the large video
  6919. // now.
  6920. VideoLayout.handleVideoThumbClicked(
  6921. videoThumb.src,
  6922. false,
  6923. Strophe.getResourceFromJid(jid));
  6924. } else {
  6925. // If we don't have a video src for jid, there's absolutely
  6926. // no point in calling handleVideoThumbClicked; Quite
  6927. // simply, it won't work because it needs an src to attach
  6928. // to the large video.
  6929. //
  6930. // Instead, we trigger the pinned endpoint changed event to
  6931. // let the bridge adjust its lastN set for myjid and store
  6932. // the pinned user in the lastNPickupJid variable to be
  6933. // picked up later by the lastN changed event handler.
  6934. lastNPickupJid = jid;
  6935. eventEmitter.emit(UIEvents.PINNED_ENDPOINT,
  6936. Strophe.getResourceFromJid(jid));
  6937. }
  6938. } else if (jid == APP.xmpp.myJid()) {
  6939. $("#localVideoContainer").click();
  6940. }
  6941. }
  6942. });
  6943. /**
  6944. * On audio muted event.
  6945. */
  6946. $(document).bind('audiomuted.muc', function (event, jid, isMuted) {
  6947. /*
  6948. // FIXME: but focus can not mute in this case ? - check
  6949. if (jid === xmpp.myJid()) {
  6950. // The local mute indicator is controlled locally
  6951. return;
  6952. }*/
  6953. var videoSpanId = null;
  6954. if (jid === APP.xmpp.myJid()) {
  6955. videoSpanId = 'localVideoContainer';
  6956. } else {
  6957. VideoLayout.ensurePeerContainerExists(jid);
  6958. videoSpanId = 'participant_' + Strophe.getResourceFromJid(jid);
  6959. }
  6960. mutedAudios[jid] = isMuted;
  6961. if (APP.xmpp.isModerator()) {
  6962. VideoLayout.updateRemoteVideoMenu(jid, isMuted);
  6963. }
  6964. if (videoSpanId)
  6965. VideoLayout.showAudioIndicator(videoSpanId, isMuted);
  6966. });
  6967. /**
  6968. * On video muted event.
  6969. */
  6970. $(document).bind('videomuted.muc', function (event, jid, value) {
  6971. var isMuted = (value === "true");
  6972. if(!APP.RTC.muteRemoteVideoStream(jid, isMuted))
  6973. return;
  6974. Avatar.showUserAvatar(jid, isMuted);
  6975. var videoSpanId = null;
  6976. if (jid === APP.xmpp.myJid()) {
  6977. videoSpanId = 'localVideoContainer';
  6978. } else {
  6979. VideoLayout.ensurePeerContainerExists(jid);
  6980. videoSpanId = 'participant_' + Strophe.getResourceFromJid(jid);
  6981. }
  6982. if (videoSpanId)
  6983. VideoLayout.showVideoIndicator(videoSpanId, value);
  6984. });
  6985. /**
  6986. * Display name changed.
  6987. */
  6988. my.onDisplayNameChanged =
  6989. function (jid, displayName, status) {
  6990. if (jid === 'localVideoContainer'
  6991. || jid === APP.xmpp.myJid()) {
  6992. setDisplayName('localVideoContainer',
  6993. displayName);
  6994. } else {
  6995. VideoLayout.ensurePeerContainerExists(jid);
  6996. setDisplayName(
  6997. 'participant_' + Strophe.getResourceFromJid(jid),
  6998. displayName,
  6999. status);
  7000. }
  7001. };
  7002. /**
  7003. * On dominant speaker changed event.
  7004. */
  7005. my.onDominantSpeakerChanged = function (resourceJid) {
  7006. // We ignore local user events.
  7007. if (resourceJid
  7008. === APP.xmpp.myResource())
  7009. return;
  7010. var members = APP.xmpp.getMembers();
  7011. // Update the current dominant speaker.
  7012. if (resourceJid !== currentDominantSpeaker) {
  7013. var oldSpeakerVideoSpanId = "participant_" + currentDominantSpeaker,
  7014. newSpeakerVideoSpanId = "participant_" + resourceJid;
  7015. var currentJID = APP.xmpp.findJidFromResource(currentDominantSpeaker);
  7016. var newJID = APP.xmpp.findJidFromResource(resourceJid);
  7017. if(currentDominantSpeaker && (!members || !members[currentJID] ||
  7018. !members[currentJID].displayName)) {
  7019. setDisplayName(oldSpeakerVideoSpanId, null);
  7020. }
  7021. if(resourceJid && (!members || !members[newJID] ||
  7022. !members[newJID].displayName)) {
  7023. setDisplayName(newSpeakerVideoSpanId, null,
  7024. interfaceConfig.DEFAULT_DOMINANT_SPEAKER_DISPLAY_NAME);
  7025. }
  7026. currentDominantSpeaker = resourceJid;
  7027. } else {
  7028. return;
  7029. }
  7030. // Obtain container for new dominant speaker.
  7031. var container = document.getElementById(
  7032. 'participant_' + resourceJid);
  7033. // Local video will not have container found, but that's ok
  7034. // since we don't want to switch to local video.
  7035. if (container && !focusedVideoInfo)
  7036. {
  7037. var video = container.getElementsByTagName("video");
  7038. // Update the large video if the video source is already available,
  7039. // otherwise wait for the "videoactive.jingle" event.
  7040. if (video.length && video[0].currentTime > 0)
  7041. VideoLayout.updateLargeVideo(APP.RTC.getVideoSrc(video[0]), resourceJid);
  7042. }
  7043. };
  7044. /**
  7045. * On last N change event.
  7046. *
  7047. * @param lastNEndpoints the list of last N endpoints
  7048. * @param endpointsEnteringLastN the list currently entering last N
  7049. * endpoints
  7050. */
  7051. my.onLastNEndpointsChanged = function ( lastNEndpoints,
  7052. endpointsEnteringLastN,
  7053. stream) {
  7054. if (lastNCount !== lastNEndpoints.length)
  7055. lastNCount = lastNEndpoints.length;
  7056. lastNEndpointsCache = lastNEndpoints;
  7057. // Say A, B, C, D, E, and F are in a conference and LastN = 3.
  7058. //
  7059. // If LastN drops to, say, 2, because of adaptivity, then E should see
  7060. // thumbnails for A, B and C. A and B are in E's server side LastN set,
  7061. // so E sees them. C is only in E's local LastN set.
  7062. //
  7063. // If F starts talking and LastN = 3, then E should see thumbnails for
  7064. // F, A, B. B gets "ejected" from E's server side LastN set, but it
  7065. // enters E's local LastN ejecting C.
  7066. // Increase the local LastN set size, if necessary.
  7067. if (lastNCount > localLastNCount) {
  7068. localLastNCount = lastNCount;
  7069. }
  7070. // Update the local LastN set preserving the order in which the
  7071. // endpoints appeared in the LastN/local LastN set.
  7072. var nextLocalLastNSet = lastNEndpoints.slice(0);
  7073. for (var i = 0; i < localLastNSet.length; i++) {
  7074. if (nextLocalLastNSet.length >= localLastNCount) {
  7075. break;
  7076. }
  7077. var resourceJid = localLastNSet[i];
  7078. if (nextLocalLastNSet.indexOf(resourceJid) === -1) {
  7079. nextLocalLastNSet.push(resourceJid);
  7080. }
  7081. }
  7082. localLastNSet = nextLocalLastNSet;
  7083. var updateLargeVideo = false;
  7084. // Handle LastN/local LastN changes.
  7085. $('#remoteVideos>span').each(function( index, element ) {
  7086. var resourceJid = VideoLayout.getPeerContainerResourceJid(element);
  7087. var isReceived = true;
  7088. if (resourceJid
  7089. && lastNEndpoints.indexOf(resourceJid) < 0
  7090. && localLastNSet.indexOf(resourceJid) < 0) {
  7091. console.log("Remove from last N", resourceJid);
  7092. showPeerContainer(resourceJid, 'hide');
  7093. isReceived = false;
  7094. } else if (resourceJid
  7095. && $('#participant_' + resourceJid).is(':visible')
  7096. && lastNEndpoints.indexOf(resourceJid) < 0
  7097. && localLastNSet.indexOf(resourceJid) >= 0) {
  7098. showPeerContainer(resourceJid, 'avatar');
  7099. isReceived = false;
  7100. }
  7101. if (!isReceived) {
  7102. // resourceJid has dropped out of the server side lastN set, so
  7103. // it is no longer being received. If resourceJid was being
  7104. // displayed in the large video we have to switch to another
  7105. // user.
  7106. var largeVideoResource = largeVideoState.userResourceJid;
  7107. if (!updateLargeVideo && resourceJid === largeVideoResource) {
  7108. updateLargeVideo = true;
  7109. }
  7110. }
  7111. });
  7112. if (!endpointsEnteringLastN || endpointsEnteringLastN.length < 0)
  7113. endpointsEnteringLastN = lastNEndpoints;
  7114. if (endpointsEnteringLastN && endpointsEnteringLastN.length > 0) {
  7115. endpointsEnteringLastN.forEach(function (resourceJid) {
  7116. var isVisible = $('#participant_' + resourceJid).is(':visible');
  7117. showPeerContainer(resourceJid, 'show');
  7118. if (!isVisible) {
  7119. console.log("Add to last N", resourceJid);
  7120. var jid = APP.xmpp.findJidFromResource(resourceJid);
  7121. var mediaStream = APP.RTC.remoteStreams[jid][MediaStreamType.VIDEO_TYPE];
  7122. var sel = $('#participant_' + resourceJid + '>video');
  7123. var videoStream = APP.simulcast.getReceivingVideoStream(
  7124. mediaStream.stream);
  7125. APP.RTC.attachMediaStream(sel, videoStream);
  7126. if (lastNPickupJid == mediaStream.peerjid) {
  7127. // Clean up the lastN pickup jid.
  7128. lastNPickupJid = null;
  7129. // Don't fire the events again, they've already
  7130. // been fired in the contact list click handler.
  7131. VideoLayout.handleVideoThumbClicked(
  7132. $(sel).attr('src'),
  7133. false,
  7134. Strophe.getResourceFromJid(mediaStream.peerjid));
  7135. updateLargeVideo = false;
  7136. }
  7137. waitForRemoteVideo(sel, mediaStream.ssrc, mediaStream.stream, resourceJid);
  7138. }
  7139. })
  7140. }
  7141. // The endpoint that was being shown in the large video has dropped out
  7142. // of the lastN set and there was no lastN pickup jid. We need to update
  7143. // the large video now.
  7144. if (updateLargeVideo) {
  7145. var resource, container, src;
  7146. var myResource
  7147. = APP.xmpp.myResource();
  7148. // Find out which endpoint to show in the large video.
  7149. for (var i = 0; i < lastNEndpoints.length; i++) {
  7150. resource = lastNEndpoints[i];
  7151. if (!resource || resource === myResource)
  7152. continue;
  7153. container = $("#participant_" + resource);
  7154. if (container.length == 0)
  7155. continue;
  7156. src = $('video', container).attr('src');
  7157. if (!src)
  7158. continue;
  7159. // videoSrcToSsrc needs to be update for this call to succeed.
  7160. VideoLayout.updateLargeVideo(src);
  7161. break;
  7162. }
  7163. }
  7164. };
  7165. my.onSimulcastLayersChanging = function (endpointSimulcastLayers) {
  7166. endpointSimulcastLayers.forEach(function (esl) {
  7167. var resource = esl.endpoint;
  7168. // if lastN is enabled *and* the endpoint is *not* in the lastN set,
  7169. // then ignore the event (= do not preload anything).
  7170. //
  7171. // The bridge could probably stop sending this message if it's for
  7172. // an endpoint that's not in lastN.
  7173. if (lastNCount != -1
  7174. && (lastNCount < 1 || lastNEndpointsCache.indexOf(resource) === -1)) {
  7175. return;
  7176. }
  7177. var primarySSRC = esl.simulcastLayer.primarySSRC;
  7178. // Get session and stream from primary ssrc.
  7179. var res = APP.simulcast.getReceivingVideoStreamBySSRC(primarySSRC);
  7180. var sid = res.sid;
  7181. var electedStream = res.stream;
  7182. if (sid && electedStream) {
  7183. var msid = APP.simulcast.getRemoteVideoStreamIdBySSRC(primarySSRC);
  7184. console.info([esl, primarySSRC, msid, sid, electedStream]);
  7185. var preload = (Strophe.getResourceFromJid(APP.xmpp.getJidFromSSRC(primarySSRC)) == largeVideoState.userResourceJid);
  7186. if (preload) {
  7187. if (largeVideoState.preload)
  7188. {
  7189. $(largeVideoState.preload).remove();
  7190. }
  7191. console.info('Preloading remote video');
  7192. largeVideoState.preload = $('<video autoplay></video>');
  7193. // ssrcs are unique in an rtp session
  7194. largeVideoState.preload_ssrc = primarySSRC;
  7195. APP.RTC.attachMediaStream(largeVideoState.preload, electedStream)
  7196. }
  7197. } else {
  7198. console.error('Could not find a stream or a session.', sid, electedStream);
  7199. }
  7200. });
  7201. };
  7202. /**
  7203. * On simulcast layers changed event.
  7204. */
  7205. my.onSimulcastLayersChanged = function (endpointSimulcastLayers) {
  7206. endpointSimulcastLayers.forEach(function (esl) {
  7207. var resource = esl.endpoint;
  7208. // if lastN is enabled *and* the endpoint is *not* in the lastN set,
  7209. // then ignore the event (= do not change large video/thumbnail
  7210. // SRCs).
  7211. //
  7212. // Note that even if we ignore the "changed" event in this event
  7213. // handler, the bridge must continue sending these events because
  7214. // the simulcast code in simulcast.js uses it to know what's going
  7215. // to be streamed by the bridge when/if the endpoint gets back into
  7216. // the lastN set.
  7217. if (lastNCount != -1
  7218. && (lastNCount < 1 || lastNEndpointsCache.indexOf(resource) === -1)) {
  7219. return;
  7220. }
  7221. var primarySSRC = esl.simulcastLayer.primarySSRC;
  7222. // Get session and stream from primary ssrc.
  7223. var res = APP.simulcast.getReceivingVideoStreamBySSRC(primarySSRC);
  7224. var sid = res.sid;
  7225. var electedStream = res.stream;
  7226. if (sid && electedStream) {
  7227. var msid = APP.simulcast.getRemoteVideoStreamIdBySSRC(primarySSRC);
  7228. console.info('Switching simulcast substream.');
  7229. console.info([esl, primarySSRC, msid, sid, electedStream]);
  7230. var msidParts = msid.split(' ');
  7231. var selRemoteVideo = $(['#', 'remoteVideo_', sid, '_', msidParts[0]].join(''));
  7232. var updateLargeVideo = (Strophe.getResourceFromJid(APP.xmpp.getJidFromSSRC(primarySSRC))
  7233. == largeVideoState.userResourceJid);
  7234. var updateFocusedVideoSrc = (focusedVideoInfo && focusedVideoInfo.src && focusedVideoInfo.src != '' &&
  7235. (APP.RTC.getVideoSrc(selRemoteVideo[0]) == focusedVideoInfo.src));
  7236. var electedStreamUrl;
  7237. if (largeVideoState.preload_ssrc == primarySSRC)
  7238. {
  7239. APP.RTC.setVideoSrc(selRemoteVideo[0], APP.RTC.getVideoSrc(largeVideoState.preload[0]));
  7240. }
  7241. else
  7242. {
  7243. if (largeVideoState.preload
  7244. && largeVideoState.preload != null) {
  7245. $(largeVideoState.preload).remove();
  7246. }
  7247. largeVideoState.preload_ssrc = 0;
  7248. APP.RTC.attachMediaStream(selRemoteVideo, electedStream);
  7249. }
  7250. var jid = APP.xmpp.getJidFromSSRC(primarySSRC);
  7251. if (updateLargeVideo) {
  7252. VideoLayout.updateLargeVideo(APP.RTC.getVideoSrc(selRemoteVideo[0]), null,
  7253. Strophe.getResourceFromJid(jid));
  7254. }
  7255. if (updateFocusedVideoSrc) {
  7256. focusedVideoInfo.src = APP.RTC.getVideoSrc(selRemoteVideo[0]);
  7257. }
  7258. var videoId;
  7259. if(resource == APP.xmpp.myResource())
  7260. {
  7261. videoId = "localVideoContainer";
  7262. }
  7263. else
  7264. {
  7265. videoId = "participant_" + resource;
  7266. }
  7267. var connectionIndicator = VideoLayout.connectionIndicators[videoId];
  7268. if(connectionIndicator)
  7269. connectionIndicator.updatePopoverData();
  7270. } else {
  7271. console.error('Could not find a stream or a sid.', sid, electedStream);
  7272. }
  7273. });
  7274. };
  7275. /**
  7276. * Updates local stats
  7277. * @param percent
  7278. * @param object
  7279. */
  7280. my.updateLocalConnectionStats = function (percent, object) {
  7281. var resolution = null;
  7282. if(object.resolution !== null)
  7283. {
  7284. resolution = object.resolution;
  7285. object.resolution = resolution[APP.xmpp.myJid()];
  7286. delete resolution[APP.xmpp.myJid()];
  7287. }
  7288. updateStatsIndicator("localVideoContainer", percent, object);
  7289. for(var jid in resolution)
  7290. {
  7291. if(resolution[jid] === null)
  7292. continue;
  7293. var id = 'participant_' + Strophe.getResourceFromJid(jid);
  7294. if(VideoLayout.connectionIndicators[id])
  7295. {
  7296. VideoLayout.connectionIndicators[id].updateResolution(resolution[jid]);
  7297. }
  7298. }
  7299. };
  7300. /**
  7301. * Updates remote stats.
  7302. * @param jid the jid associated with the stats
  7303. * @param percent the connection quality percent
  7304. * @param object the stats data
  7305. */
  7306. my.updateConnectionStats = function (jid, percent, object) {
  7307. var resourceJid = Strophe.getResourceFromJid(jid);
  7308. var videoSpanId = 'participant_' + resourceJid;
  7309. updateStatsIndicator(videoSpanId, percent, object);
  7310. };
  7311. /**
  7312. * Removes the connection
  7313. * @param jid
  7314. */
  7315. my.removeConnectionIndicator = function (jid) {
  7316. if(VideoLayout.connectionIndicators['participant_' + Strophe.getResourceFromJid(jid)])
  7317. VideoLayout.connectionIndicators['participant_' + Strophe.getResourceFromJid(jid)].remove();
  7318. };
  7319. /**
  7320. * Hides the connection indicator
  7321. * @param jid
  7322. */
  7323. my.hideConnectionIndicator = function (jid) {
  7324. if(VideoLayout.connectionIndicators['participant_' + Strophe.getResourceFromJid(jid)])
  7325. VideoLayout.connectionIndicators['participant_' + Strophe.getResourceFromJid(jid)].hide();
  7326. };
  7327. /**
  7328. * Hides all the indicators
  7329. */
  7330. my.onStatsStop = function () {
  7331. for(var indicator in VideoLayout.connectionIndicators)
  7332. {
  7333. VideoLayout.connectionIndicators[indicator].hideIndicator();
  7334. }
  7335. };
  7336. my.participantLeft = function (jid) {
  7337. // Unlock large video
  7338. if (focusedVideoInfo && focusedVideoInfo.jid === jid)
  7339. {
  7340. console.info("Focused video owner has left the conference");
  7341. focusedVideoInfo = null;
  7342. }
  7343. }
  7344. return my;
  7345. }(VideoLayout || {}));
  7346. module.exports = VideoLayout;
  7347. },{"../../../service/RTC/MediaStreamTypes":86,"../../../service/UI/UIEvents":91,"../audio_levels/AudioLevels":9,"../avatar/Avatar":12,"../etherpad/Etherpad":13,"../prezi/Prezi":14,"../side_pannels/chat/Chat":17,"../side_pannels/contactlist/ContactList":21,"../util/NicknameHandler":28,"../util/UIUtil":29,"./ConnectionIndicator":30}],32:[function(require,module,exports){
  7348. //var nouns = [
  7349. //];
  7350. var pluralNouns = [
  7351. "Aliens", "Animals", "Antelopes", "Ants", "Apes", "Apples", "Baboons", "Bacteria", "Badgers", "Bananas", "Bats",
  7352. "Bears", "Birds", "Bonobos", "Brides", "Bugs", "Bulls", "Butterflies", "Cheetahs",
  7353. "Cherries", "Chicken", "Children", "Chimps", "Clowns", "Cows", "Creatures", "Dinosaurs", "Dogs", "Dolphins",
  7354. "Donkeys", "Dragons", "Ducks", "Dwarfs", "Eagles", "Elephants", "Elves", "FAIL", "Fathers",
  7355. "Fish", "Flowers", "Frogs", "Fruit", "Fungi", "Galaxies", "Geese", "Goats",
  7356. "Gorillas", "Hedgehogs", "Hippos", "Horses", "Hunters", "Insects", "Kids", "Knights",
  7357. "Lemons", "Lemurs", "Leopards", "LifeForms", "Lions", "Lizards", "Mice", "Monkeys", "Monsters",
  7358. "Mushrooms", "Octopodes", "Oranges", "Orangutans", "Organisms", "Pants", "Parrots", "Penguins",
  7359. "People", "Pigeons", "Pigs", "Pineapples", "Plants", "Potatoes", "Priests", "Rats", "Reptiles", "Reptilians",
  7360. "Rhinos", "Seagulls", "Sheep", "Siblings", "Snakes", "Spaghetti", "Spiders", "Squid", "Squirrels",
  7361. "Stars", "Students", "Teachers", "Tigers", "Tomatoes", "Trees", "Vampires", "Vegetables", "Viruses", "Vulcans",
  7362. "Warewolves", "Weasels", "Whales", "Witches", "Wizards", "Wolves", "Workers", "Worms", "Zebras"
  7363. ];
  7364. //var places = [
  7365. //"Pub", "University", "Airport", "Library", "Mall", "Theater", "Stadium", "Office", "Show", "Gallows", "Beach",
  7366. // "Cemetery", "Hospital", "Reception", "Restaurant", "Bar", "Church", "House", "School", "Square", "Village",
  7367. // "Cinema", "Movies", "Party", "Restroom", "End", "Jail", "PostOffice", "Station", "Circus", "Gates", "Entrance",
  7368. // "Bridge"
  7369. //];
  7370. var verbs = [
  7371. "Abandon", "Adapt", "Advertise", "Answer", "Anticipate", "Appreciate",
  7372. "Approach", "Argue", "Ask", "Bite", "Blossom", "Blush", "Breathe", "Breed", "Bribe", "Burn", "Calculate",
  7373. "Clean", "Code", "Communicate", "Compute", "Confess", "Confiscate", "Conjugate", "Conjure", "Consume",
  7374. "Contemplate", "Crawl", "Dance", "Delegate", "Devour", "Develop", "Differ", "Discuss",
  7375. "Dissolve", "Drink", "Eat", "Elaborate", "Emancipate", "Estimate", "Expire", "Extinguish",
  7376. "Extract", "FAIL", "Facilitate", "Fall", "Feed", "Finish", "Floss", "Fly", "Follow", "Fragment", "Freeze",
  7377. "Gather", "Glow", "Grow", "Hex", "Hide", "Hug", "Hurry", "Improve", "Intersect", "Investigate", "Jinx",
  7378. "Joke", "Jubilate", "Kiss", "Laugh", "Manage", "Meet", "Merge", "Move", "Object", "Observe", "Offer",
  7379. "Paint", "Participate", "Party", "Perform", "Plan", "Pursue", "Pierce", "Play", "Postpone", "Pray", "Proclaim",
  7380. "Question", "Read", "Reckon", "Rejoice", "Represent", "Resize", "Rhyme", "Scream", "Search", "Select", "Share", "Shoot",
  7381. "Shout", "Signal", "Sing", "Skate", "Sleep", "Smile", "Smoke", "Solve", "Spell", "Steer", "Stink",
  7382. "Substitute", "Swim", "Taste", "Teach", "Terminate", "Think", "Type", "Unite", "Vanish", "Worship"
  7383. ];
  7384. var adverbs = [
  7385. "Absently", "Accurately", "Accusingly", "Adorably", "AllTheTime", "Alone", "Always", "Amazingly", "Angrily",
  7386. "Anxiously", "Anywhere", "Appallingly", "Apparently", "Articulately", "Astonishingly", "Badly", "Barely",
  7387. "Beautifully", "Blindly", "Bravely", "Brightly", "Briskly", "Brutally", "Calmly", "Carefully", "Casually",
  7388. "Cautiously", "Cleverly", "Constantly", "Correctly", "Crazily", "Curiously", "Cynically", "Daily",
  7389. "Dangerously", "Deliberately", "Delicately", "Desperately", "Discreetly", "Eagerly", "Easily", "Euphoricly",
  7390. "Evenly", "Everywhere", "Exactly", "Expectantly", "Extensively", "FAIL", "Ferociously", "Fiercely", "Finely",
  7391. "Flatly", "Frequently", "Frighteningly", "Gently", "Gloriously", "Grimly", "Guiltily", "Happily",
  7392. "Hard", "Hastily", "Heroically", "High", "Highly", "Hourly", "Humbly", "Hysterically", "Immensely",
  7393. "Impartially", "Impolitely", "Indifferently", "Intensely", "Jealously", "Jovially", "Kindly", "Lazily",
  7394. "Lightly", "Loudly", "Lovingly", "Loyally", "Magnificently", "Malevolently", "Merrily", "Mightily", "Miserably",
  7395. "Mysteriously", "NOT", "Nervously", "Nicely", "Nowhere", "Objectively", "Obnoxiously", "Obsessively",
  7396. "Obviously", "Often", "Painfully", "Patiently", "Playfully", "Politely", "Poorly", "Precisely", "Promptly",
  7397. "Quickly", "Quietly", "Randomly", "Rapidly", "Rarely", "Recklessly", "Regularly", "Remorsefully", "Responsibly",
  7398. "Rudely", "Ruthlessly", "Sadly", "Scornfully", "Seamlessly", "Seldom", "Selfishly", "Seriously", "Shakily",
  7399. "Sharply", "Sideways", "Silently", "Sleepily", "Slightly", "Slowly", "Slyly", "Smoothly", "Softly", "Solemnly", "Steadily", "Sternly", "Strangely", "Strongly", "Stunningly", "Surely", "Tenderly", "Thoughtfully",
  7400. "Tightly", "Uneasily", "Vanishingly", "Violently", "Warmly", "Weakly", "Wearily", "Weekly", "Weirdly", "Well",
  7401. "Well", "Wickedly", "Wildly", "Wisely", "Wonderfully", "Yearly"
  7402. ];
  7403. var adjectives = [
  7404. "Abominable", "Accurate", "Adorable", "All", "Alleged", "Ancient", "Angry", "Angry", "Anxious", "Appalling",
  7405. "Apparent", "Astonishing", "Attractive", "Awesome", "Baby", "Bad", "Beautiful", "Benign", "Big", "Bitter",
  7406. "Blind", "Blue", "Bold", "Brave", "Bright", "Brisk", "Calm", "Camouflaged", "Casual", "Cautious",
  7407. "Choppy", "Chosen", "Clever", "Cold", "Cool", "Crawly", "Crazy", "Creepy", "Cruel", "Curious", "Cynical",
  7408. "Dangerous", "Dark", "Delicate", "Desperate", "Difficult", "Discreet", "Disguised", "Dizzy",
  7409. "Dumb", "Eager", "Easy", "Edgy", "Electric", "Elegant", "Emancipated", "Enormous", "Euphoric", "Evil",
  7410. "FAIL", "Fast", "Ferocious", "Fierce", "Fine", "Flawed", "Flying", "Foolish", "Foxy",
  7411. "Freezing", "Funny", "Furious", "Gentle", "Glorious", "Golden", "Good", "Green", "Green", "Guilty",
  7412. "Hairy", "Happy", "Hard", "Hasty", "Hazy", "Heroic", "Hostile", "Hot", "Humble", "Humongous",
  7413. "Humorous", "Hysterical", "Idealistic", "Ignorant", "Immense", "Impartial", "Impolite", "Indifferent",
  7414. "Infuriated", "Insightful", "Intense", "Interesting", "Intimidated", "Intriguing", "Jealous", "Jolly", "Jovial",
  7415. "Jumpy", "Kind", "Laughing", "Lazy", "Liquid", "Lonely", "Longing", "Loud", "Loving", "Loyal", "Macabre", "Mad",
  7416. "Magical", "Magnificent", "Malevolent", "Medieval", "Memorable", "Mere", "Merry", "Mighty",
  7417. "Mischievous", "Miserable", "Modified", "Moody", "Most", "Mysterious", "Mystical", "Needy",
  7418. "Nervous", "Nice", "Objective", "Obnoxious", "Obsessive", "Obvious", "Opinionated", "Orange",
  7419. "Painful", "Passionate", "Perfect", "Pink", "Playful", "Poisonous", "Polite", "Poor", "Popular", "Powerful",
  7420. "Precise", "Preserved", "Pretty", "Purple", "Quick", "Quiet", "Random", "Rapid", "Rare", "Real",
  7421. "Reassuring", "Reckless", "Red", "Regular", "Remorseful", "Responsible", "Rich", "Rude", "Ruthless",
  7422. "Sad", "Scared", "Scary", "Scornful", "Screaming", "Selfish", "Serious", "Shady", "Shaky", "Sharp",
  7423. "Shiny", "Shy", "Simple", "Sleepy", "Slow", "Sly", "Small", "Smart", "Smelly", "Smiling", "Smooth",
  7424. "Smug", "Sober", "Soft", "Solemn", "Square", "Square", "Steady", "Strange", "Strong",
  7425. "Stunning", "Subjective", "Successful", "Surly", "Sweet", "Tactful", "Tense",
  7426. "Thoughtful", "Tight", "Tiny", "Tolerant", "Uneasy", "Unique", "Unseen", "Warm", "Weak",
  7427. "Weird", "WellCooked", "Wild", "Wise", "Witty", "Wonderful", "Worried", "Yellow", "Young",
  7428. "Zealous"
  7429. ];
  7430. //var pronouns = [
  7431. //];
  7432. //var conjunctions = [
  7433. //"And", "Or", "For", "Above", "Before", "Against", "Between"
  7434. //];
  7435. /*
  7436. * Maps a string (category name) to the array of words from that category.
  7437. */
  7438. var CATEGORIES =
  7439. {
  7440. //"_NOUN_": nouns,
  7441. "_PLURALNOUN_": pluralNouns,
  7442. //"_PLACE_": places,
  7443. "_VERB_": verbs,
  7444. "_ADVERB_": adverbs,
  7445. "_ADJECTIVE_": adjectives
  7446. //"_PRONOUN_": pronouns,
  7447. //"_CONJUNCTION_": conjunctions,
  7448. };
  7449. var PATTERNS = [
  7450. "_ADJECTIVE__PLURALNOUN__VERB__ADVERB_"
  7451. // BeautifulFungiOrSpaghetti
  7452. //"_ADJECTIVE__PLURALNOUN__CONJUNCTION__PLURALNOUN_",
  7453. // AmazinglyScaryToy
  7454. //"_ADVERB__ADJECTIVE__NOUN_",
  7455. // NeitherTrashNorRifle
  7456. //"Neither_NOUN_Nor_NOUN_",
  7457. //"Either_NOUN_Or_NOUN_",
  7458. // EitherCopulateOrInvestigate
  7459. //"Either_VERB_Or_VERB_",
  7460. //"Neither_VERB_Nor_VERB_",
  7461. //"The_ADJECTIVE__ADJECTIVE__NOUN_",
  7462. //"The_ADVERB__ADJECTIVE__NOUN_",
  7463. //"The_ADVERB__ADJECTIVE__NOUN_s",
  7464. //"The_ADVERB__ADJECTIVE__PLURALNOUN__VERB_",
  7465. // WolvesComputeBadly
  7466. //"_PLURALNOUN__VERB__ADVERB_",
  7467. // UniteFacilitateAndMerge
  7468. //"_VERB__VERB_And_VERB_",
  7469. //NastyWitchesAtThePub
  7470. //"_ADJECTIVE__PLURALNOUN_AtThe_PLACE_",
  7471. ];
  7472. /*
  7473. * Returns a random element from the array 'arr'
  7474. */
  7475. function randomElement(arr)
  7476. {
  7477. return arr[Math.floor(Math.random() * arr.length)];
  7478. }
  7479. /*
  7480. * Returns true if the string 's' contains one of the
  7481. * template strings.
  7482. */
  7483. function hasTemplate(s)
  7484. {
  7485. for (var template in CATEGORIES){
  7486. if (s.indexOf(template) >= 0){
  7487. return true;
  7488. }
  7489. }
  7490. }
  7491. /**
  7492. * Generates new room name.
  7493. */
  7494. var RoomNameGenerator = {
  7495. generateRoomWithoutSeparator: function()
  7496. {
  7497. // Note that if more than one pattern is available, the choice of 'name' won't be random (names from patterns
  7498. // with fewer options will have higher probability of being chosen that names from patterns with more options).
  7499. var name = randomElement(PATTERNS);
  7500. var word;
  7501. while (hasTemplate(name)){
  7502. for (var template in CATEGORIES){
  7503. word = randomElement(CATEGORIES[template]);
  7504. name = name.replace(template, word);
  7505. }
  7506. }
  7507. return name;
  7508. }
  7509. }
  7510. module.exports = RoomNameGenerator;
  7511. },{}],33:[function(require,module,exports){
  7512. var animateTimeout, updateTimeout;
  7513. var RoomNameGenerator = require("./RoomnameGenerator");
  7514. function enter_room()
  7515. {
  7516. var val = $("#enter_room_field").val();
  7517. if(!val) {
  7518. val = $("#enter_room_field").attr("room_name");
  7519. }
  7520. if (val) {
  7521. window.location.pathname = "/" + val;
  7522. }
  7523. }
  7524. function animate(word) {
  7525. var currentVal = $("#enter_room_field").attr("placeholder");
  7526. $("#enter_room_field").attr("placeholder", currentVal + word.substr(0, 1));
  7527. animateTimeout = setTimeout(function() {
  7528. animate(word.substring(1, word.length))
  7529. }, 70);
  7530. }
  7531. function update_roomname()
  7532. {
  7533. var word = RoomNameGenerator.generateRoomWithoutSeparator();
  7534. $("#enter_room_field").attr("room_name", word);
  7535. $("#enter_room_field").attr("placeholder", "");
  7536. clearTimeout(animateTimeout);
  7537. animate(word);
  7538. updateTimeout = setTimeout(update_roomname, 10000);
  7539. }
  7540. function setupWelcomePage()
  7541. {
  7542. $("#videoconference_page").hide();
  7543. $("#domain_name").text(
  7544. window.location.protocol + "//" + window.location.host + "/");
  7545. if (interfaceConfig.SHOW_JITSI_WATERMARK) {
  7546. var leftWatermarkDiv
  7547. = $("#welcome_page_header div[class='watermark leftwatermark']");
  7548. if(leftWatermarkDiv && leftWatermarkDiv.length > 0)
  7549. {
  7550. leftWatermarkDiv.css({display: 'block'});
  7551. leftWatermarkDiv.parent().get(0).href
  7552. = interfaceConfig.JITSI_WATERMARK_LINK;
  7553. }
  7554. }
  7555. if (interfaceConfig.SHOW_BRAND_WATERMARK) {
  7556. var rightWatermarkDiv
  7557. = $("#welcome_page_header div[class='watermark rightwatermark']");
  7558. if(rightWatermarkDiv && rightWatermarkDiv.length > 0) {
  7559. rightWatermarkDiv.css({display: 'block'});
  7560. rightWatermarkDiv.parent().get(0).href
  7561. = interfaceConfig.BRAND_WATERMARK_LINK;
  7562. rightWatermarkDiv.get(0).style.backgroundImage
  7563. = "url(images/rightwatermark.png)";
  7564. }
  7565. }
  7566. if (interfaceConfig.SHOW_POWERED_BY) {
  7567. $("#welcome_page_header>a[class='poweredby']")
  7568. .css({display: 'block'});
  7569. }
  7570. $("#enter_room_button").click(function()
  7571. {
  7572. enter_room();
  7573. });
  7574. $("#enter_room_field").keydown(function (event) {
  7575. if (event.keyCode === 13 /* enter */) {
  7576. enter_room();
  7577. }
  7578. });
  7579. if (!(interfaceConfig.GENERATE_ROOMNAMES_ON_WELCOME_PAGE === false)){
  7580. var updateTimeout;
  7581. var animateTimeout;
  7582. $("#reload_roomname").click(function () {
  7583. clearTimeout(updateTimeout);
  7584. clearTimeout(animateTimeout);
  7585. update_roomname();
  7586. });
  7587. $("#reload_roomname").show();
  7588. update_roomname();
  7589. }
  7590. $("#disable_welcome").click(function () {
  7591. window.localStorage.welcomePageDisabled
  7592. = $("#disable_welcome").is(":checked");
  7593. });
  7594. }
  7595. module.exports = setupWelcomePage;
  7596. },{"./RoomnameGenerator":32}],34:[function(require,module,exports){
  7597. var EventEmitter = require("events");
  7598. var eventEmitter = new EventEmitter();
  7599. var CQEvents = require("../../service/connectionquality/CQEvents");
  7600. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  7601. /**
  7602. * local stats
  7603. * @type {{}}
  7604. */
  7605. var stats = {};
  7606. /**
  7607. * remote stats
  7608. * @type {{}}
  7609. */
  7610. var remoteStats = {};
  7611. /**
  7612. * Interval for sending statistics to other participants
  7613. * @type {null}
  7614. */
  7615. var sendIntervalId = null;
  7616. /**
  7617. * Start statistics sending.
  7618. */
  7619. function startSendingStats() {
  7620. sendStats();
  7621. sendIntervalId = setInterval(sendStats, 10000);
  7622. }
  7623. /**
  7624. * Sends statistics to other participants
  7625. */
  7626. function sendStats() {
  7627. APP.xmpp.addToPresence("connectionQuality", convertToMUCStats(stats));
  7628. }
  7629. /**
  7630. * Converts statistics to format for sending through XMPP
  7631. * @param stats the statistics
  7632. * @returns {{bitrate_donwload: *, bitrate_uplpoad: *, packetLoss_total: *, packetLoss_download: *, packetLoss_upload: *}}
  7633. */
  7634. function convertToMUCStats(stats) {
  7635. return {
  7636. "bitrate_download": stats.bitrate.download,
  7637. "bitrate_upload": stats.bitrate.upload,
  7638. "packetLoss_total": stats.packetLoss.total,
  7639. "packetLoss_download": stats.packetLoss.download,
  7640. "packetLoss_upload": stats.packetLoss.upload
  7641. };
  7642. }
  7643. /**
  7644. * Converts statitistics to format used by VideoLayout
  7645. * @param stats
  7646. * @returns {{bitrate: {download: *, upload: *}, packetLoss: {total: *, download: *, upload: *}}}
  7647. */
  7648. function parseMUCStats(stats) {
  7649. return {
  7650. bitrate: {
  7651. download: stats.bitrate_download,
  7652. upload: stats.bitrate_upload
  7653. },
  7654. packetLoss: {
  7655. total: stats.packetLoss_total,
  7656. download: stats.packetLoss_download,
  7657. upload: stats.packetLoss_upload
  7658. }
  7659. };
  7660. }
  7661. var ConnectionQuality = {
  7662. init: function () {
  7663. APP.xmpp.addListener(XMPPEvents.REMOTE_STATS, this.updateRemoteStats);
  7664. APP.statistics.addConnectionStatsListener(this.updateLocalStats);
  7665. APP.statistics.addRemoteStatsStopListener(this.stopSendingStats);
  7666. },
  7667. /**
  7668. * Updates the local statistics
  7669. * @param data new statistics
  7670. */
  7671. updateLocalStats: function (data) {
  7672. stats = data;
  7673. eventEmitter.emit(CQEvents.LOCALSTATS_UPDATED, 100 - stats.packetLoss.total, stats);
  7674. if (sendIntervalId == null) {
  7675. startSendingStats();
  7676. }
  7677. },
  7678. /**
  7679. * Updates remote statistics
  7680. * @param jid the jid associated with the statistics
  7681. * @param data the statistics
  7682. */
  7683. updateRemoteStats: function (jid, data) {
  7684. if (data == null || data.packetLoss_total == null) {
  7685. eventEmitter.emit(CQEvents.REMOTESTATS_UPDATED, jid, null, null);
  7686. return;
  7687. }
  7688. remoteStats[jid] = parseMUCStats(data);
  7689. eventEmitter.emit(CQEvents.REMOTESTATS_UPDATED,
  7690. jid, 100 - data.packetLoss_total, remoteStats[jid]);
  7691. },
  7692. /**
  7693. * Stops statistics sending.
  7694. */
  7695. stopSendingStats: function () {
  7696. clearInterval(sendIntervalId);
  7697. sendIntervalId = null;
  7698. //notify UI about stopping statistics gathering
  7699. eventEmitter.emit(CQEvents.STOP);
  7700. },
  7701. /**
  7702. * Returns the local statistics.
  7703. */
  7704. getStats: function () {
  7705. return stats;
  7706. },
  7707. addListener: function (type, listener) {
  7708. eventEmitter.on(type, listener);
  7709. }
  7710. };
  7711. module.exports = ConnectionQuality;
  7712. },{"../../service/connectionquality/CQEvents":93,"../../service/xmpp/XMPPEvents":96,"events":97}],35:[function(require,module,exports){
  7713. /* global $, alert, changeLocalVideo, chrome, config, getConferenceHandler, getUserMediaWithConstraints */
  7714. /**
  7715. * Indicates that desktop stream is currently in use(for toggle purpose).
  7716. * @type {boolean}
  7717. */
  7718. var isUsingScreenStream = false;
  7719. /**
  7720. * Indicates that switch stream operation is in progress and prevent from triggering new events.
  7721. * @type {boolean}
  7722. */
  7723. var switchInProgress = false;
  7724. /**
  7725. * Method used to get screen sharing stream.
  7726. *
  7727. * @type {function (stream_callback, failure_callback}
  7728. */
  7729. var obtainDesktopStream = null;
  7730. /**
  7731. * Flag used to cache desktop sharing enabled state. Do not use directly as it can be <tt>null</tt>.
  7732. * @type {null|boolean}
  7733. */
  7734. var _desktopSharingEnabled = null;
  7735. var EventEmitter = require("events");
  7736. var eventEmitter = new EventEmitter();
  7737. var DesktopSharingEventTypes = require("../../service/desktopsharing/DesktopSharingEventTypes");
  7738. /**
  7739. * Method obtains desktop stream from WebRTC 'screen' source.
  7740. * Flag 'chrome://flags/#enable-usermedia-screen-capture' must be enabled.
  7741. */
  7742. function obtainWebRTCScreen(streamCallback, failCallback) {
  7743. APP.RTC.getUserMediaWithConstraints(
  7744. ['screen'],
  7745. streamCallback,
  7746. failCallback
  7747. );
  7748. }
  7749. /**
  7750. * Constructs inline install URL for Chrome desktop streaming extension.
  7751. * The 'chromeExtensionId' must be defined in config.js.
  7752. * @returns {string}
  7753. */
  7754. function getWebStoreInstallUrl()
  7755. {
  7756. return "https://chrome.google.com/webstore/detail/" + config.chromeExtensionId;
  7757. }
  7758. /**
  7759. * Checks whether extension update is required.
  7760. * @param minVersion minimal required version
  7761. * @param extVersion current extension version
  7762. * @returns {boolean}
  7763. */
  7764. function isUpdateRequired(minVersion, extVersion)
  7765. {
  7766. try
  7767. {
  7768. var s1 = minVersion.split('.');
  7769. var s2 = extVersion.split('.');
  7770. var len = Math.max(s1.length, s2.length);
  7771. for (var i = 0; i < len; i++)
  7772. {
  7773. var n1 = 0,
  7774. n2 = 0;
  7775. if (i < s1.length)
  7776. n1 = parseInt(s1[i]);
  7777. if (i < s2.length)
  7778. n2 = parseInt(s2[i]);
  7779. if (isNaN(n1) || isNaN(n2))
  7780. {
  7781. return true;
  7782. }
  7783. else if (n1 !== n2)
  7784. {
  7785. return n1 > n2;
  7786. }
  7787. }
  7788. // will happen if boths version has identical numbers in
  7789. // their components (even if one of them is longer, has more components)
  7790. return false;
  7791. }
  7792. catch (e)
  7793. {
  7794. console.error("Failed to parse extension version", e);
  7795. APP.UI.messageHandler.showError("dialog.error",
  7796. "dialog.detectext");
  7797. return true;
  7798. }
  7799. }
  7800. function checkExtInstalled(isInstalledCallback) {
  7801. if (!chrome.runtime) {
  7802. // No API, so no extension for sure
  7803. isInstalledCallback(false);
  7804. return;
  7805. }
  7806. chrome.runtime.sendMessage(
  7807. config.chromeExtensionId,
  7808. { getVersion: true },
  7809. function (response) {
  7810. if (!response || !response.version) {
  7811. // Communication failure - assume that no endpoint exists
  7812. console.warn("Extension not installed?: " + chrome.runtime.lastError);
  7813. isInstalledCallback(false);
  7814. } else {
  7815. // Check installed extension version
  7816. var extVersion = response.version;
  7817. console.log('Extension version is: ' + extVersion);
  7818. var updateRequired = isUpdateRequired(config.minChromeExtVersion, extVersion);
  7819. if (updateRequired) {
  7820. alert(
  7821. 'Jitsi Desktop Streamer requires update. ' +
  7822. 'Changes will take effect after next Chrome restart.');
  7823. }
  7824. isInstalledCallback(!updateRequired);
  7825. }
  7826. }
  7827. );
  7828. }
  7829. function doGetStreamFromExtension(streamCallback, failCallback) {
  7830. // Sends 'getStream' msg to the extension. Extension id must be defined in the config.
  7831. chrome.runtime.sendMessage(
  7832. config.chromeExtensionId,
  7833. { getStream: true, sources: config.desktopSharingSources },
  7834. function (response) {
  7835. if (!response) {
  7836. failCallback(chrome.runtime.lastError);
  7837. return;
  7838. }
  7839. console.log("Response from extension: " + response);
  7840. if (response.streamId) {
  7841. APP.RTC.getUserMediaWithConstraints(
  7842. ['desktop'],
  7843. function (stream) {
  7844. streamCallback(stream);
  7845. },
  7846. failCallback,
  7847. null, null, null,
  7848. response.streamId);
  7849. } else {
  7850. failCallback("Extension failed to get the stream");
  7851. }
  7852. }
  7853. );
  7854. }
  7855. /**
  7856. * Asks Chrome extension to call chooseDesktopMedia and gets chrome 'desktop' stream for returned stream token.
  7857. */
  7858. function obtainScreenFromExtension(streamCallback, failCallback) {
  7859. checkExtInstalled(
  7860. function (isInstalled) {
  7861. if (isInstalled) {
  7862. doGetStreamFromExtension(streamCallback, failCallback);
  7863. } else {
  7864. chrome.webstore.install(
  7865. getWebStoreInstallUrl(),
  7866. function (arg) {
  7867. console.log("Extension installed successfully", arg);
  7868. // We need to reload the page in order to get the access to chrome.runtime
  7869. window.location.reload(false);
  7870. },
  7871. function (arg) {
  7872. console.log("Failed to install the extension", arg);
  7873. failCallback(arg);
  7874. APP.UI.messageHandler.showError("dialog.error",
  7875. "dialog.failtoinstall");
  7876. }
  7877. );
  7878. }
  7879. }
  7880. );
  7881. }
  7882. /**
  7883. * Call this method to toggle desktop sharing feature.
  7884. * @param method pass "ext" to use chrome extension for desktop capture(chrome extension required),
  7885. * pass "webrtc" to use WebRTC "screen" desktop source('chrome://flags/#enable-usermedia-screen-capture'
  7886. * must be enabled), pass any other string or nothing in order to disable this feature completely.
  7887. */
  7888. function setDesktopSharing(method) {
  7889. // Check if we are running chrome
  7890. if (!navigator.webkitGetUserMedia) {
  7891. obtainDesktopStream = null;
  7892. console.info("Desktop sharing disabled");
  7893. } else if (method == "ext") {
  7894. obtainDesktopStream = obtainScreenFromExtension;
  7895. console.info("Using Chrome extension for desktop sharing");
  7896. } else if (method == "webrtc") {
  7897. obtainDesktopStream = obtainWebRTCScreen;
  7898. console.info("Using Chrome WebRTC for desktop sharing");
  7899. }
  7900. // Reset enabled cache
  7901. _desktopSharingEnabled = null;
  7902. }
  7903. /**
  7904. * Initializes <link rel=chrome-webstore-item /> with extension id set in config.js to support inline installs.
  7905. * Host site must be selected as main website of published extension.
  7906. */
  7907. function initInlineInstalls()
  7908. {
  7909. $("link[rel=chrome-webstore-item]").attr("href", getWebStoreInstallUrl());
  7910. }
  7911. function getSwitchStreamFailed(error) {
  7912. console.error("Failed to obtain the stream to switch to", error);
  7913. switchInProgress = false;
  7914. }
  7915. function streamSwitchDone() {
  7916. switchInProgress = false;
  7917. eventEmitter.emit(
  7918. DesktopSharingEventTypes.SWITCHING_DONE,
  7919. isUsingScreenStream);
  7920. }
  7921. function newStreamCreated(stream)
  7922. {
  7923. eventEmitter.emit(DesktopSharingEventTypes.NEW_STREAM_CREATED,
  7924. stream, isUsingScreenStream, streamSwitchDone);
  7925. }
  7926. module.exports = {
  7927. isUsingScreenStream: function () {
  7928. return isUsingScreenStream;
  7929. },
  7930. /**
  7931. * @returns {boolean} <tt>true</tt> if desktop sharing feature is available and enabled.
  7932. */
  7933. isDesktopSharingEnabled: function () {
  7934. if (_desktopSharingEnabled === null) {
  7935. if (obtainDesktopStream === obtainScreenFromExtension) {
  7936. // Parse chrome version
  7937. var userAgent = navigator.userAgent.toLowerCase();
  7938. // We can assume that user agent is chrome, because it's enforced when 'ext' streaming method is set
  7939. var ver = parseInt(userAgent.match(/chrome\/(\d+)\./)[1], 10);
  7940. console.log("Chrome version" + userAgent, ver);
  7941. _desktopSharingEnabled = ver >= 34;
  7942. } else {
  7943. _desktopSharingEnabled = obtainDesktopStream === obtainWebRTCScreen;
  7944. }
  7945. }
  7946. return _desktopSharingEnabled;
  7947. },
  7948. init: function () {
  7949. setDesktopSharing(config.desktopSharing);
  7950. // Initialize Chrome extension inline installs
  7951. if (config.chromeExtensionId) {
  7952. initInlineInstalls();
  7953. }
  7954. eventEmitter.emit(DesktopSharingEventTypes.INIT);
  7955. },
  7956. addListener: function(listener, type)
  7957. {
  7958. eventEmitter.on(type, listener);
  7959. },
  7960. removeListener: function (listener,type) {
  7961. eventEmitter.removeListener(type, listener);
  7962. },
  7963. /*
  7964. * Toggles screen sharing.
  7965. */
  7966. toggleScreenSharing: function () {
  7967. if (switchInProgress || !obtainDesktopStream) {
  7968. console.warn("Switch in progress or no method defined");
  7969. return;
  7970. }
  7971. switchInProgress = true;
  7972. if (!isUsingScreenStream)
  7973. {
  7974. // Switch to desktop stream
  7975. obtainDesktopStream(
  7976. function (stream) {
  7977. // We now use screen stream
  7978. isUsingScreenStream = true;
  7979. // Hook 'ended' event to restore camera when screen stream stops
  7980. stream.addEventListener('ended',
  7981. function (e) {
  7982. if (!switchInProgress && isUsingScreenStream) {
  7983. toggleScreenSharing();
  7984. }
  7985. }
  7986. );
  7987. newStreamCreated(stream);
  7988. },
  7989. getSwitchStreamFailed);
  7990. } else {
  7991. // Disable screen stream
  7992. APP.RTC.getUserMediaWithConstraints(
  7993. ['video'],
  7994. function (stream) {
  7995. // We are now using camera stream
  7996. isUsingScreenStream = false;
  7997. newStreamCreated(stream);
  7998. },
  7999. getSwitchStreamFailed, config.resolution || '360'
  8000. );
  8001. }
  8002. }
  8003. };
  8004. },{"../../service/desktopsharing/DesktopSharingEventTypes":94,"events":97}],36:[function(require,module,exports){
  8005. //maps keycode to character, id of popover for given function and function
  8006. var shortcuts = {
  8007. 67: {
  8008. character: "C",
  8009. id: "toggleChatPopover",
  8010. function: APP.UI.toggleChat
  8011. },
  8012. 70: {
  8013. character: "F",
  8014. id: "filmstripPopover",
  8015. function: APP.UI.toggleFilmStrip
  8016. },
  8017. 77: {
  8018. character: "M",
  8019. id: "mutePopover",
  8020. function: APP.UI.toggleAudio
  8021. },
  8022. 84: {
  8023. character: "T",
  8024. function: function() {
  8025. if(!APP.RTC.localAudio.isMuted()) {
  8026. APP.UI.toggleAudio();
  8027. }
  8028. }
  8029. },
  8030. 86: {
  8031. character: "V",
  8032. id: "toggleVideoPopover",
  8033. function: APP.UI.toggleVideo
  8034. }
  8035. };
  8036. var KeyboardShortcut = {
  8037. init: function () {
  8038. window.onkeyup = function(e) {
  8039. var keycode = e.which;
  8040. if(!($(":focus").is("input[type=text]") ||
  8041. $(":focus").is("input[type=password]") ||
  8042. $(":focus").is("textarea"))) {
  8043. if (typeof shortcuts[keycode] === "object") {
  8044. shortcuts[keycode].function();
  8045. }
  8046. else if (keycode >= "0".charCodeAt(0) &&
  8047. keycode <= "9".charCodeAt(0)) {
  8048. APP.UI.clickOnVideo(keycode - "0".charCodeAt(0) + 1);
  8049. }
  8050. //esc while the smileys are visible hides them
  8051. } else if (keycode === 27 && $('#smileysContainer').is(':visible')) {
  8052. APP.UI.toggleSmileys();
  8053. }
  8054. };
  8055. window.onkeydown = function(e) {
  8056. if(!($(":focus").is("input[type=text]") ||
  8057. $(":focus").is("input[type=password]") ||
  8058. $(":focus").is("textarea"))) {
  8059. if(e.which === "T".charCodeAt(0)) {
  8060. if(APP.RTC.localAudio.isMuted()) {
  8061. APP.UI.toggleAudio();
  8062. }
  8063. }
  8064. }
  8065. };
  8066. var self = this;
  8067. $('body').popover({ selector: '[data-toggle=popover]',
  8068. trigger: 'click hover',
  8069. content: function() {
  8070. return this.getAttribute("content") +
  8071. self.getShortcut(this.getAttribute("shortcut"));
  8072. }
  8073. });
  8074. },
  8075. /**
  8076. *
  8077. * @param id indicates the popover associated with the shortcut
  8078. * @returns {string} the keyboard shortcut used for the id given
  8079. */
  8080. getShortcut: function (id) {
  8081. for (var keycode in shortcuts) {
  8082. if (shortcuts.hasOwnProperty(keycode)) {
  8083. if (shortcuts[keycode].id === id) {
  8084. return " (" + shortcuts[keycode].character + ")";
  8085. }
  8086. }
  8087. }
  8088. return "";
  8089. }
  8090. };
  8091. module.exports = KeyboardShortcut;
  8092. },{}],37:[function(require,module,exports){
  8093. var email = '';
  8094. var displayName = '';
  8095. var userId;
  8096. var language = null;
  8097. function supportsLocalStorage() {
  8098. try {
  8099. return 'localStorage' in window && window.localStorage !== null;
  8100. } catch (e) {
  8101. console.log("localstorage is not supported");
  8102. return false;
  8103. }
  8104. }
  8105. function generateUniqueId() {
  8106. function _p8() {
  8107. return (Math.random().toString(16) + "000000000").substr(2, 8);
  8108. }
  8109. return _p8() + _p8() + _p8() + _p8();
  8110. }
  8111. if (supportsLocalStorage()) {
  8112. if (!window.localStorage.jitsiMeetId) {
  8113. window.localStorage.jitsiMeetId = generateUniqueId();
  8114. console.log("generated id", window.localStorage.jitsiMeetId);
  8115. }
  8116. userId = window.localStorage.jitsiMeetId || '';
  8117. email = window.localStorage.email || '';
  8118. displayName = window.localStorage.displayname || '';
  8119. language = window.localStorage.language;
  8120. } else {
  8121. console.log("local storage is not supported");
  8122. userId = generateUniqueId();
  8123. }
  8124. var Settings =
  8125. {
  8126. setDisplayName: function (newDisplayName) {
  8127. displayName = newDisplayName;
  8128. window.localStorage.displayname = displayName;
  8129. return displayName;
  8130. },
  8131. setEmail: function (newEmail)
  8132. {
  8133. email = newEmail;
  8134. window.localStorage.email = newEmail;
  8135. return email;
  8136. },
  8137. getSettings: function () {
  8138. return {
  8139. email: email,
  8140. displayName: displayName,
  8141. uid: userId,
  8142. language: language
  8143. };
  8144. },
  8145. setLanguage: function (lang) {
  8146. language = lang;
  8147. window.localStorage.language = lang;
  8148. }
  8149. };
  8150. module.exports = Settings;
  8151. },{}],38:[function(require,module,exports){
  8152. /**
  8153. *
  8154. * @constructor
  8155. */
  8156. function SimulcastLogger(name, lvl) {
  8157. this.name = name;
  8158. this.lvl = lvl;
  8159. }
  8160. SimulcastLogger.prototype.log = function (text) {
  8161. if (this.lvl) {
  8162. console.log(text);
  8163. }
  8164. };
  8165. SimulcastLogger.prototype.info = function (text) {
  8166. if (this.lvl > 1) {
  8167. console.info(text);
  8168. }
  8169. };
  8170. SimulcastLogger.prototype.fine = function (text) {
  8171. if (this.lvl > 2) {
  8172. console.log(text);
  8173. }
  8174. };
  8175. SimulcastLogger.prototype.error = function (text) {
  8176. console.error(text);
  8177. };
  8178. module.exports = SimulcastLogger;
  8179. },{}],39:[function(require,module,exports){
  8180. var SimulcastLogger = require("./SimulcastLogger");
  8181. var SimulcastUtils = require("./SimulcastUtils");
  8182. var MediaStreamType = require("../../service/RTC/MediaStreamTypes");
  8183. function SimulcastReceiver() {
  8184. this.simulcastUtils = new SimulcastUtils();
  8185. this.logger = new SimulcastLogger('SimulcastReceiver', 1);
  8186. }
  8187. SimulcastReceiver.prototype._remoteVideoSourceCache = '';
  8188. SimulcastReceiver.prototype._remoteMaps = {
  8189. msid2Quality: {},
  8190. ssrc2Msid: {},
  8191. msid2ssrc: {},
  8192. receivingVideoStreams: {}
  8193. };
  8194. SimulcastReceiver.prototype._cacheRemoteVideoSources = function (lines) {
  8195. this._remoteVideoSourceCache = this.simulcastUtils._getVideoSources(lines);
  8196. };
  8197. SimulcastReceiver.prototype._restoreRemoteVideoSources = function (lines) {
  8198. this.simulcastUtils._replaceVideoSources(lines, this._remoteVideoSourceCache);
  8199. };
  8200. SimulcastReceiver.prototype._ensureGoogConference = function (lines) {
  8201. var sb;
  8202. this.logger.info('Ensuring x-google-conference flag...')
  8203. if (this.simulcastUtils._indexOfArray('a=x-google-flag:conference', lines) === this.simulcastUtils._emptyCompoundIndex) {
  8204. // TODO(gp) do that for the audio as well as suggested by fippo.
  8205. // Add the google conference flag
  8206. sb = this.simulcastUtils._getVideoSources(lines);
  8207. sb = ['a=x-google-flag:conference'].concat(sb);
  8208. this.simulcastUtils._replaceVideoSources(lines, sb);
  8209. }
  8210. };
  8211. SimulcastReceiver.prototype._restoreSimulcastGroups = function (sb) {
  8212. this._restoreRemoteVideoSources(sb);
  8213. };
  8214. /**
  8215. * Restores the simulcast groups of the remote description. In
  8216. * transformRemoteDescription we remove those in order for the set remote
  8217. * description to succeed. The focus needs the signal the groups to new
  8218. * participants.
  8219. *
  8220. * @param desc
  8221. * @returns {*}
  8222. */
  8223. SimulcastReceiver.prototype.reverseTransformRemoteDescription = function (desc) {
  8224. var sb;
  8225. if (!this.simulcastUtils.isValidDescription(desc)) {
  8226. return desc;
  8227. }
  8228. if (config.enableSimulcast) {
  8229. sb = desc.sdp.split('\r\n');
  8230. this._restoreSimulcastGroups(sb);
  8231. desc = new RTCSessionDescription({
  8232. type: desc.type,
  8233. sdp: sb.join('\r\n')
  8234. });
  8235. }
  8236. return desc;
  8237. };
  8238. SimulcastUtils.prototype._ensureOrder = function (lines) {
  8239. var videoSources, sb;
  8240. videoSources = this.parseMedia(lines, ['video'])[0];
  8241. sb = this._compileVideoSources(videoSources);
  8242. this._replaceVideoSources(lines, sb);
  8243. };
  8244. SimulcastReceiver.prototype._updateRemoteMaps = function (lines) {
  8245. var remoteVideoSources = this.simulcastUtils.parseMedia(lines, ['video'])[0],
  8246. videoSource, quality;
  8247. // (re) initialize the remote maps.
  8248. this._remoteMaps.msid2Quality = {};
  8249. this._remoteMaps.ssrc2Msid = {};
  8250. this._remoteMaps.msid2ssrc = {};
  8251. var self = this;
  8252. if (remoteVideoSources.groups && remoteVideoSources.groups.length !== 0) {
  8253. remoteVideoSources.groups.forEach(function (group) {
  8254. if (group.semantics === 'SIM' && group.ssrcs && group.ssrcs.length !== 0) {
  8255. quality = 0;
  8256. group.ssrcs.forEach(function (ssrc) {
  8257. videoSource = remoteVideoSources.sources[ssrc];
  8258. self._remoteMaps.msid2Quality[videoSource.msid] = quality++;
  8259. self._remoteMaps.ssrc2Msid[videoSource.ssrc] = videoSource.msid;
  8260. self._remoteMaps.msid2ssrc[videoSource.msid] = videoSource.ssrc;
  8261. });
  8262. }
  8263. });
  8264. }
  8265. };
  8266. SimulcastReceiver.prototype._setReceivingVideoStream = function (resource, ssrc) {
  8267. this._remoteMaps.receivingVideoStreams[resource] = ssrc;
  8268. };
  8269. /**
  8270. * Returns a stream with single video track, the one currently being
  8271. * received by this endpoint.
  8272. *
  8273. * @param stream the remote simulcast stream.
  8274. * @returns {webkitMediaStream}
  8275. */
  8276. SimulcastReceiver.prototype.getReceivingVideoStream = function (stream) {
  8277. var tracks, i, electedTrack, msid, quality = 0, receivingTrackId;
  8278. var self = this;
  8279. if (config.enableSimulcast) {
  8280. stream.getVideoTracks().some(function (track) {
  8281. return Object.keys(self._remoteMaps.receivingVideoStreams).some(function (resource) {
  8282. var ssrc = self._remoteMaps.receivingVideoStreams[resource];
  8283. var msid = self._remoteMaps.ssrc2Msid[ssrc];
  8284. if (msid == [stream.id, track.id].join(' ')) {
  8285. electedTrack = track;
  8286. return true;
  8287. }
  8288. });
  8289. });
  8290. if (!electedTrack) {
  8291. // we don't have an elected track, choose by initial quality.
  8292. tracks = stream.getVideoTracks();
  8293. for (i = 0; i < tracks.length; i++) {
  8294. msid = [stream.id, tracks[i].id].join(' ');
  8295. if (this._remoteMaps.msid2Quality[msid] === quality) {
  8296. electedTrack = tracks[i];
  8297. break;
  8298. }
  8299. }
  8300. // TODO(gp) if the initialQuality could not be satisfied, lower
  8301. // the requirement and try again.
  8302. }
  8303. }
  8304. return (electedTrack)
  8305. ? new webkitMediaStream([electedTrack])
  8306. : stream;
  8307. };
  8308. SimulcastReceiver.prototype.getReceivingSSRC = function (jid) {
  8309. var resource = Strophe.getResourceFromJid(jid);
  8310. var ssrc = this._remoteMaps.receivingVideoStreams[resource];
  8311. // If we haven't receiving a "changed" event yet, then we must be receiving
  8312. // low quality (that the sender always streams).
  8313. if(!ssrc)
  8314. {
  8315. var remoteStreamObject = APP.RTC.remoteStreams[jid][MediaStreamType.VIDEO_TYPE];
  8316. var remoteStream = remoteStreamObject.getOriginalStream();
  8317. var tracks = remoteStream.getVideoTracks();
  8318. if (tracks) {
  8319. for (var k = 0; k < tracks.length; k++) {
  8320. var track = tracks[k];
  8321. var msid = [remoteStream.id, track.id].join(' ');
  8322. var _ssrc = this._remoteMaps.msid2ssrc[msid];
  8323. var quality = this._remoteMaps.msid2Quality[msid];
  8324. if (quality == 0) {
  8325. ssrc = _ssrc;
  8326. }
  8327. }
  8328. }
  8329. }
  8330. return ssrc;
  8331. };
  8332. SimulcastReceiver.prototype.getReceivingVideoStreamBySSRC = function (ssrc)
  8333. {
  8334. var sid, electedStream;
  8335. var i, j, k;
  8336. var jid = APP.xmpp.getJidFromSSRC(ssrc);
  8337. if(jid && APP.RTC.remoteStreams[jid])
  8338. {
  8339. var remoteStreamObject = APP.RTC.remoteStreams[jid][MediaStreamType.VIDEO_TYPE];
  8340. var remoteStream = remoteStreamObject.getOriginalStream();
  8341. var tracks = remoteStream.getVideoTracks();
  8342. if (tracks) {
  8343. for (k = 0; k < tracks.length; k++) {
  8344. var track = tracks[k];
  8345. var msid = [remoteStream.id, track.id].join(' ');
  8346. var tmp = this._remoteMaps.msid2ssrc[msid];
  8347. if (tmp == ssrc) {
  8348. electedStream = new webkitMediaStream([track]);
  8349. sid = remoteStreamObject.sid;
  8350. // stream found, stop.
  8351. break;
  8352. }
  8353. }
  8354. }
  8355. }
  8356. else
  8357. {
  8358. console.debug(APP.RTC.remoteStreams, jid, ssrc);
  8359. }
  8360. return {
  8361. sid: sid,
  8362. stream: electedStream
  8363. };
  8364. };
  8365. /**
  8366. * Gets the fully qualified msid (stream.id + track.id) associated to the
  8367. * SSRC.
  8368. *
  8369. * @param ssrc
  8370. * @returns {*}
  8371. */
  8372. SimulcastReceiver.prototype.getRemoteVideoStreamIdBySSRC = function (ssrc) {
  8373. return this._remoteMaps.ssrc2Msid[ssrc];
  8374. };
  8375. /**
  8376. * Removes the ssrc-group:SIM from the remote description bacause Chrome
  8377. * either gets confused and thinks this is an FID group or, if an FID group
  8378. * is already present, it fails to set the remote description.
  8379. *
  8380. * @param desc
  8381. * @returns {*}
  8382. */
  8383. SimulcastReceiver.prototype.transformRemoteDescription = function (desc) {
  8384. if (desc && desc.sdp) {
  8385. var sb = desc.sdp.split('\r\n');
  8386. this._updateRemoteMaps(sb);
  8387. this._cacheRemoteVideoSources(sb);
  8388. // NOTE(gp) this needs to be called after updateRemoteMaps because we
  8389. // need the simulcast group in the _updateRemoteMaps() method.
  8390. this.simulcastUtils._removeSimulcastGroup(sb);
  8391. if (desc.sdp.indexOf('a=ssrc-group:SIM') !== -1) {
  8392. // We don't need the goog conference flag if we're not doing
  8393. // simulcast.
  8394. this._ensureGoogConference(sb);
  8395. }
  8396. desc = new RTCSessionDescription({
  8397. type: desc.type,
  8398. sdp: sb.join('\r\n')
  8399. });
  8400. this.logger.fine(['Transformed remote description', desc.sdp].join(' '));
  8401. }
  8402. return desc;
  8403. };
  8404. module.exports = SimulcastReceiver;
  8405. },{"../../service/RTC/MediaStreamTypes":86,"./SimulcastLogger":38,"./SimulcastUtils":41}],40:[function(require,module,exports){
  8406. var SimulcastLogger = require("./SimulcastLogger");
  8407. var SimulcastUtils = require("./SimulcastUtils");
  8408. function SimulcastSender() {
  8409. this.simulcastUtils = new SimulcastUtils();
  8410. this.logger = new SimulcastLogger('SimulcastSender', 1);
  8411. }
  8412. SimulcastSender.prototype.displayedLocalVideoStream = null;
  8413. SimulcastSender.prototype._generateGuid = (function () {
  8414. function s4() {
  8415. return Math.floor((1 + Math.random()) * 0x10000)
  8416. .toString(16)
  8417. .substring(1);
  8418. }
  8419. return function () {
  8420. return s4() + s4() + '-' + s4() + '-' + s4() + '-' +
  8421. s4() + '-' + s4() + s4() + s4();
  8422. };
  8423. }());
  8424. // Returns a random integer between min (included) and max (excluded)
  8425. // Using Math.round() gives a non-uniform distribution!
  8426. SimulcastSender.prototype._generateRandomSSRC = function () {
  8427. var min = 0, max = 0xffffffff;
  8428. return Math.floor(Math.random() * (max - min)) + min;
  8429. };
  8430. SimulcastSender.prototype.getLocalVideoStream = function () {
  8431. return (this.displayedLocalVideoStream != null)
  8432. ? this.displayedLocalVideoStream
  8433. // in case we have no simulcast at all, i.e. we didn't perform the GUM
  8434. : APP.RTC.localVideo.getOriginalStream();
  8435. };
  8436. function NativeSimulcastSender() {
  8437. SimulcastSender.call(this); // call the super constructor.
  8438. }
  8439. NativeSimulcastSender.prototype = Object.create(SimulcastSender.prototype);
  8440. NativeSimulcastSender.prototype._localExplosionMap = {};
  8441. NativeSimulcastSender.prototype._isUsingScreenStream = false;
  8442. NativeSimulcastSender.prototype._localVideoSourceCache = '';
  8443. NativeSimulcastSender.prototype.reset = function () {
  8444. this._localExplosionMap = {};
  8445. this._isUsingScreenStream = APP.desktopsharing.isUsingScreenStream();
  8446. };
  8447. NativeSimulcastSender.prototype._cacheLocalVideoSources = function (lines) {
  8448. this._localVideoSourceCache = this.simulcastUtils._getVideoSources(lines);
  8449. };
  8450. NativeSimulcastSender.prototype._restoreLocalVideoSources = function (lines) {
  8451. this.simulcastUtils._replaceVideoSources(lines, this._localVideoSourceCache);
  8452. };
  8453. NativeSimulcastSender.prototype._appendSimulcastGroup = function (lines) {
  8454. var videoSources, ssrcGroup, simSSRC, numOfSubs = 2, i, sb, msid;
  8455. this.logger.info('Appending simulcast group...');
  8456. // Get the primary SSRC information.
  8457. videoSources = this.simulcastUtils.parseMedia(lines, ['video'])[0];
  8458. // Start building the SIM SSRC group.
  8459. ssrcGroup = ['a=ssrc-group:SIM'];
  8460. // The video source buffer.
  8461. sb = [];
  8462. // Create the simulcast sub-streams.
  8463. for (i = 0; i < numOfSubs; i++) {
  8464. // TODO(gp) prevent SSRC collision.
  8465. simSSRC = this._generateRandomSSRC();
  8466. ssrcGroup.push(simSSRC);
  8467. if (videoSources.base) {
  8468. sb.splice.apply(sb, [sb.length, 0].concat(
  8469. [["a=ssrc:", simSSRC, " cname:", videoSources.base.cname].join(''),
  8470. ["a=ssrc:", simSSRC, " msid:", videoSources.base.msid].join('')]
  8471. ));
  8472. }
  8473. this.logger.info(['Generated substream ', i, ' with SSRC ', simSSRC, '.'].join(''));
  8474. }
  8475. // Add the group sim layers.
  8476. sb.splice(0, 0, ssrcGroup.join(' '))
  8477. this.simulcastUtils._replaceVideoSources(lines, sb);
  8478. };
  8479. // Does the actual patching.
  8480. NativeSimulcastSender.prototype._ensureSimulcastGroup = function (lines) {
  8481. this.logger.info('Ensuring simulcast group...');
  8482. if (this.simulcastUtils._indexOfArray('a=ssrc-group:SIM', lines) === this.simulcastUtils._emptyCompoundIndex) {
  8483. this._appendSimulcastGroup(lines);
  8484. this._cacheLocalVideoSources(lines);
  8485. } else {
  8486. // verify that the ssrcs participating in the SIM group are present
  8487. // in the SDP (needed for presence).
  8488. this._restoreLocalVideoSources(lines);
  8489. }
  8490. };
  8491. /**
  8492. * Produces a single stream with multiple tracks for local video sources.
  8493. *
  8494. * @param lines
  8495. * @private
  8496. */
  8497. NativeSimulcastSender.prototype._explodeSimulcastSenderSources = function (lines) {
  8498. var sb, msid, sid, tid, videoSources, self;
  8499. this.logger.info('Exploding local video sources...');
  8500. videoSources = this.simulcastUtils.parseMedia(lines, ['video'])[0];
  8501. self = this;
  8502. if (videoSources.groups && videoSources.groups.length !== 0) {
  8503. videoSources.groups.forEach(function (group) {
  8504. if (group.semantics === 'SIM') {
  8505. group.ssrcs.forEach(function (ssrc) {
  8506. // Get the msid for this ssrc..
  8507. if (self._localExplosionMap[ssrc]) {
  8508. // .. either from the explosion map..
  8509. msid = self._localExplosionMap[ssrc];
  8510. } else {
  8511. // .. or generate a new one (msid).
  8512. sid = videoSources.sources[ssrc].msid
  8513. .substring(0, videoSources.sources[ssrc].msid.indexOf(' '));
  8514. tid = self._generateGuid();
  8515. msid = [sid, tid].join(' ');
  8516. self._localExplosionMap[ssrc] = msid;
  8517. }
  8518. // Assign it to the source object.
  8519. videoSources.sources[ssrc].msid = msid;
  8520. // TODO(gp) Change the msid of associated sources.
  8521. });
  8522. }
  8523. });
  8524. }
  8525. sb = this.simulcastUtils._compileVideoSources(videoSources);
  8526. this.simulcastUtils._replaceVideoSources(lines, sb);
  8527. };
  8528. /**
  8529. * GUM for simulcast.
  8530. *
  8531. * @param constraints
  8532. * @param success
  8533. * @param err
  8534. */
  8535. NativeSimulcastSender.prototype.getUserMedia = function (constraints, success, err) {
  8536. // There's nothing special to do for native simulcast, so just do a normal GUM.
  8537. navigator.webkitGetUserMedia(constraints, function (hqStream) {
  8538. success(hqStream);
  8539. }, err);
  8540. };
  8541. /**
  8542. * Prepares the local description for public usage (i.e. to be signaled
  8543. * through Jingle to the focus).
  8544. *
  8545. * @param desc
  8546. * @returns {RTCSessionDescription}
  8547. */
  8548. NativeSimulcastSender.prototype.reverseTransformLocalDescription = function (desc) {
  8549. var sb;
  8550. if (!this.simulcastUtils.isValidDescription(desc) || this._isUsingScreenStream) {
  8551. return desc;
  8552. }
  8553. sb = desc.sdp.split('\r\n');
  8554. this._explodeSimulcastSenderSources(sb);
  8555. desc = new RTCSessionDescription({
  8556. type: desc.type,
  8557. sdp: sb.join('\r\n')
  8558. });
  8559. this.logger.fine(['Exploded local video sources', desc.sdp].join(' '));
  8560. return desc;
  8561. };
  8562. /**
  8563. * Ensures that the simulcast group is present in the answer, _if_ native
  8564. * simulcast is enabled,
  8565. *
  8566. * @param desc
  8567. * @returns {*}
  8568. */
  8569. NativeSimulcastSender.prototype.transformAnswer = function (desc) {
  8570. if (!this.simulcastUtils.isValidDescription(desc) || this._isUsingScreenStream) {
  8571. return desc;
  8572. }
  8573. var sb = desc.sdp.split('\r\n');
  8574. // Even if we have enabled native simulcasting previously
  8575. // (with a call to SLD with an appropriate SDP, for example),
  8576. // createAnswer seems to consistently generate incomplete SDP
  8577. // with missing SSRCS.
  8578. //
  8579. // So, subsequent calls to SLD will have missing SSRCS and presence
  8580. // won't have the complete list of SRCs.
  8581. this._ensureSimulcastGroup(sb);
  8582. desc = new RTCSessionDescription({
  8583. type: desc.type,
  8584. sdp: sb.join('\r\n')
  8585. });
  8586. this.logger.fine(['Transformed answer', desc.sdp].join(' '));
  8587. return desc;
  8588. };
  8589. /**
  8590. *
  8591. *
  8592. * @param desc
  8593. * @returns {*}
  8594. */
  8595. NativeSimulcastSender.prototype.transformLocalDescription = function (desc) {
  8596. return desc;
  8597. };
  8598. NativeSimulcastSender.prototype._setLocalVideoStreamEnabled = function (ssrc, enabled) {
  8599. // Nothing to do here, native simulcast does that auto-magically.
  8600. };
  8601. NativeSimulcastSender.prototype.constructor = NativeSimulcastSender;
  8602. function SimpleSimulcastSender() {
  8603. SimulcastSender.call(this);
  8604. }
  8605. SimpleSimulcastSender.prototype = Object.create(SimulcastSender.prototype);
  8606. SimpleSimulcastSender.prototype.localStream = null;
  8607. SimpleSimulcastSender.prototype._localMaps = {
  8608. msids: [],
  8609. msid2ssrc: {}
  8610. };
  8611. /**
  8612. * Groups local video sources together in the ssrc-group:SIM group.
  8613. *
  8614. * @param lines
  8615. * @private
  8616. */
  8617. SimpleSimulcastSender.prototype._groupLocalVideoSources = function (lines) {
  8618. var sb, videoSources, ssrcs = [], ssrc;
  8619. this.logger.info('Grouping local video sources...');
  8620. videoSources = this.simulcastUtils.parseMedia(lines, ['video'])[0];
  8621. for (ssrc in videoSources.sources) {
  8622. // jitsi-meet destroys/creates streams at various places causing
  8623. // the original local stream ids to change. The only thing that
  8624. // remains unchanged is the trackid.
  8625. this._localMaps.msid2ssrc[videoSources.sources[ssrc].msid.split(' ')[1]] = ssrc;
  8626. }
  8627. var self = this;
  8628. // TODO(gp) add only "free" sources.
  8629. this._localMaps.msids.forEach(function (msid) {
  8630. ssrcs.push(self._localMaps.msid2ssrc[msid]);
  8631. });
  8632. if (!videoSources.groups) {
  8633. videoSources.groups = [];
  8634. }
  8635. videoSources.groups.push({
  8636. 'semantics': 'SIM',
  8637. 'ssrcs': ssrcs
  8638. });
  8639. sb = this.simulcastUtils._compileVideoSources(videoSources);
  8640. this.simulcastUtils._replaceVideoSources(lines, sb);
  8641. };
  8642. /**
  8643. * GUM for simulcast.
  8644. *
  8645. * @param constraints
  8646. * @param success
  8647. * @param err
  8648. */
  8649. SimpleSimulcastSender.prototype.getUserMedia = function (constraints, success, err) {
  8650. // TODO(gp) what if we request a resolution not supported by the hardware?
  8651. // TODO(gp) make the lq stream configurable; although this wouldn't work with native simulcast
  8652. var lqConstraints = {
  8653. audio: false,
  8654. video: {
  8655. mandatory: {
  8656. maxWidth: 320,
  8657. maxHeight: 180,
  8658. maxFrameRate: 15
  8659. }
  8660. }
  8661. };
  8662. this.logger.info('HQ constraints: ', constraints);
  8663. this.logger.info('LQ constraints: ', lqConstraints);
  8664. // NOTE(gp) if we request the lq stream first webkitGetUserMedia
  8665. // fails randomly. Tested with Chrome 37. As fippo suggested, the
  8666. // reason appears to be that Chrome only acquires the cam once and
  8667. // then downscales the picture (https://code.google.com/p/chromium/issues/detail?id=346616#c11)
  8668. var self = this;
  8669. navigator.webkitGetUserMedia(constraints, function (hqStream) {
  8670. self.localStream = hqStream;
  8671. // reset local maps.
  8672. self._localMaps.msids = [];
  8673. self._localMaps.msid2ssrc = {};
  8674. // add hq trackid to local map
  8675. self._localMaps.msids.push(hqStream.getVideoTracks()[0].id);
  8676. navigator.webkitGetUserMedia(lqConstraints, function (lqStream) {
  8677. self.displayedLocalVideoStream = lqStream;
  8678. // NOTE(gp) The specification says Array.forEach() will visit
  8679. // the array elements in numeric order, and that it doesn't
  8680. // visit elements that don't exist.
  8681. // add lq trackid to local map
  8682. self._localMaps.msids.splice(0, 0, lqStream.getVideoTracks()[0].id);
  8683. self.localStream.addTrack(lqStream.getVideoTracks()[0]);
  8684. success(self.localStream);
  8685. }, err);
  8686. }, err);
  8687. };
  8688. /**
  8689. * Prepares the local description for public usage (i.e. to be signaled
  8690. * through Jingle to the focus).
  8691. *
  8692. * @param desc
  8693. * @returns {RTCSessionDescription}
  8694. */
  8695. SimpleSimulcastSender.prototype.reverseTransformLocalDescription = function (desc) {
  8696. var sb;
  8697. if (!this.simulcastUtils.isValidDescription(desc)) {
  8698. return desc;
  8699. }
  8700. sb = desc.sdp.split('\r\n');
  8701. this._groupLocalVideoSources(sb);
  8702. desc = new RTCSessionDescription({
  8703. type: desc.type,
  8704. sdp: sb.join('\r\n')
  8705. });
  8706. this.logger.fine('Grouped local video sources');
  8707. this.logger.fine(desc.sdp);
  8708. return desc;
  8709. };
  8710. /**
  8711. * Ensures that the simulcast group is present in the answer, _if_ native
  8712. * simulcast is enabled,
  8713. *
  8714. * @param desc
  8715. * @returns {*}
  8716. */
  8717. SimpleSimulcastSender.prototype.transformAnswer = function (desc) {
  8718. return desc;
  8719. };
  8720. /**
  8721. *
  8722. *
  8723. * @param desc
  8724. * @returns {*}
  8725. */
  8726. SimpleSimulcastSender.prototype.transformLocalDescription = function (desc) {
  8727. var sb = desc.sdp.split('\r\n');
  8728. this.simulcastUtils._removeSimulcastGroup(sb);
  8729. desc = new RTCSessionDescription({
  8730. type: desc.type,
  8731. sdp: sb.join('\r\n')
  8732. });
  8733. this.logger.fine('Transformed local description');
  8734. this.logger.fine(desc.sdp);
  8735. return desc;
  8736. };
  8737. SimpleSimulcastSender.prototype._setLocalVideoStreamEnabled = function (ssrc, enabled) {
  8738. var trackid;
  8739. var self = this;
  8740. this.logger.log(['Requested to', enabled ? 'enable' : 'disable', ssrc].join(' '));
  8741. if (Object.keys(this._localMaps.msid2ssrc).some(function (tid) {
  8742. // Search for the track id that corresponds to the ssrc
  8743. if (self._localMaps.msid2ssrc[tid] == ssrc) {
  8744. trackid = tid;
  8745. return true;
  8746. }
  8747. }) && self.localStream.getVideoTracks().some(function (track) {
  8748. // Start/stop the track that corresponds to the track id
  8749. if (track.id === trackid) {
  8750. track.enabled = enabled;
  8751. return true;
  8752. }
  8753. })) {
  8754. this.logger.log([trackid, enabled ? 'enabled' : 'disabled'].join(' '));
  8755. $(document).trigger(enabled
  8756. ? 'simulcastlayerstarted'
  8757. : 'simulcastlayerstopped');
  8758. } else {
  8759. this.logger.error("I don't have a local stream with SSRC " + ssrc);
  8760. }
  8761. };
  8762. SimpleSimulcastSender.prototype.constructor = SimpleSimulcastSender;
  8763. function NoSimulcastSender() {
  8764. SimulcastSender.call(this);
  8765. }
  8766. NoSimulcastSender.prototype = Object.create(SimulcastSender.prototype);
  8767. /**
  8768. * GUM for simulcast.
  8769. *
  8770. * @param constraints
  8771. * @param success
  8772. * @param err
  8773. */
  8774. NoSimulcastSender.prototype.getUserMedia = function (constraints, success, err) {
  8775. navigator.webkitGetUserMedia(constraints, function (hqStream) {
  8776. success(hqStream);
  8777. }, err);
  8778. };
  8779. /**
  8780. * Prepares the local description for public usage (i.e. to be signaled
  8781. * through Jingle to the focus).
  8782. *
  8783. * @param desc
  8784. * @returns {RTCSessionDescription}
  8785. */
  8786. NoSimulcastSender.prototype.reverseTransformLocalDescription = function (desc) {
  8787. return desc;
  8788. };
  8789. /**
  8790. * Ensures that the simulcast group is present in the answer, _if_ native
  8791. * simulcast is enabled,
  8792. *
  8793. * @param desc
  8794. * @returns {*}
  8795. */
  8796. NoSimulcastSender.prototype.transformAnswer = function (desc) {
  8797. return desc;
  8798. };
  8799. /**
  8800. *
  8801. *
  8802. * @param desc
  8803. * @returns {*}
  8804. */
  8805. NoSimulcastSender.prototype.transformLocalDescription = function (desc) {
  8806. return desc;
  8807. };
  8808. NoSimulcastSender.prototype._setLocalVideoStreamEnabled = function (ssrc, enabled) {
  8809. };
  8810. NoSimulcastSender.prototype.constructor = NoSimulcastSender;
  8811. module.exports = {
  8812. "native": NativeSimulcastSender,
  8813. "no": NoSimulcastSender
  8814. }
  8815. },{"./SimulcastLogger":38,"./SimulcastUtils":41}],41:[function(require,module,exports){
  8816. var SimulcastLogger = require("./SimulcastLogger");
  8817. /**
  8818. *
  8819. * @constructor
  8820. */
  8821. function SimulcastUtils() {
  8822. this.logger = new SimulcastLogger("SimulcastUtils", 1);
  8823. }
  8824. /**
  8825. *
  8826. * @type {{}}
  8827. * @private
  8828. */
  8829. SimulcastUtils.prototype._emptyCompoundIndex = {};
  8830. /**
  8831. *
  8832. * @param lines
  8833. * @param videoSources
  8834. * @private
  8835. */
  8836. SimulcastUtils.prototype._replaceVideoSources = function (lines, videoSources) {
  8837. var i, inVideo = false, index = -1, howMany = 0;
  8838. this.logger.info('Replacing video sources...');
  8839. for (i = 0; i < lines.length; i++) {
  8840. if (inVideo && lines[i].substring(0, 'm='.length) === 'm=') {
  8841. // Out of video.
  8842. break;
  8843. }
  8844. if (!inVideo && lines[i].substring(0, 'm=video '.length) === 'm=video ') {
  8845. // In video.
  8846. inVideo = true;
  8847. }
  8848. if (inVideo && (lines[i].substring(0, 'a=ssrc:'.length) === 'a=ssrc:'
  8849. || lines[i].substring(0, 'a=ssrc-group:'.length) === 'a=ssrc-group:')) {
  8850. if (index === -1) {
  8851. index = i;
  8852. }
  8853. howMany++;
  8854. }
  8855. }
  8856. // efficiency baby ;)
  8857. lines.splice.apply(lines,
  8858. [index, howMany].concat(videoSources));
  8859. };
  8860. SimulcastUtils.prototype.isValidDescription = function (desc)
  8861. {
  8862. return desc && desc != null
  8863. && desc.type && desc.type != ''
  8864. && desc.sdp && desc.sdp != '';
  8865. };
  8866. SimulcastUtils.prototype._getVideoSources = function (lines) {
  8867. var i, inVideo = false, sb = [];
  8868. this.logger.info('Getting video sources...');
  8869. for (i = 0; i < lines.length; i++) {
  8870. if (inVideo && lines[i].substring(0, 'm='.length) === 'm=') {
  8871. // Out of video.
  8872. break;
  8873. }
  8874. if (!inVideo && lines[i].substring(0, 'm=video '.length) === 'm=video ') {
  8875. // In video.
  8876. inVideo = true;
  8877. }
  8878. if (inVideo && lines[i].substring(0, 'a=ssrc:'.length) === 'a=ssrc:') {
  8879. // In SSRC.
  8880. sb.push(lines[i]);
  8881. }
  8882. if (inVideo && lines[i].substring(0, 'a=ssrc-group:'.length) === 'a=ssrc-group:') {
  8883. sb.push(lines[i]);
  8884. }
  8885. }
  8886. return sb;
  8887. };
  8888. SimulcastUtils.prototype.parseMedia = function (lines, mediatypes) {
  8889. var i, res = [], type, cur_media, idx, ssrcs, cur_ssrc, ssrc,
  8890. ssrc_attribute, group, semantics, skip = true;
  8891. this.logger.info('Parsing media sources...');
  8892. for (i = 0; i < lines.length; i++) {
  8893. if (lines[i].substring(0, 'm='.length) === 'm=') {
  8894. type = lines[i]
  8895. .substr('m='.length, lines[i].indexOf(' ') - 'm='.length);
  8896. skip = mediatypes !== undefined && mediatypes.indexOf(type) === -1;
  8897. if (!skip) {
  8898. cur_media = {
  8899. 'type': type,
  8900. 'sources': {},
  8901. 'groups': []
  8902. };
  8903. res.push(cur_media);
  8904. }
  8905. } else if (!skip && lines[i].substring(0, 'a=ssrc:'.length) === 'a=ssrc:') {
  8906. idx = lines[i].indexOf(' ');
  8907. ssrc = lines[i].substring('a=ssrc:'.length, idx);
  8908. if (cur_media.sources[ssrc] === undefined) {
  8909. cur_ssrc = {'ssrc': ssrc};
  8910. cur_media.sources[ssrc] = cur_ssrc;
  8911. }
  8912. ssrc_attribute = lines[i].substr(idx + 1).split(':', 2)[0];
  8913. cur_ssrc[ssrc_attribute] = lines[i].substr(idx + 1).split(':', 2)[1];
  8914. if (cur_media.base === undefined) {
  8915. cur_media.base = cur_ssrc;
  8916. }
  8917. } else if (!skip && lines[i].substring(0, 'a=ssrc-group:'.length) === 'a=ssrc-group:') {
  8918. idx = lines[i].indexOf(' ');
  8919. semantics = lines[i].substr(0, idx).substr('a=ssrc-group:'.length);
  8920. ssrcs = lines[i].substr(idx).trim().split(' ');
  8921. group = {
  8922. 'semantics': semantics,
  8923. 'ssrcs': ssrcs
  8924. };
  8925. cur_media.groups.push(group);
  8926. } else if (!skip && (lines[i].substring(0, 'a=sendrecv'.length) === 'a=sendrecv' ||
  8927. lines[i].substring(0, 'a=recvonly'.length) === 'a=recvonly' ||
  8928. lines[i].substring(0, 'a=sendonly'.length) === 'a=sendonly' ||
  8929. lines[i].substring(0, 'a=inactive'.length) === 'a=inactive')) {
  8930. cur_media.direction = lines[i].substring('a='.length);
  8931. }
  8932. }
  8933. return res;
  8934. };
  8935. /**
  8936. * The _indexOfArray() method returns the first a CompoundIndex at which a
  8937. * given element can be found in the array, or _emptyCompoundIndex if it is
  8938. * not present.
  8939. *
  8940. * Example:
  8941. *
  8942. * _indexOfArray('3', [ 'this is line 1', 'this is line 2', 'this is line 3' ])
  8943. *
  8944. * returns {row: 2, column: 14}
  8945. *
  8946. * @param needle
  8947. * @param haystack
  8948. * @param start
  8949. * @returns {}
  8950. * @private
  8951. */
  8952. SimulcastUtils.prototype._indexOfArray = function (needle, haystack, start) {
  8953. var length = haystack.length, idx, i;
  8954. if (!start) {
  8955. start = 0;
  8956. }
  8957. for (i = start; i < length; i++) {
  8958. idx = haystack[i].indexOf(needle);
  8959. if (idx !== -1) {
  8960. return {row: i, column: idx};
  8961. }
  8962. }
  8963. return this._emptyCompoundIndex;
  8964. };
  8965. SimulcastUtils.prototype._removeSimulcastGroup = function (lines) {
  8966. var i;
  8967. for (i = lines.length - 1; i >= 0; i--) {
  8968. if (lines[i].indexOf('a=ssrc-group:SIM') !== -1) {
  8969. lines.splice(i, 1);
  8970. }
  8971. }
  8972. };
  8973. SimulcastUtils.prototype._compileVideoSources = function (videoSources) {
  8974. var sb = [], ssrc, addedSSRCs = [];
  8975. this.logger.info('Compiling video sources...');
  8976. // Add the groups
  8977. if (videoSources.groups && videoSources.groups.length !== 0) {
  8978. videoSources.groups.forEach(function (group) {
  8979. if (group.ssrcs && group.ssrcs.length !== 0) {
  8980. sb.push([['a=ssrc-group:', group.semantics].join(''), group.ssrcs.join(' ')].join(' '));
  8981. // if (group.semantics !== 'SIM') {
  8982. group.ssrcs.forEach(function (ssrc) {
  8983. addedSSRCs.push(ssrc);
  8984. sb.splice.apply(sb, [sb.length, 0].concat([
  8985. ["a=ssrc:", ssrc, " cname:", videoSources.sources[ssrc].cname].join(''),
  8986. ["a=ssrc:", ssrc, " msid:", videoSources.sources[ssrc].msid].join('')]));
  8987. });
  8988. //}
  8989. }
  8990. });
  8991. }
  8992. // Then add any free sources.
  8993. if (videoSources.sources) {
  8994. for (ssrc in videoSources.sources) {
  8995. if (addedSSRCs.indexOf(ssrc) === -1) {
  8996. sb.splice.apply(sb, [sb.length, 0].concat([
  8997. ["a=ssrc:", ssrc, " cname:", videoSources.sources[ssrc].cname].join(''),
  8998. ["a=ssrc:", ssrc, " msid:", videoSources.sources[ssrc].msid].join('')]));
  8999. }
  9000. }
  9001. }
  9002. return sb;
  9003. };
  9004. module.exports = SimulcastUtils;
  9005. },{"./SimulcastLogger":38}],42:[function(require,module,exports){
  9006. /*jslint plusplus: true */
  9007. /*jslint nomen: true*/
  9008. var SimulcastSender = require("./SimulcastSender");
  9009. var NoSimulcastSender = SimulcastSender["no"];
  9010. var NativeSimulcastSender = SimulcastSender["native"];
  9011. var SimulcastReceiver = require("./SimulcastReceiver");
  9012. var SimulcastUtils = require("./SimulcastUtils");
  9013. var RTCEvents = require("../../service/RTC/RTCEvents");
  9014. /**
  9015. *
  9016. * @constructor
  9017. */
  9018. function SimulcastManager() {
  9019. // Create the simulcast utilities.
  9020. this.simulcastUtils = new SimulcastUtils();
  9021. // Create remote simulcast.
  9022. this.simulcastReceiver = new SimulcastReceiver();
  9023. // Initialize local simulcast.
  9024. // TODO(gp) move into SimulcastManager.prototype.getUserMedia and take into
  9025. // account constraints.
  9026. if (!config.enableSimulcast) {
  9027. this.simulcastSender = new NoSimulcastSender();
  9028. } else {
  9029. var isChromium = window.chrome,
  9030. vendorName = window.navigator.vendor;
  9031. if(isChromium !== null && isChromium !== undefined
  9032. /* skip opera */
  9033. && vendorName === "Google Inc."
  9034. /* skip Chromium as suggested by fippo */
  9035. && !window.navigator.appVersion.match(/Chromium\//) ) {
  9036. var ver = parseInt(window.navigator.appVersion.match(/Chrome\/(\d+)\./)[1], 10);
  9037. if (ver > 37) {
  9038. this.simulcastSender = new NativeSimulcastSender();
  9039. } else {
  9040. this.simulcastSender = new NoSimulcastSender();
  9041. }
  9042. } else {
  9043. this.simulcastSender = new NoSimulcastSender();
  9044. }
  9045. }
  9046. APP.RTC.addListener(RTCEvents.SIMULCAST_LAYER_CHANGED,
  9047. function (endpointSimulcastLayers) {
  9048. endpointSimulcastLayers.forEach(function (esl) {
  9049. var ssrc = esl.simulcastLayer.primarySSRC;
  9050. simulcast._setReceivingVideoStream(esl.endpoint, ssrc);
  9051. });
  9052. });
  9053. APP.RTC.addListener(RTCEvents.SIMULCAST_START, function (simulcastLayer) {
  9054. var ssrc = simulcastLayer.primarySSRC;
  9055. simulcast._setLocalVideoStreamEnabled(ssrc, true);
  9056. });
  9057. APP.RTC.addListener(RTCEvents.SIMULCAST_STOP, function (simulcastLayer) {
  9058. var ssrc = simulcastLayer.primarySSRC;
  9059. simulcast._setLocalVideoStreamEnabled(ssrc, false);
  9060. });
  9061. }
  9062. /**
  9063. * Restores the simulcast groups of the remote description. In
  9064. * transformRemoteDescription we remove those in order for the set remote
  9065. * description to succeed. The focus needs the signal the groups to new
  9066. * participants.
  9067. *
  9068. * @param desc
  9069. * @returns {*}
  9070. */
  9071. SimulcastManager.prototype.reverseTransformRemoteDescription = function (desc) {
  9072. return this.simulcastReceiver.reverseTransformRemoteDescription(desc);
  9073. };
  9074. /**
  9075. * Removes the ssrc-group:SIM from the remote description bacause Chrome
  9076. * either gets confused and thinks this is an FID group or, if an FID group
  9077. * is already present, it fails to set the remote description.
  9078. *
  9079. * @param desc
  9080. * @returns {*}
  9081. */
  9082. SimulcastManager.prototype.transformRemoteDescription = function (desc) {
  9083. return this.simulcastReceiver.transformRemoteDescription(desc);
  9084. };
  9085. /**
  9086. * Gets the fully qualified msid (stream.id + track.id) associated to the
  9087. * SSRC.
  9088. *
  9089. * @param ssrc
  9090. * @returns {*}
  9091. */
  9092. SimulcastManager.prototype.getRemoteVideoStreamIdBySSRC = function (ssrc) {
  9093. return this.simulcastReceiver.getRemoteVideoStreamIdBySSRC(ssrc);
  9094. };
  9095. /**
  9096. * Returns a stream with single video track, the one currently being
  9097. * received by this endpoint.
  9098. *
  9099. * @param stream the remote simulcast stream.
  9100. * @returns {webkitMediaStream}
  9101. */
  9102. SimulcastManager.prototype.getReceivingVideoStream = function (stream) {
  9103. return this.simulcastReceiver.getReceivingVideoStream(stream);
  9104. };
  9105. /**
  9106. *
  9107. *
  9108. * @param desc
  9109. * @returns {*}
  9110. */
  9111. SimulcastManager.prototype.transformLocalDescription = function (desc) {
  9112. return this.simulcastSender.transformLocalDescription(desc);
  9113. };
  9114. /**
  9115. *
  9116. * @returns {*}
  9117. */
  9118. SimulcastManager.prototype.getLocalVideoStream = function() {
  9119. return this.simulcastSender.getLocalVideoStream();
  9120. };
  9121. /**
  9122. * GUM for simulcast.
  9123. *
  9124. * @param constraints
  9125. * @param success
  9126. * @param err
  9127. */
  9128. SimulcastManager.prototype.getUserMedia = function (constraints, success, err) {
  9129. this.simulcastSender.getUserMedia(constraints, success, err);
  9130. };
  9131. /**
  9132. * Prepares the local description for public usage (i.e. to be signaled
  9133. * through Jingle to the focus).
  9134. *
  9135. * @param desc
  9136. * @returns {RTCSessionDescription}
  9137. */
  9138. SimulcastManager.prototype.reverseTransformLocalDescription = function (desc) {
  9139. return this.simulcastSender.reverseTransformLocalDescription(desc);
  9140. };
  9141. /**
  9142. * Ensures that the simulcast group is present in the answer, _if_ native
  9143. * simulcast is enabled,
  9144. *
  9145. * @param desc
  9146. * @returns {*}
  9147. */
  9148. SimulcastManager.prototype.transformAnswer = function (desc) {
  9149. return this.simulcastSender.transformAnswer(desc);
  9150. };
  9151. SimulcastManager.prototype.getReceivingSSRC = function (jid) {
  9152. return this.simulcastReceiver.getReceivingSSRC(jid);
  9153. };
  9154. SimulcastManager.prototype.getReceivingVideoStreamBySSRC = function (msid) {
  9155. return this.simulcastReceiver.getReceivingVideoStreamBySSRC(msid);
  9156. };
  9157. /**
  9158. *
  9159. * @param lines
  9160. * @param mediatypes
  9161. * @returns {*}
  9162. */
  9163. SimulcastManager.prototype.parseMedia = function(lines, mediatypes) {
  9164. var sb = lines.sdp.split('\r\n');
  9165. return this.simulcastUtils.parseMedia(sb, mediatypes);
  9166. };
  9167. SimulcastManager.prototype._setReceivingVideoStream = function(resource, ssrc) {
  9168. this.simulcastReceiver._setReceivingVideoStream(resource, ssrc);
  9169. };
  9170. SimulcastManager.prototype._setLocalVideoStreamEnabled = function(ssrc, enabled) {
  9171. this.simulcastSender._setLocalVideoStreamEnabled(ssrc, enabled);
  9172. };
  9173. SimulcastManager.prototype.resetSender = function() {
  9174. if (typeof this.simulcastSender.reset === 'function'){
  9175. this.simulcastSender.reset();
  9176. }
  9177. };
  9178. var simulcast = new SimulcastManager();
  9179. module.exports = simulcast;
  9180. },{"../../service/RTC/RTCEvents":88,"./SimulcastReceiver":39,"./SimulcastSender":40,"./SimulcastUtils":41}],43:[function(require,module,exports){
  9181. /**
  9182. * Provides statistics for the local stream.
  9183. */
  9184. /**
  9185. * Size of the webaudio analizer buffer.
  9186. * @type {number}
  9187. */
  9188. var WEBAUDIO_ANALIZER_FFT_SIZE = 2048;
  9189. /**
  9190. * Value of the webaudio analizer smoothing time parameter.
  9191. * @type {number}
  9192. */
  9193. var WEBAUDIO_ANALIZER_SMOOTING_TIME = 0.8;
  9194. /**
  9195. * Converts time domain data array to audio level.
  9196. * @param array the time domain data array.
  9197. * @returns {number} the audio level
  9198. */
  9199. function timeDomainDataToAudioLevel(samples) {
  9200. var maxVolume = 0;
  9201. var length = samples.length;
  9202. for (var i = 0; i < length; i++) {
  9203. if (maxVolume < samples[i])
  9204. maxVolume = samples[i];
  9205. }
  9206. return parseFloat(((maxVolume - 127) / 128).toFixed(3));
  9207. };
  9208. /**
  9209. * Animates audio level change
  9210. * @param newLevel the new audio level
  9211. * @param lastLevel the last audio level
  9212. * @returns {Number} the audio level to be set
  9213. */
  9214. function animateLevel(newLevel, lastLevel)
  9215. {
  9216. var value = 0;
  9217. var diff = lastLevel - newLevel;
  9218. if(diff > 0.2)
  9219. {
  9220. value = lastLevel - 0.2;
  9221. }
  9222. else if(diff < -0.4)
  9223. {
  9224. value = lastLevel + 0.4;
  9225. }
  9226. else
  9227. {
  9228. value = newLevel;
  9229. }
  9230. return parseFloat(value.toFixed(3));
  9231. }
  9232. /**
  9233. * <tt>LocalStatsCollector</tt> calculates statistics for the local stream.
  9234. *
  9235. * @param stream the local stream
  9236. * @param interval stats refresh interval given in ms.
  9237. * @param {function(LocalStatsCollector)} updateCallback the callback called on stats
  9238. * update.
  9239. * @constructor
  9240. */
  9241. function LocalStatsCollector(stream, interval, statisticsService, eventEmitter) {
  9242. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  9243. this.stream = stream;
  9244. this.intervalId = null;
  9245. this.intervalMilis = interval;
  9246. this.eventEmitter = eventEmitter;
  9247. this.audioLevel = 0;
  9248. this.statisticsService = statisticsService;
  9249. }
  9250. /**
  9251. * Starts the collecting the statistics.
  9252. */
  9253. LocalStatsCollector.prototype.start = function () {
  9254. if (config.disableAudioLevels || !window.AudioContext)
  9255. return;
  9256. var context = new AudioContext();
  9257. var analyser = context.createAnalyser();
  9258. analyser.smoothingTimeConstant = WEBAUDIO_ANALIZER_SMOOTING_TIME;
  9259. analyser.fftSize = WEBAUDIO_ANALIZER_FFT_SIZE;
  9260. var source = context.createMediaStreamSource(this.stream);
  9261. source.connect(analyser);
  9262. var self = this;
  9263. this.intervalId = setInterval(
  9264. function () {
  9265. var array = new Uint8Array(analyser.frequencyBinCount);
  9266. analyser.getByteTimeDomainData(array);
  9267. var audioLevel = timeDomainDataToAudioLevel(array);
  9268. if(audioLevel != self.audioLevel) {
  9269. self.audioLevel = animateLevel(audioLevel, self.audioLevel);
  9270. self.eventEmitter.emit(
  9271. "statistics.audioLevel",
  9272. self.statisticsService.LOCAL_JID,
  9273. self.audioLevel);
  9274. }
  9275. },
  9276. this.intervalMilis
  9277. );
  9278. };
  9279. /**
  9280. * Stops collecting the statistics.
  9281. */
  9282. LocalStatsCollector.prototype.stop = function () {
  9283. if (this.intervalId) {
  9284. clearInterval(this.intervalId);
  9285. this.intervalId = null;
  9286. }
  9287. };
  9288. module.exports = LocalStatsCollector;
  9289. },{}],44:[function(require,module,exports){
  9290. /* global ssrc2jid */
  9291. /* jshint -W117 */
  9292. var RTCBrowserType = require("../../service/RTC/RTCBrowserType");
  9293. /**
  9294. * Calculates packet lost percent using the number of lost packets and the
  9295. * number of all packet.
  9296. * @param lostPackets the number of lost packets
  9297. * @param totalPackets the number of all packets.
  9298. * @returns {number} packet loss percent
  9299. */
  9300. function calculatePacketLoss(lostPackets, totalPackets) {
  9301. if(!totalPackets || totalPackets <= 0 || !lostPackets || lostPackets <= 0)
  9302. return 0;
  9303. return Math.round((lostPackets/totalPackets)*100);
  9304. }
  9305. function getStatValue(item, name) {
  9306. if(!keyMap[APP.RTC.getBrowserType()][name])
  9307. throw "The property isn't supported!";
  9308. var key = keyMap[APP.RTC.getBrowserType()][name];
  9309. return APP.RTC.getBrowserType() == RTCBrowserType.RTC_BROWSER_CHROME? item.stat(key) : item[key];
  9310. }
  9311. /**
  9312. * Peer statistics data holder.
  9313. * @constructor
  9314. */
  9315. function PeerStats()
  9316. {
  9317. this.ssrc2Loss = {};
  9318. this.ssrc2AudioLevel = {};
  9319. this.ssrc2bitrate = {};
  9320. this.ssrc2resolution = {};
  9321. }
  9322. /**
  9323. * The bandwidth
  9324. * @type {{}}
  9325. */
  9326. PeerStats.bandwidth = {};
  9327. /**
  9328. * The bit rate
  9329. * @type {{}}
  9330. */
  9331. PeerStats.bitrate = {};
  9332. /**
  9333. * The packet loss rate
  9334. * @type {{}}
  9335. */
  9336. PeerStats.packetLoss = null;
  9337. /**
  9338. * Sets packets loss rate for given <tt>ssrc</tt> that blong to the peer
  9339. * represented by this instance.
  9340. * @param ssrc audio or video RTP stream SSRC.
  9341. * @param lossRate new packet loss rate value to be set.
  9342. */
  9343. PeerStats.prototype.setSsrcLoss = function (ssrc, lossRate)
  9344. {
  9345. this.ssrc2Loss[ssrc] = lossRate;
  9346. };
  9347. /**
  9348. * Sets resolution for given <tt>ssrc</tt> that belong to the peer
  9349. * represented by this instance.
  9350. * @param ssrc audio or video RTP stream SSRC.
  9351. * @param resolution new resolution value to be set.
  9352. */
  9353. PeerStats.prototype.setSsrcResolution = function (ssrc, resolution)
  9354. {
  9355. if(resolution === null && this.ssrc2resolution[ssrc])
  9356. {
  9357. delete this.ssrc2resolution[ssrc];
  9358. }
  9359. else if(resolution !== null)
  9360. this.ssrc2resolution[ssrc] = resolution;
  9361. };
  9362. /**
  9363. * Sets the bit rate for given <tt>ssrc</tt> that blong to the peer
  9364. * represented by this instance.
  9365. * @param ssrc audio or video RTP stream SSRC.
  9366. * @param bitrate new bitrate value to be set.
  9367. */
  9368. PeerStats.prototype.setSsrcBitrate = function (ssrc, bitrate)
  9369. {
  9370. if(this.ssrc2bitrate[ssrc])
  9371. {
  9372. this.ssrc2bitrate[ssrc].download += bitrate.download;
  9373. this.ssrc2bitrate[ssrc].upload += bitrate.upload;
  9374. }
  9375. else {
  9376. this.ssrc2bitrate[ssrc] = bitrate;
  9377. }
  9378. };
  9379. /**
  9380. * Sets new audio level(input or output) for given <tt>ssrc</tt> that identifies
  9381. * the stream which belongs to the peer represented by this instance.
  9382. * @param ssrc RTP stream SSRC for which current audio level value will be
  9383. * updated.
  9384. * @param audioLevel the new audio level value to be set. Value is truncated to
  9385. * fit the range from 0 to 1.
  9386. */
  9387. PeerStats.prototype.setSsrcAudioLevel = function (ssrc, audioLevel)
  9388. {
  9389. // Range limit 0 - 1
  9390. this.ssrc2AudioLevel[ssrc] = formatAudioLevel(audioLevel);
  9391. };
  9392. function formatAudioLevel(audioLevel) {
  9393. return Math.min(Math.max(audioLevel, 0), 1);
  9394. }
  9395. /**
  9396. * Array with the transport information.
  9397. * @type {Array}
  9398. */
  9399. PeerStats.transport = [];
  9400. /**
  9401. * <tt>StatsCollector</tt> registers for stats updates of given
  9402. * <tt>peerconnection</tt> in given <tt>interval</tt>. On each update particular
  9403. * stats are extracted and put in {@link PeerStats} objects. Once the processing
  9404. * is done <tt>audioLevelsUpdateCallback</tt> is called with <tt>this</tt>
  9405. * instance as an event source.
  9406. *
  9407. * @param peerconnection webRTC peer connection object.
  9408. * @param interval stats refresh interval given in ms.
  9409. * @param {function(StatsCollector)} audioLevelsUpdateCallback the callback
  9410. * called on stats update.
  9411. * @constructor
  9412. */
  9413. function StatsCollector(peerconnection, audioLevelsInterval, statsInterval, eventEmitter)
  9414. {
  9415. this.peerconnection = peerconnection;
  9416. this.baselineAudioLevelsReport = null;
  9417. this.currentAudioLevelsReport = null;
  9418. this.currentStatsReport = null;
  9419. this.baselineStatsReport = null;
  9420. this.audioLevelsIntervalId = null;
  9421. this.eventEmitter = eventEmitter;
  9422. /**
  9423. * Gather PeerConnection stats once every this many milliseconds.
  9424. */
  9425. this.GATHER_INTERVAL = 15000;
  9426. /**
  9427. * Log stats via the focus once every this many milliseconds.
  9428. */
  9429. this.LOG_INTERVAL = 60000;
  9430. /**
  9431. * Gather stats and store them in this.statsToBeLogged.
  9432. */
  9433. this.gatherStatsIntervalId = null;
  9434. /**
  9435. * Send the stats already saved in this.statsToBeLogged to be logged via
  9436. * the focus.
  9437. */
  9438. this.logStatsIntervalId = null;
  9439. /**
  9440. * Stores the statistics which will be send to the focus to be logged.
  9441. */
  9442. this.statsToBeLogged =
  9443. {
  9444. timestamps: [],
  9445. stats: {}
  9446. };
  9447. // Updates stats interval
  9448. this.audioLevelsIntervalMilis = audioLevelsInterval;
  9449. this.statsIntervalId = null;
  9450. this.statsIntervalMilis = statsInterval;
  9451. // Map of jids to PeerStats
  9452. this.jid2stats = {};
  9453. }
  9454. module.exports = StatsCollector;
  9455. /**
  9456. * Stops stats updates.
  9457. */
  9458. StatsCollector.prototype.stop = function () {
  9459. if (this.audioLevelsIntervalId) {
  9460. clearInterval(this.audioLevelsIntervalId);
  9461. this.audioLevelsIntervalId = null;
  9462. }
  9463. if (this.statsIntervalId)
  9464. {
  9465. clearInterval(this.statsIntervalId);
  9466. this.statsIntervalId = null;
  9467. }
  9468. if(this.logStatsIntervalId)
  9469. {
  9470. clearInterval(this.logStatsIntervalId);
  9471. this.logStatsIntervalId = null;
  9472. }
  9473. if(this.gatherStatsIntervalId)
  9474. {
  9475. clearInterval(this.gatherStatsIntervalId);
  9476. this.gatherStatsIntervalId = null;
  9477. }
  9478. };
  9479. /**
  9480. * Callback passed to <tt>getStats</tt> method.
  9481. * @param error an error that occurred on <tt>getStats</tt> call.
  9482. */
  9483. StatsCollector.prototype.errorCallback = function (error)
  9484. {
  9485. console.error("Get stats error", error);
  9486. this.stop();
  9487. };
  9488. /**
  9489. * Starts stats updates.
  9490. */
  9491. StatsCollector.prototype.start = function ()
  9492. {
  9493. var self = this;
  9494. if(!config.disableAudioLevels) {
  9495. console.debug("set audio levels interval");
  9496. this.audioLevelsIntervalId = setInterval(
  9497. function () {
  9498. // Interval updates
  9499. self.peerconnection.getStats(
  9500. function (report) {
  9501. var results = null;
  9502. if (!report || !report.result ||
  9503. typeof report.result != 'function') {
  9504. results = report;
  9505. }
  9506. else {
  9507. results = report.result();
  9508. }
  9509. //console.error("Got interval report", results);
  9510. self.currentAudioLevelsReport = results;
  9511. self.processAudioLevelReport();
  9512. self.baselineAudioLevelsReport =
  9513. self.currentAudioLevelsReport;
  9514. },
  9515. self.errorCallback
  9516. );
  9517. },
  9518. self.audioLevelsIntervalMilis
  9519. );
  9520. }
  9521. if(!config.disableStats) {
  9522. console.debug("set stats interval");
  9523. this.statsIntervalId = setInterval(
  9524. function () {
  9525. // Interval updates
  9526. self.peerconnection.getStats(
  9527. function (report) {
  9528. var results = null;
  9529. if (!report || !report.result ||
  9530. typeof report.result != 'function') {
  9531. //firefox
  9532. results = report;
  9533. }
  9534. else {
  9535. //chrome
  9536. results = report.result();
  9537. }
  9538. //console.error("Got interval report", results);
  9539. self.currentStatsReport = results;
  9540. try {
  9541. self.processStatsReport();
  9542. }
  9543. catch (e) {
  9544. console.error("Unsupported key:" + e, e);
  9545. }
  9546. self.baselineStatsReport = self.currentStatsReport;
  9547. },
  9548. self.errorCallback
  9549. );
  9550. },
  9551. self.statsIntervalMilis
  9552. );
  9553. }
  9554. if (config.logStats) {
  9555. this.gatherStatsIntervalId = setInterval(
  9556. function () {
  9557. self.peerconnection.getStats(
  9558. function (report) {
  9559. self.addStatsToBeLogged(report.result());
  9560. },
  9561. function () {
  9562. }
  9563. );
  9564. },
  9565. this.GATHER_INTERVAL
  9566. );
  9567. this.logStatsIntervalId = setInterval(
  9568. function() { self.logStats(); },
  9569. this.LOG_INTERVAL);
  9570. }
  9571. };
  9572. /**
  9573. * Checks whether a certain record should be included in the logged statistics.
  9574. */
  9575. function acceptStat(reportId, reportType, statName) {
  9576. if (reportType == "googCandidatePair" && statName == "googChannelId")
  9577. return false;
  9578. if (reportType == "ssrc") {
  9579. if (statName == "googTrackId" ||
  9580. statName == "transportId" ||
  9581. statName == "ssrc")
  9582. return false;
  9583. }
  9584. return true;
  9585. }
  9586. /**
  9587. * Checks whether a certain record should be included in the logged statistics.
  9588. */
  9589. function acceptReport(id, type) {
  9590. if (id.substring(0, 15) == "googCertificate" ||
  9591. id.substring(0, 9) == "googTrack" ||
  9592. id.substring(0, 20) == "googLibjingleSession")
  9593. return false;
  9594. if (type == "googComponent")
  9595. return false;
  9596. return true;
  9597. }
  9598. /**
  9599. * Converts the stats to the format used for logging, and saves the data in
  9600. * this.statsToBeLogged.
  9601. * @param reports Reports as given by webkitRTCPerConnection.getStats.
  9602. */
  9603. StatsCollector.prototype.addStatsToBeLogged = function (reports) {
  9604. var self = this;
  9605. var num_records = this.statsToBeLogged.timestamps.length;
  9606. this.statsToBeLogged.timestamps.push(new Date().getTime());
  9607. reports.map(function (report) {
  9608. if (!acceptReport(report.id, report.type))
  9609. return;
  9610. var stat = self.statsToBeLogged.stats[report.id];
  9611. if (!stat) {
  9612. stat = self.statsToBeLogged.stats[report.id] = {};
  9613. }
  9614. stat.type = report.type;
  9615. report.names().map(function (name) {
  9616. if (!acceptStat(report.id, report.type, name))
  9617. return;
  9618. var values = stat[name];
  9619. if (!values) {
  9620. values = stat[name] = [];
  9621. }
  9622. while (values.length < num_records) {
  9623. values.push(null);
  9624. }
  9625. values.push(report.stat(name));
  9626. });
  9627. });
  9628. };
  9629. StatsCollector.prototype.logStats = function () {
  9630. if(!APP.xmpp.sendLogs(this.statsToBeLogged))
  9631. return;
  9632. // Reset the stats
  9633. this.statsToBeLogged.stats = {};
  9634. this.statsToBeLogged.timestamps = [];
  9635. };
  9636. var keyMap = {};
  9637. keyMap[RTCBrowserType.RTC_BROWSER_FIREFOX] = {
  9638. "ssrc": "ssrc",
  9639. "packetsReceived": "packetsReceived",
  9640. "packetsLost": "packetsLost",
  9641. "packetsSent": "packetsSent",
  9642. "bytesReceived": "bytesReceived",
  9643. "bytesSent": "bytesSent"
  9644. };
  9645. keyMap[RTCBrowserType.RTC_BROWSER_CHROME] = {
  9646. "receiveBandwidth": "googAvailableReceiveBandwidth",
  9647. "sendBandwidth": "googAvailableSendBandwidth",
  9648. "remoteAddress": "googRemoteAddress",
  9649. "transportType": "googTransportType",
  9650. "localAddress": "googLocalAddress",
  9651. "activeConnection": "googActiveConnection",
  9652. "ssrc": "ssrc",
  9653. "packetsReceived": "packetsReceived",
  9654. "packetsSent": "packetsSent",
  9655. "packetsLost": "packetsLost",
  9656. "bytesReceived": "bytesReceived",
  9657. "bytesSent": "bytesSent",
  9658. "googFrameHeightReceived": "googFrameHeightReceived",
  9659. "googFrameWidthReceived": "googFrameWidthReceived",
  9660. "googFrameHeightSent": "googFrameHeightSent",
  9661. "googFrameWidthSent": "googFrameWidthSent",
  9662. "audioInputLevel": "audioInputLevel",
  9663. "audioOutputLevel": "audioOutputLevel"
  9664. };
  9665. /**
  9666. * Stats processing logic.
  9667. */
  9668. StatsCollector.prototype.processStatsReport = function () {
  9669. if (!this.baselineStatsReport) {
  9670. return;
  9671. }
  9672. for (var idx in this.currentStatsReport) {
  9673. var now = this.currentStatsReport[idx];
  9674. try {
  9675. if (getStatValue(now, 'receiveBandwidth') ||
  9676. getStatValue(now, 'sendBandwidth')) {
  9677. PeerStats.bandwidth = {
  9678. "download": Math.round(
  9679. (getStatValue(now, 'receiveBandwidth')) / 1000),
  9680. "upload": Math.round(
  9681. (getStatValue(now, 'sendBandwidth')) / 1000)
  9682. };
  9683. }
  9684. }
  9685. catch(e){/*not supported*/}
  9686. if(now.type == 'googCandidatePair')
  9687. {
  9688. var ip, type, localIP, active;
  9689. try {
  9690. ip = getStatValue(now, 'remoteAddress');
  9691. type = getStatValue(now, "transportType");
  9692. localIP = getStatValue(now, "localAddress");
  9693. active = getStatValue(now, "activeConnection");
  9694. }
  9695. catch(e){/*not supported*/}
  9696. if(!ip || !type || !localIP || active != "true")
  9697. continue;
  9698. var addressSaved = false;
  9699. for(var i = 0; i < PeerStats.transport.length; i++)
  9700. {
  9701. if(PeerStats.transport[i].ip == ip &&
  9702. PeerStats.transport[i].type == type &&
  9703. PeerStats.transport[i].localip == localIP)
  9704. {
  9705. addressSaved = true;
  9706. }
  9707. }
  9708. if(addressSaved)
  9709. continue;
  9710. PeerStats.transport.push({localip: localIP, ip: ip, type: type});
  9711. continue;
  9712. }
  9713. if(now.type == "candidatepair")
  9714. {
  9715. if(now.state == "succeeded")
  9716. continue;
  9717. var local = this.currentStatsReport[now.localCandidateId];
  9718. var remote = this.currentStatsReport[now.remoteCandidateId];
  9719. PeerStats.transport.push({localip: local.ipAddress + ":" + local.portNumber,
  9720. ip: remote.ipAddress + ":" + remote.portNumber, type: local.transport});
  9721. }
  9722. if (now.type != 'ssrc' && now.type != "outboundrtp" &&
  9723. now.type != "inboundrtp") {
  9724. continue;
  9725. }
  9726. var before = this.baselineStatsReport[idx];
  9727. if (!before) {
  9728. console.warn(getStatValue(now, 'ssrc') + ' not enough data');
  9729. continue;
  9730. }
  9731. var ssrc = getStatValue(now, 'ssrc');
  9732. if(!ssrc)
  9733. continue;
  9734. var jid = APP.xmpp.getJidFromSSRC(ssrc);
  9735. if (!jid && (Date.now() - now.timestamp) < 3000) {
  9736. console.warn("No jid for ssrc: " + ssrc);
  9737. continue;
  9738. }
  9739. var jidStats = this.jid2stats[jid];
  9740. if (!jidStats) {
  9741. jidStats = new PeerStats();
  9742. this.jid2stats[jid] = jidStats;
  9743. }
  9744. var isDownloadStream = true;
  9745. var key = 'packetsReceived';
  9746. if (!getStatValue(now, key))
  9747. {
  9748. isDownloadStream = false;
  9749. key = 'packetsSent';
  9750. if (!getStatValue(now, key))
  9751. {
  9752. console.warn("No packetsReceived nor packetSent stat found");
  9753. continue;
  9754. }
  9755. }
  9756. var packetsNow = getStatValue(now, key);
  9757. if(!packetsNow || packetsNow < 0)
  9758. packetsNow = 0;
  9759. var packetsBefore = getStatValue(before, key);
  9760. if(!packetsBefore || packetsBefore < 0)
  9761. packetsBefore = 0;
  9762. var packetRate = packetsNow - packetsBefore;
  9763. if(!packetRate || packetRate < 0)
  9764. packetRate = 0;
  9765. var currentLoss = getStatValue(now, 'packetsLost');
  9766. if(!currentLoss || currentLoss < 0)
  9767. currentLoss = 0;
  9768. var previousLoss = getStatValue(before, 'packetsLost');
  9769. if(!previousLoss || previousLoss < 0)
  9770. previousLoss = 0;
  9771. var lossRate = currentLoss - previousLoss;
  9772. if(!lossRate || lossRate < 0)
  9773. lossRate = 0;
  9774. var packetsTotal = (packetRate + lossRate);
  9775. jidStats.setSsrcLoss(ssrc,
  9776. {"packetsTotal": packetsTotal,
  9777. "packetsLost": lossRate,
  9778. "isDownloadStream": isDownloadStream});
  9779. var bytesReceived = 0, bytesSent = 0;
  9780. if(getStatValue(now, "bytesReceived"))
  9781. {
  9782. bytesReceived = getStatValue(now, "bytesReceived") -
  9783. getStatValue(before, "bytesReceived");
  9784. }
  9785. if(getStatValue(now, "bytesSent"))
  9786. {
  9787. bytesSent = getStatValue(now, "bytesSent") -
  9788. getStatValue(before, "bytesSent");
  9789. }
  9790. var time = Math.round((now.timestamp - before.timestamp) / 1000);
  9791. if(bytesReceived <= 0 || time <= 0)
  9792. {
  9793. bytesReceived = 0;
  9794. }
  9795. else
  9796. {
  9797. bytesReceived = Math.round(((bytesReceived * 8) / time) / 1000);
  9798. }
  9799. if(bytesSent <= 0 || time <= 0)
  9800. {
  9801. bytesSent = 0;
  9802. }
  9803. else
  9804. {
  9805. bytesSent = Math.round(((bytesSent * 8) / time) / 1000);
  9806. }
  9807. jidStats.setSsrcBitrate(ssrc, {
  9808. "download": bytesReceived,
  9809. "upload": bytesSent});
  9810. var resolution = {height: null, width: null};
  9811. try {
  9812. if (getStatValue(now, "googFrameHeightReceived") &&
  9813. getStatValue(now, "googFrameWidthReceived")) {
  9814. resolution.height = getStatValue(now, "googFrameHeightReceived");
  9815. resolution.width = getStatValue(now, "googFrameWidthReceived");
  9816. }
  9817. else if (getStatValue(now, "googFrameHeightSent") &&
  9818. getStatValue(now, "googFrameWidthSent")) {
  9819. resolution.height = getStatValue(now, "googFrameHeightSent");
  9820. resolution.width = getStatValue(now, "googFrameWidthSent");
  9821. }
  9822. }
  9823. catch(e){/*not supported*/}
  9824. if(resolution.height && resolution.width)
  9825. {
  9826. jidStats.setSsrcResolution(ssrc, resolution);
  9827. }
  9828. else
  9829. {
  9830. jidStats.setSsrcResolution(ssrc, null);
  9831. }
  9832. }
  9833. var self = this;
  9834. // Jid stats
  9835. var totalPackets = {download: 0, upload: 0};
  9836. var lostPackets = {download: 0, upload: 0};
  9837. var bitrateDownload = 0;
  9838. var bitrateUpload = 0;
  9839. var resolutions = {};
  9840. Object.keys(this.jid2stats).forEach(
  9841. function (jid)
  9842. {
  9843. Object.keys(self.jid2stats[jid].ssrc2Loss).forEach(
  9844. function (ssrc)
  9845. {
  9846. var type = "upload";
  9847. if(self.jid2stats[jid].ssrc2Loss[ssrc].isDownloadStream)
  9848. type = "download";
  9849. totalPackets[type] +=
  9850. self.jid2stats[jid].ssrc2Loss[ssrc].packetsTotal;
  9851. lostPackets[type] +=
  9852. self.jid2stats[jid].ssrc2Loss[ssrc].packetsLost;
  9853. }
  9854. );
  9855. Object.keys(self.jid2stats[jid].ssrc2bitrate).forEach(
  9856. function (ssrc) {
  9857. bitrateDownload +=
  9858. self.jid2stats[jid].ssrc2bitrate[ssrc].download;
  9859. bitrateUpload +=
  9860. self.jid2stats[jid].ssrc2bitrate[ssrc].upload;
  9861. delete self.jid2stats[jid].ssrc2bitrate[ssrc];
  9862. }
  9863. );
  9864. resolutions[jid] = self.jid2stats[jid].ssrc2resolution;
  9865. }
  9866. );
  9867. PeerStats.bitrate = {"upload": bitrateUpload, "download": bitrateDownload};
  9868. PeerStats.packetLoss = {
  9869. total:
  9870. calculatePacketLoss(lostPackets.download + lostPackets.upload,
  9871. totalPackets.download + totalPackets.upload),
  9872. download:
  9873. calculatePacketLoss(lostPackets.download, totalPackets.download),
  9874. upload:
  9875. calculatePacketLoss(lostPackets.upload, totalPackets.upload)
  9876. };
  9877. this.eventEmitter.emit("statistics.connectionstats",
  9878. {
  9879. "bitrate": PeerStats.bitrate,
  9880. "packetLoss": PeerStats.packetLoss,
  9881. "bandwidth": PeerStats.bandwidth,
  9882. "resolution": resolutions,
  9883. "transport": PeerStats.transport
  9884. });
  9885. PeerStats.transport = [];
  9886. };
  9887. /**
  9888. * Stats processing logic.
  9889. */
  9890. StatsCollector.prototype.processAudioLevelReport = function ()
  9891. {
  9892. if (!this.baselineAudioLevelsReport)
  9893. {
  9894. return;
  9895. }
  9896. for (var idx in this.currentAudioLevelsReport)
  9897. {
  9898. var now = this.currentAudioLevelsReport[idx];
  9899. if (now.type != 'ssrc')
  9900. {
  9901. continue;
  9902. }
  9903. var before = this.baselineAudioLevelsReport[idx];
  9904. if (!before)
  9905. {
  9906. console.warn(getStatValue(now, 'ssrc') + ' not enough data');
  9907. continue;
  9908. }
  9909. var ssrc = getStatValue(now, 'ssrc');
  9910. var jid = APP.xmpp.getJidFromSSRC(ssrc);
  9911. if (!jid && (Date.now() - now.timestamp) < 3000)
  9912. {
  9913. console.warn("No jid for ssrc: " + ssrc);
  9914. continue;
  9915. }
  9916. var jidStats = this.jid2stats[jid];
  9917. if (!jidStats)
  9918. {
  9919. jidStats = new PeerStats();
  9920. this.jid2stats[jid] = jidStats;
  9921. }
  9922. // Audio level
  9923. var audioLevel = null;
  9924. try {
  9925. audioLevel = getStatValue(now, 'audioInputLevel');
  9926. if (!audioLevel)
  9927. audioLevel = getStatValue(now, 'audioOutputLevel');
  9928. }
  9929. catch(e) {/*not supported*/
  9930. console.warn("Audio Levels are not available in the statistics.");
  9931. clearInterval(this.audioLevelsIntervalId);
  9932. return;
  9933. }
  9934. if (audioLevel)
  9935. {
  9936. // TODO: can't find specs about what this value really is,
  9937. // but it seems to vary between 0 and around 32k.
  9938. audioLevel = audioLevel / 32767;
  9939. jidStats.setSsrcAudioLevel(ssrc, audioLevel);
  9940. if(jid != APP.xmpp.myJid())
  9941. this.eventEmitter.emit("statistics.audioLevel", jid, audioLevel);
  9942. }
  9943. }
  9944. };
  9945. },{"../../service/RTC/RTCBrowserType":87}],45:[function(require,module,exports){
  9946. /**
  9947. * Created by hristo on 8/4/14.
  9948. */
  9949. var LocalStats = require("./LocalStatsCollector.js");
  9950. var RTPStats = require("./RTPStatsCollector.js");
  9951. var EventEmitter = require("events");
  9952. var StreamEventTypes = require("../../service/RTC/StreamEventTypes.js");
  9953. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  9954. var eventEmitter = new EventEmitter();
  9955. var localStats = null;
  9956. var rtpStats = null;
  9957. function stopLocal()
  9958. {
  9959. if(localStats)
  9960. {
  9961. localStats.stop();
  9962. localStats = null;
  9963. }
  9964. }
  9965. function stopRemote()
  9966. {
  9967. if(rtpStats)
  9968. {
  9969. rtpStats.stop();
  9970. eventEmitter.emit("statistics.stop");
  9971. rtpStats = null;
  9972. }
  9973. }
  9974. function startRemoteStats (peerconnection) {
  9975. if(rtpStats)
  9976. {
  9977. rtpStats.stop();
  9978. rtpStats = null;
  9979. }
  9980. rtpStats = new RTPStats(peerconnection, 200, 2000, eventEmitter);
  9981. rtpStats.start();
  9982. }
  9983. function onStreamCreated(stream)
  9984. {
  9985. if(stream.getOriginalStream().getAudioTracks().length === 0)
  9986. return;
  9987. localStats = new LocalStats(stream.getOriginalStream(), 200, statistics,
  9988. eventEmitter);
  9989. localStats.start();
  9990. }
  9991. function onDisposeConference(onUnload) {
  9992. stopRemote();
  9993. if(onUnload) {
  9994. stopLocal();
  9995. eventEmitter.removeAllListeners();
  9996. }
  9997. }
  9998. var statistics =
  9999. {
  10000. /**
  10001. * Indicates that this audio level is for local jid.
  10002. * @type {string}
  10003. */
  10004. LOCAL_JID: 'local',
  10005. addAudioLevelListener: function(listener)
  10006. {
  10007. eventEmitter.on("statistics.audioLevel", listener);
  10008. },
  10009. removeAudioLevelListener: function(listener)
  10010. {
  10011. eventEmitter.removeListener("statistics.audioLevel", listener);
  10012. },
  10013. addConnectionStatsListener: function(listener)
  10014. {
  10015. eventEmitter.on("statistics.connectionstats", listener);
  10016. },
  10017. removeConnectionStatsListener: function(listener)
  10018. {
  10019. eventEmitter.removeListener("statistics.connectionstats", listener);
  10020. },
  10021. addRemoteStatsStopListener: function(listener)
  10022. {
  10023. eventEmitter.on("statistics.stop", listener);
  10024. },
  10025. removeRemoteStatsStopListener: function(listener)
  10026. {
  10027. eventEmitter.removeListener("statistics.stop", listener);
  10028. },
  10029. stop: function () {
  10030. stopLocal();
  10031. stopRemote();
  10032. if(eventEmitter)
  10033. {
  10034. eventEmitter.removeAllListeners();
  10035. }
  10036. },
  10037. stopRemoteStatistics: function()
  10038. {
  10039. stopRemote();
  10040. },
  10041. start: function () {
  10042. APP.RTC.addStreamListener(onStreamCreated,
  10043. StreamEventTypes.EVENT_TYPE_LOCAL_CREATED);
  10044. APP.xmpp.addListener(XMPPEvents.DISPOSE_CONFERENCE, onDisposeConference);
  10045. APP.xmpp.addListener(XMPPEvents.CALL_INCOMING, function (event) {
  10046. startRemoteStats(event.peerconnection);
  10047. });
  10048. }
  10049. };
  10050. module.exports = statistics;
  10051. },{"../../service/RTC/StreamEventTypes.js":90,"../../service/xmpp/XMPPEvents":96,"./LocalStatsCollector.js":43,"./RTPStatsCollector.js":44,"events":97}],46:[function(require,module,exports){
  10052. var i18n = require("i18next-client");
  10053. var languages = require("../../service/translation/languages");
  10054. var Settings = require("../settings/Settings");
  10055. var DEFAULT_LANG = languages.EN;
  10056. i18n.addPostProcessor("resolveAppName", function(value, key, options) {
  10057. return value.replace("__app__", interfaceConfig.APP_NAME);
  10058. });
  10059. var defaultOptions = {
  10060. detectLngQS: "lang",
  10061. useCookie: false,
  10062. fallbackLng: DEFAULT_LANG,
  10063. load: "unspecific",
  10064. resGetPath: 'lang/__ns__-__lng__.json',
  10065. ns: {
  10066. namespaces: ['main', 'languages'],
  10067. defaultNs: 'main'
  10068. },
  10069. lngWhitelist : languages.getLanguages(),
  10070. fallbackOnNull: true,
  10071. fallbackOnEmpty: true,
  10072. useDataAttrOptions: true,
  10073. defaultValueFromContent: false,
  10074. app: interfaceConfig.APP_NAME,
  10075. getAsync: false,
  10076. defaultValueFromContent: false,
  10077. customLoad: function(lng, ns, options, done) {
  10078. var resPath = "lang/__ns__-__lng__.json";
  10079. if(lng === languages.EN)
  10080. resPath = "lang/__ns__.json";
  10081. var url = i18n.functions.applyReplacement(resPath, { lng: lng, ns: ns });
  10082. i18n.functions.ajax({
  10083. url: url,
  10084. success: function(data, status, xhr) {
  10085. i18n.functions.log('loaded: ' + url);
  10086. done(null, data);
  10087. },
  10088. error : function(xhr, status, error) {
  10089. if ((status && status == 200) ||
  10090. (xhr && xhr.status && xhr.status == 200)) {
  10091. // file loaded but invalid json, stop waste time !
  10092. i18n.functions.error('There is a typo in: ' + url);
  10093. } else if ((status && status == 404) ||
  10094. (xhr && xhr.status && xhr.status == 404)) {
  10095. i18n.functions.log('Does not exist: ' + url);
  10096. } else {
  10097. var theStatus = status ? status :
  10098. ((xhr && xhr.status) ? xhr.status : null);
  10099. i18n.functions.log(theStatus + ' when loading ' + url);
  10100. }
  10101. done(error, {});
  10102. },
  10103. dataType: "json",
  10104. async : options.getAsync
  10105. });
  10106. }
  10107. // options for caching
  10108. // useLocalStorage: true,
  10109. // localStorageExpirationTime: 86400000 // in ms, default 1 week
  10110. };
  10111. function initCompleted(t)
  10112. {
  10113. $("[data-i18n]").i18n();
  10114. }
  10115. function checkForParameter() {
  10116. var query = window.location.search.substring(1);
  10117. var vars = query.split("&");
  10118. for (var i=0;i<vars.length;i++) {
  10119. var pair = vars[i].split("=");
  10120. if(pair[0] == "lang")
  10121. {
  10122. return pair[1];
  10123. }
  10124. }
  10125. return null;
  10126. }
  10127. module.exports = {
  10128. init: function (lang) {
  10129. var options = defaultOptions;
  10130. if(!lang)
  10131. {
  10132. lang = checkForParameter();
  10133. if(!lang)
  10134. {
  10135. var settings = Settings.getSettings();
  10136. if(settings)
  10137. lang = settings.language;
  10138. }
  10139. }
  10140. if(lang) {
  10141. options.lng = lang;
  10142. }
  10143. i18n.init(options, initCompleted);
  10144. },
  10145. translateString: function (key, options) {
  10146. return i18n.t(key, options);
  10147. },
  10148. setLanguage: function (lang) {
  10149. if(!lang)
  10150. lang = DEFAULT_LANG;
  10151. i18n.setLng(lang, defaultOptions, initCompleted);
  10152. },
  10153. getCurrentLanguage: function () {
  10154. return i18n.lng();
  10155. },
  10156. translateElement: function (selector) {
  10157. selector.i18n();
  10158. },
  10159. generateTranslatonHTML: function (key, options) {
  10160. var str = "<span data-i18n=\"" + key + "\"";
  10161. if(options)
  10162. {
  10163. str += " data-i18n-options=\"" + JSON.stringify(options) + "\"";
  10164. }
  10165. str += ">";
  10166. str += this.translateString(key, options);
  10167. str += "</span>";
  10168. return str;
  10169. }
  10170. };
  10171. },{"../../service/translation/languages":95,"../settings/Settings":37,"i18next-client":61}],47:[function(require,module,exports){
  10172. /* jshint -W117 */
  10173. var TraceablePeerConnection = require("./TraceablePeerConnection");
  10174. var SDPDiffer = require("./SDPDiffer");
  10175. var SDPUtil = require("./SDPUtil");
  10176. var SDP = require("./SDP");
  10177. var RTCBrowserType = require("../../service/RTC/RTCBrowserType");
  10178. // Jingle stuff
  10179. function JingleSession(me, sid, connection, service) {
  10180. this.me = me;
  10181. this.sid = sid;
  10182. this.connection = connection;
  10183. this.initiator = null;
  10184. this.responder = null;
  10185. this.isInitiator = null;
  10186. this.peerjid = null;
  10187. this.state = null;
  10188. this.localSDP = null;
  10189. this.remoteSDP = null;
  10190. this.relayedStreams = [];
  10191. this.startTime = null;
  10192. this.stopTime = null;
  10193. this.media_constraints = null;
  10194. this.pc_constraints = null;
  10195. this.ice_config = {};
  10196. this.drip_container = [];
  10197. this.service = service;
  10198. this.usetrickle = true;
  10199. this.usepranswer = false; // early transport warmup -- mind you, this might fail. depends on webrtc issue 1718
  10200. this.usedrip = false; // dripping is sending trickle candidates not one-by-one
  10201. this.hadstuncandidate = false;
  10202. this.hadturncandidate = false;
  10203. this.lasticecandidate = false;
  10204. this.statsinterval = null;
  10205. this.reason = null;
  10206. this.addssrc = [];
  10207. this.removessrc = [];
  10208. this.pendingop = null;
  10209. this.switchstreams = false;
  10210. this.wait = true;
  10211. this.localStreamsSSRC = null;
  10212. /**
  10213. * The indicator which determines whether the (local) video has been muted
  10214. * in response to a user command in contrast to an automatic decision made
  10215. * by the application logic.
  10216. */
  10217. this.videoMuteByUser = false;
  10218. }
  10219. //TODO: this array must be removed when firefox implement multistream support
  10220. JingleSession.notReceivedSSRCs = [];
  10221. JingleSession.prototype.initiate = function (peerjid, isInitiator) {
  10222. var self = this;
  10223. if (this.state !== null) {
  10224. console.error('attempt to initiate on session ' + this.sid +
  10225. 'in state ' + this.state);
  10226. return;
  10227. }
  10228. this.isInitiator = isInitiator;
  10229. this.state = 'pending';
  10230. this.initiator = isInitiator ? this.me : peerjid;
  10231. this.responder = !isInitiator ? this.me : peerjid;
  10232. this.peerjid = peerjid;
  10233. this.hadstuncandidate = false;
  10234. this.hadturncandidate = false;
  10235. this.lasticecandidate = false;
  10236. this.peerconnection
  10237. = new TraceablePeerConnection(
  10238. this.connection.jingle.ice_config,
  10239. this.connection.jingle.pc_constraints );
  10240. this.peerconnection.onicecandidate = function (event) {
  10241. self.sendIceCandidate(event.candidate);
  10242. };
  10243. this.peerconnection.onaddstream = function (event) {
  10244. console.log("REMOTE STREAM ADDED: " + event.stream + " - " + event.stream.id);
  10245. self.remoteStreamAdded(event);
  10246. };
  10247. this.peerconnection.onremovestream = function (event) {
  10248. // Remove the stream from remoteStreams
  10249. // FIXME: remotestreamremoved.jingle not defined anywhere(unused)
  10250. $(document).trigger('remotestreamremoved.jingle', [event, self.sid]);
  10251. };
  10252. this.peerconnection.onsignalingstatechange = function (event) {
  10253. if (!(self && self.peerconnection)) return;
  10254. };
  10255. this.peerconnection.oniceconnectionstatechange = function (event) {
  10256. if (!(self && self.peerconnection)) return;
  10257. switch (self.peerconnection.iceConnectionState) {
  10258. case 'connected':
  10259. this.startTime = new Date();
  10260. break;
  10261. case 'disconnected':
  10262. this.stopTime = new Date();
  10263. break;
  10264. }
  10265. onIceConnectionStateChange(self.sid, self);
  10266. };
  10267. // add any local and relayed stream
  10268. APP.RTC.localStreams.forEach(function(stream) {
  10269. self.peerconnection.addStream(stream.getOriginalStream());
  10270. });
  10271. this.relayedStreams.forEach(function(stream) {
  10272. self.peerconnection.addStream(stream);
  10273. });
  10274. };
  10275. function onIceConnectionStateChange(sid, session) {
  10276. switch (session.peerconnection.iceConnectionState) {
  10277. case 'checking':
  10278. session.timeChecking = (new Date()).getTime();
  10279. session.firstconnect = true;
  10280. break;
  10281. case 'completed': // on caller side
  10282. case 'connected':
  10283. if (session.firstconnect) {
  10284. session.firstconnect = false;
  10285. var metadata = {};
  10286. metadata.setupTime
  10287. = (new Date()).getTime() - session.timeChecking;
  10288. session.peerconnection.getStats(function (res) {
  10289. if(res && res.result) {
  10290. res.result().forEach(function (report) {
  10291. if (report.type == 'googCandidatePair' &&
  10292. report.stat('googActiveConnection') == 'true') {
  10293. metadata.localCandidateType
  10294. = report.stat('googLocalCandidateType');
  10295. metadata.remoteCandidateType
  10296. = report.stat('googRemoteCandidateType');
  10297. // log pair as well so we can get nice pie
  10298. // charts
  10299. metadata.candidatePair
  10300. = report.stat('googLocalCandidateType') +
  10301. ';' +
  10302. report.stat('googRemoteCandidateType');
  10303. if (report.stat('googRemoteAddress').indexOf('[') === 0)
  10304. {
  10305. metadata.ipv6 = true;
  10306. }
  10307. }
  10308. });
  10309. }
  10310. });
  10311. }
  10312. break;
  10313. }
  10314. }
  10315. JingleSession.prototype.accept = function () {
  10316. var self = this;
  10317. this.state = 'active';
  10318. var pranswer = this.peerconnection.localDescription;
  10319. if (!pranswer || pranswer.type != 'pranswer') {
  10320. return;
  10321. }
  10322. console.log('going from pranswer to answer');
  10323. if (this.usetrickle) {
  10324. // remove candidates already sent from session-accept
  10325. var lines = SDPUtil.find_lines(pranswer.sdp, 'a=candidate:');
  10326. for (var i = 0; i < lines.length; i++) {
  10327. pranswer.sdp = pranswer.sdp.replace(lines[i] + '\r\n', '');
  10328. }
  10329. }
  10330. while (SDPUtil.find_line(pranswer.sdp, 'a=inactive')) {
  10331. // FIXME: change any inactive to sendrecv or whatever they were originally
  10332. pranswer.sdp = pranswer.sdp.replace('a=inactive', 'a=sendrecv');
  10333. }
  10334. pranswer = APP.simulcast.reverseTransformLocalDescription(pranswer);
  10335. var prsdp = new SDP(pranswer.sdp);
  10336. var accept = $iq({to: this.peerjid,
  10337. type: 'set'})
  10338. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  10339. action: 'session-accept',
  10340. initiator: this.initiator,
  10341. responder: this.responder,
  10342. sid: this.sid });
  10343. prsdp.toJingle(accept, this.initiator == this.me ? 'initiator' : 'responder', this.localStreamsSSRC);
  10344. var sdp = this.peerconnection.localDescription.sdp;
  10345. while (SDPUtil.find_line(sdp, 'a=inactive')) {
  10346. // FIXME: change any inactive to sendrecv or whatever they were originally
  10347. sdp = sdp.replace('a=inactive', 'a=sendrecv');
  10348. }
  10349. var self = this;
  10350. this.peerconnection.setLocalDescription(new RTCSessionDescription({type: 'answer', sdp: sdp}),
  10351. function () {
  10352. //console.log('setLocalDescription success');
  10353. self.setLocalDescription();
  10354. self.connection.sendIQ(accept,
  10355. function () {
  10356. var ack = {};
  10357. ack.source = 'answer';
  10358. $(document).trigger('ack.jingle', [self.sid, ack]);
  10359. },
  10360. function (stanza) {
  10361. var error = ($(stanza).find('error').length) ? {
  10362. code: $(stanza).find('error').attr('code'),
  10363. reason: $(stanza).find('error :first')[0].tagName
  10364. }:{};
  10365. error.source = 'answer';
  10366. JingleSession.onJingleError(self.sid, error);
  10367. },
  10368. 10000);
  10369. },
  10370. function (e) {
  10371. console.error('setLocalDescription failed', e);
  10372. }
  10373. );
  10374. };
  10375. JingleSession.prototype.terminate = function (reason) {
  10376. this.state = 'ended';
  10377. this.reason = reason;
  10378. this.peerconnection.close();
  10379. if (this.statsinterval !== null) {
  10380. window.clearInterval(this.statsinterval);
  10381. this.statsinterval = null;
  10382. }
  10383. };
  10384. JingleSession.prototype.active = function () {
  10385. return this.state == 'active';
  10386. };
  10387. JingleSession.prototype.sendIceCandidate = function (candidate) {
  10388. var self = this;
  10389. if (candidate && !this.lasticecandidate) {
  10390. var ice = SDPUtil.iceparams(this.localSDP.media[candidate.sdpMLineIndex], this.localSDP.session);
  10391. var jcand = SDPUtil.candidateToJingle(candidate.candidate);
  10392. if (!(ice && jcand)) {
  10393. console.error('failed to get ice && jcand');
  10394. return;
  10395. }
  10396. ice.xmlns = 'urn:xmpp:jingle:transports:ice-udp:1';
  10397. if (jcand.type === 'srflx') {
  10398. this.hadstuncandidate = true;
  10399. } else if (jcand.type === 'relay') {
  10400. this.hadturncandidate = true;
  10401. }
  10402. if (this.usetrickle) {
  10403. if (this.usedrip) {
  10404. if (this.drip_container.length === 0) {
  10405. // start 20ms callout
  10406. window.setTimeout(function () {
  10407. if (self.drip_container.length === 0) return;
  10408. self.sendIceCandidates(self.drip_container);
  10409. self.drip_container = [];
  10410. }, 20);
  10411. }
  10412. this.drip_container.push(candidate);
  10413. return;
  10414. } else {
  10415. self.sendIceCandidate([candidate]);
  10416. }
  10417. }
  10418. } else {
  10419. //console.log('sendIceCandidate: last candidate.');
  10420. if (!this.usetrickle) {
  10421. //console.log('should send full offer now...');
  10422. var init = $iq({to: this.peerjid,
  10423. type: 'set'})
  10424. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  10425. action: this.peerconnection.localDescription.type == 'offer' ? 'session-initiate' : 'session-accept',
  10426. initiator: this.initiator,
  10427. sid: this.sid});
  10428. this.localSDP = new SDP(this.peerconnection.localDescription.sdp);
  10429. var self = this;
  10430. var sendJingle = function (ssrc) {
  10431. if(!ssrc)
  10432. ssrc = {};
  10433. self.localSDP.toJingle(init, self.initiator == self.me ? 'initiator' : 'responder', ssrc);
  10434. self.connection.sendIQ(init,
  10435. function () {
  10436. //console.log('session initiate ack');
  10437. var ack = {};
  10438. ack.source = 'offer';
  10439. $(document).trigger('ack.jingle', [self.sid, ack]);
  10440. },
  10441. function (stanza) {
  10442. self.state = 'error';
  10443. self.peerconnection.close();
  10444. var error = ($(stanza).find('error').length) ? {
  10445. code: $(stanza).find('error').attr('code'),
  10446. reason: $(stanza).find('error :first')[0].tagName,
  10447. }:{};
  10448. error.source = 'offer';
  10449. JingleSession.onJingleError(self.sid, error);
  10450. },
  10451. 10000);
  10452. }
  10453. sendJingle();
  10454. }
  10455. this.lasticecandidate = true;
  10456. console.log('Have we encountered any srflx candidates? ' + this.hadstuncandidate);
  10457. console.log('Have we encountered any relay candidates? ' + this.hadturncandidate);
  10458. if (!(this.hadstuncandidate || this.hadturncandidate) && this.peerconnection.signalingState != 'closed') {
  10459. $(document).trigger('nostuncandidates.jingle', [this.sid]);
  10460. }
  10461. }
  10462. };
  10463. JingleSession.prototype.sendIceCandidates = function (candidates) {
  10464. console.log('sendIceCandidates', candidates);
  10465. var cand = $iq({to: this.peerjid, type: 'set'})
  10466. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  10467. action: 'transport-info',
  10468. initiator: this.initiator,
  10469. sid: this.sid});
  10470. for (var mid = 0; mid < this.localSDP.media.length; mid++) {
  10471. var cands = candidates.filter(function (el) { return el.sdpMLineIndex == mid; });
  10472. var mline = SDPUtil.parse_mline(this.localSDP.media[mid].split('\r\n')[0]);
  10473. if (cands.length > 0) {
  10474. var ice = SDPUtil.iceparams(this.localSDP.media[mid], this.localSDP.session);
  10475. ice.xmlns = 'urn:xmpp:jingle:transports:ice-udp:1';
  10476. cand.c('content', {creator: this.initiator == this.me ? 'initiator' : 'responder',
  10477. name: (cands[0].sdpMid? cands[0].sdpMid : mline.media)
  10478. }).c('transport', ice);
  10479. for (var i = 0; i < cands.length; i++) {
  10480. cand.c('candidate', SDPUtil.candidateToJingle(cands[i].candidate)).up();
  10481. }
  10482. // add fingerprint
  10483. if (SDPUtil.find_line(this.localSDP.media[mid], 'a=fingerprint:', this.localSDP.session)) {
  10484. var tmp = SDPUtil.parse_fingerprint(SDPUtil.find_line(this.localSDP.media[mid], 'a=fingerprint:', this.localSDP.session));
  10485. tmp.required = true;
  10486. cand.c(
  10487. 'fingerprint',
  10488. {xmlns: 'urn:xmpp:jingle:apps:dtls:0'})
  10489. .t(tmp.fingerprint);
  10490. delete tmp.fingerprint;
  10491. cand.attrs(tmp);
  10492. cand.up();
  10493. }
  10494. cand.up(); // transport
  10495. cand.up(); // content
  10496. }
  10497. }
  10498. // might merge last-candidate notification into this, but it is called alot later. See webrtc issue #2340
  10499. //console.log('was this the last candidate', this.lasticecandidate);
  10500. this.connection.sendIQ(cand,
  10501. function () {
  10502. var ack = {};
  10503. ack.source = 'transportinfo';
  10504. $(document).trigger('ack.jingle', [this.sid, ack]);
  10505. },
  10506. function (stanza) {
  10507. var error = ($(stanza).find('error').length) ? {
  10508. code: $(stanza).find('error').attr('code'),
  10509. reason: $(stanza).find('error :first')[0].tagName,
  10510. }:{};
  10511. error.source = 'transportinfo';
  10512. JingleSession.onJingleError(this.sid, error);
  10513. },
  10514. 10000);
  10515. };
  10516. JingleSession.prototype.sendOffer = function () {
  10517. //console.log('sendOffer...');
  10518. var self = this;
  10519. this.peerconnection.createOffer(function (sdp) {
  10520. self.createdOffer(sdp);
  10521. },
  10522. function (e) {
  10523. console.error('createOffer failed', e);
  10524. },
  10525. this.media_constraints
  10526. );
  10527. };
  10528. JingleSession.prototype.createdOffer = function (sdp) {
  10529. //console.log('createdOffer', sdp);
  10530. var self = this;
  10531. this.localSDP = new SDP(sdp.sdp);
  10532. //this.localSDP.mangle();
  10533. var sendJingle = function () {
  10534. var init = $iq({to: this.peerjid,
  10535. type: 'set'})
  10536. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  10537. action: 'session-initiate',
  10538. initiator: this.initiator,
  10539. sid: this.sid});
  10540. self.localSDP.toJingle(init, this.initiator == this.me ? 'initiator' : 'responder', this.localStreamsSSRC);
  10541. self.connection.sendIQ(init,
  10542. function () {
  10543. var ack = {};
  10544. ack.source = 'offer';
  10545. $(document).trigger('ack.jingle', [self.sid, ack]);
  10546. },
  10547. function (stanza) {
  10548. self.state = 'error';
  10549. self.peerconnection.close();
  10550. var error = ($(stanza).find('error').length) ? {
  10551. code: $(stanza).find('error').attr('code'),
  10552. reason: $(stanza).find('error :first')[0].tagName,
  10553. }:{};
  10554. error.source = 'offer';
  10555. JingleSession.onJingleError(self.sid, error);
  10556. },
  10557. 10000);
  10558. }
  10559. sdp.sdp = this.localSDP.raw;
  10560. this.peerconnection.setLocalDescription(sdp,
  10561. function () {
  10562. if(self.usetrickle)
  10563. {
  10564. sendJingle();
  10565. }
  10566. self.setLocalDescription();
  10567. //console.log('setLocalDescription success');
  10568. },
  10569. function (e) {
  10570. console.error('setLocalDescription failed', e);
  10571. }
  10572. );
  10573. var cands = SDPUtil.find_lines(this.localSDP.raw, 'a=candidate:');
  10574. for (var i = 0; i < cands.length; i++) {
  10575. var cand = SDPUtil.parse_icecandidate(cands[i]);
  10576. if (cand.type == 'srflx') {
  10577. this.hadstuncandidate = true;
  10578. } else if (cand.type == 'relay') {
  10579. this.hadturncandidate = true;
  10580. }
  10581. }
  10582. };
  10583. JingleSession.prototype.setRemoteDescription = function (elem, desctype) {
  10584. //console.log('setting remote description... ', desctype);
  10585. this.remoteSDP = new SDP('');
  10586. this.remoteSDP.fromJingle(elem);
  10587. if (this.peerconnection.remoteDescription !== null) {
  10588. console.log('setRemoteDescription when remote description is not null, should be pranswer', this.peerconnection.remoteDescription);
  10589. if (this.peerconnection.remoteDescription.type == 'pranswer') {
  10590. var pranswer = new SDP(this.peerconnection.remoteDescription.sdp);
  10591. for (var i = 0; i < pranswer.media.length; i++) {
  10592. // make sure we have ice ufrag and pwd
  10593. if (!SDPUtil.find_line(this.remoteSDP.media[i], 'a=ice-ufrag:', this.remoteSDP.session)) {
  10594. if (SDPUtil.find_line(pranswer.media[i], 'a=ice-ufrag:', pranswer.session)) {
  10595. this.remoteSDP.media[i] += SDPUtil.find_line(pranswer.media[i], 'a=ice-ufrag:', pranswer.session) + '\r\n';
  10596. } else {
  10597. console.warn('no ice ufrag?');
  10598. }
  10599. if (SDPUtil.find_line(pranswer.media[i], 'a=ice-pwd:', pranswer.session)) {
  10600. this.remoteSDP.media[i] += SDPUtil.find_line(pranswer.media[i], 'a=ice-pwd:', pranswer.session) + '\r\n';
  10601. } else {
  10602. console.warn('no ice pwd?');
  10603. }
  10604. }
  10605. // copy over candidates
  10606. var lines = SDPUtil.find_lines(pranswer.media[i], 'a=candidate:');
  10607. for (var j = 0; j < lines.length; j++) {
  10608. this.remoteSDP.media[i] += lines[j] + '\r\n';
  10609. }
  10610. }
  10611. this.remoteSDP.raw = this.remoteSDP.session + this.remoteSDP.media.join('');
  10612. }
  10613. }
  10614. var remotedesc = new RTCSessionDescription({type: desctype, sdp: this.remoteSDP.raw});
  10615. this.peerconnection.setRemoteDescription(remotedesc,
  10616. function () {
  10617. //console.log('setRemoteDescription success');
  10618. },
  10619. function (e) {
  10620. console.error('setRemoteDescription error', e);
  10621. JingleSession.onJingleFatalError(self, e);
  10622. }
  10623. );
  10624. };
  10625. JingleSession.prototype.addIceCandidate = function (elem) {
  10626. var self = this;
  10627. if (this.peerconnection.signalingState == 'closed') {
  10628. return;
  10629. }
  10630. if (!this.peerconnection.remoteDescription && this.peerconnection.signalingState == 'have-local-offer') {
  10631. console.log('trickle ice candidate arriving before session accept...');
  10632. // create a PRANSWER for setRemoteDescription
  10633. if (!this.remoteSDP) {
  10634. var cobbled = 'v=0\r\n' +
  10635. 'o=- ' + '1923518516' + ' 2 IN IP4 0.0.0.0\r\n' +// FIXME
  10636. 's=-\r\n' +
  10637. 't=0 0\r\n';
  10638. // first, take some things from the local description
  10639. for (var i = 0; i < this.localSDP.media.length; i++) {
  10640. cobbled += SDPUtil.find_line(this.localSDP.media[i], 'm=') + '\r\n';
  10641. cobbled += SDPUtil.find_lines(this.localSDP.media[i], 'a=rtpmap:').join('\r\n') + '\r\n';
  10642. if (SDPUtil.find_line(this.localSDP.media[i], 'a=mid:')) {
  10643. cobbled += SDPUtil.find_line(this.localSDP.media[i], 'a=mid:') + '\r\n';
  10644. }
  10645. cobbled += 'a=inactive\r\n';
  10646. }
  10647. this.remoteSDP = new SDP(cobbled);
  10648. }
  10649. // then add things like ice and dtls from remote candidate
  10650. elem.each(function () {
  10651. for (var i = 0; i < self.remoteSDP.media.length; i++) {
  10652. if (SDPUtil.find_line(self.remoteSDP.media[i], 'a=mid:' + $(this).attr('name')) ||
  10653. self.remoteSDP.media[i].indexOf('m=' + $(this).attr('name')) === 0) {
  10654. if (!SDPUtil.find_line(self.remoteSDP.media[i], 'a=ice-ufrag:')) {
  10655. var tmp = $(this).find('transport');
  10656. self.remoteSDP.media[i] += 'a=ice-ufrag:' + tmp.attr('ufrag') + '\r\n';
  10657. self.remoteSDP.media[i] += 'a=ice-pwd:' + tmp.attr('pwd') + '\r\n';
  10658. tmp = $(this).find('transport>fingerprint');
  10659. if (tmp.length) {
  10660. self.remoteSDP.media[i] += 'a=fingerprint:' + tmp.attr('hash') + ' ' + tmp.text() + '\r\n';
  10661. } else {
  10662. console.log('no dtls fingerprint (webrtc issue #1718?)');
  10663. self.remoteSDP.media[i] += 'a=crypto:1 AES_CM_128_HMAC_SHA1_80 inline:BAADBAADBAADBAADBAADBAADBAADBAADBAADBAAD\r\n';
  10664. }
  10665. break;
  10666. }
  10667. }
  10668. }
  10669. });
  10670. this.remoteSDP.raw = this.remoteSDP.session + this.remoteSDP.media.join('');
  10671. // we need a complete SDP with ice-ufrag/ice-pwd in all parts
  10672. // this makes the assumption that the PRANSWER is constructed such that the ice-ufrag is in all mediaparts
  10673. // but it could be in the session part as well. since the code above constructs this sdp this can't happen however
  10674. var iscomplete = this.remoteSDP.media.filter(function (mediapart) {
  10675. return SDPUtil.find_line(mediapart, 'a=ice-ufrag:');
  10676. }).length == this.remoteSDP.media.length;
  10677. if (iscomplete) {
  10678. console.log('setting pranswer');
  10679. try {
  10680. this.peerconnection.setRemoteDescription(new RTCSessionDescription({type: 'pranswer', sdp: this.remoteSDP.raw }),
  10681. function() {
  10682. },
  10683. function(e) {
  10684. console.log('setRemoteDescription pranswer failed', e.toString());
  10685. });
  10686. } catch (e) {
  10687. console.error('setting pranswer failed', e);
  10688. }
  10689. } else {
  10690. //console.log('not yet setting pranswer');
  10691. }
  10692. }
  10693. // operate on each content element
  10694. elem.each(function () {
  10695. // would love to deactivate this, but firefox still requires it
  10696. var idx = -1;
  10697. var i;
  10698. for (i = 0; i < self.remoteSDP.media.length; i++) {
  10699. if (SDPUtil.find_line(self.remoteSDP.media[i], 'a=mid:' + $(this).attr('name')) ||
  10700. self.remoteSDP.media[i].indexOf('m=' + $(this).attr('name')) === 0) {
  10701. idx = i;
  10702. break;
  10703. }
  10704. }
  10705. if (idx == -1) { // fall back to localdescription
  10706. for (i = 0; i < self.localSDP.media.length; i++) {
  10707. if (SDPUtil.find_line(self.localSDP.media[i], 'a=mid:' + $(this).attr('name')) ||
  10708. self.localSDP.media[i].indexOf('m=' + $(this).attr('name')) === 0) {
  10709. idx = i;
  10710. break;
  10711. }
  10712. }
  10713. }
  10714. var name = $(this).attr('name');
  10715. // TODO: check ice-pwd and ice-ufrag?
  10716. $(this).find('transport>candidate').each(function () {
  10717. var line, candidate;
  10718. line = SDPUtil.candidateFromJingle(this);
  10719. candidate = new RTCIceCandidate({sdpMLineIndex: idx,
  10720. sdpMid: name,
  10721. candidate: line});
  10722. try {
  10723. self.peerconnection.addIceCandidate(candidate);
  10724. } catch (e) {
  10725. console.error('addIceCandidate failed', e.toString(), line);
  10726. }
  10727. });
  10728. });
  10729. };
  10730. JingleSession.prototype.sendAnswer = function (provisional) {
  10731. //console.log('createAnswer', provisional);
  10732. var self = this;
  10733. this.peerconnection.createAnswer(
  10734. function (sdp) {
  10735. self.createdAnswer(sdp, provisional);
  10736. },
  10737. function (e) {
  10738. console.error('createAnswer failed', e);
  10739. },
  10740. this.media_constraints
  10741. );
  10742. };
  10743. JingleSession.prototype.createdAnswer = function (sdp, provisional) {
  10744. //console.log('createAnswer callback');
  10745. var self = this;
  10746. this.localSDP = new SDP(sdp.sdp);
  10747. //this.localSDP.mangle();
  10748. this.usepranswer = provisional === true;
  10749. if (this.usetrickle) {
  10750. if (this.usepranswer) {
  10751. sdp.type = 'pranswer';
  10752. for (var i = 0; i < this.localSDP.media.length; i++) {
  10753. this.localSDP.media[i] = this.localSDP.media[i].replace('a=sendrecv\r\n', 'a=inactive\r\n');
  10754. }
  10755. this.localSDP.raw = this.localSDP.session + '\r\n' + this.localSDP.media.join('');
  10756. }
  10757. }
  10758. var self = this;
  10759. var sendJingle = function (ssrcs) {
  10760. var accept = $iq({to: self.peerjid,
  10761. type: 'set'})
  10762. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  10763. action: 'session-accept',
  10764. initiator: self.initiator,
  10765. responder: self.responder,
  10766. sid: self.sid });
  10767. var publicLocalDesc = APP.simulcast.reverseTransformLocalDescription(sdp);
  10768. var publicLocalSDP = new SDP(publicLocalDesc.sdp);
  10769. publicLocalSDP.toJingle(accept, self.initiator == self.me ? 'initiator' : 'responder', ssrcs);
  10770. self.connection.sendIQ(accept,
  10771. function () {
  10772. var ack = {};
  10773. ack.source = 'answer';
  10774. $(document).trigger('ack.jingle', [self.sid, ack]);
  10775. },
  10776. function (stanza) {
  10777. var error = ($(stanza).find('error').length) ? {
  10778. code: $(stanza).find('error').attr('code'),
  10779. reason: $(stanza).find('error :first')[0].tagName,
  10780. }:{};
  10781. error.source = 'answer';
  10782. JingleSession.onJingleError(self.sid, error);
  10783. },
  10784. 10000);
  10785. }
  10786. sdp.sdp = this.localSDP.raw;
  10787. this.peerconnection.setLocalDescription(sdp,
  10788. function () {
  10789. //console.log('setLocalDescription success');
  10790. if (self.usetrickle && !self.usepranswer) {
  10791. sendJingle();
  10792. }
  10793. self.setLocalDescription();
  10794. },
  10795. function (e) {
  10796. console.error('setLocalDescription failed', e);
  10797. }
  10798. );
  10799. var cands = SDPUtil.find_lines(this.localSDP.raw, 'a=candidate:');
  10800. for (var j = 0; j < cands.length; j++) {
  10801. var cand = SDPUtil.parse_icecandidate(cands[j]);
  10802. if (cand.type == 'srflx') {
  10803. this.hadstuncandidate = true;
  10804. } else if (cand.type == 'relay') {
  10805. this.hadturncandidate = true;
  10806. }
  10807. }
  10808. };
  10809. JingleSession.prototype.sendTerminate = function (reason, text) {
  10810. var self = this,
  10811. term = $iq({to: this.peerjid,
  10812. type: 'set'})
  10813. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  10814. action: 'session-terminate',
  10815. initiator: this.initiator,
  10816. sid: this.sid})
  10817. .c('reason')
  10818. .c(reason || 'success');
  10819. if (text) {
  10820. term.up().c('text').t(text);
  10821. }
  10822. this.connection.sendIQ(term,
  10823. function () {
  10824. self.peerconnection.close();
  10825. self.peerconnection = null;
  10826. self.terminate();
  10827. var ack = {};
  10828. ack.source = 'terminate';
  10829. $(document).trigger('ack.jingle', [self.sid, ack]);
  10830. },
  10831. function (stanza) {
  10832. var error = ($(stanza).find('error').length) ? {
  10833. code: $(stanza).find('error').attr('code'),
  10834. reason: $(stanza).find('error :first')[0].tagName,
  10835. }:{};
  10836. $(document).trigger('ack.jingle', [self.sid, error]);
  10837. },
  10838. 10000);
  10839. if (this.statsinterval !== null) {
  10840. window.clearInterval(this.statsinterval);
  10841. this.statsinterval = null;
  10842. }
  10843. };
  10844. JingleSession.prototype.addSource = function (elem, fromJid) {
  10845. var self = this;
  10846. // FIXME: dirty waiting
  10847. if (!this.peerconnection.localDescription)
  10848. {
  10849. console.warn("addSource - localDescription not ready yet")
  10850. setTimeout(function()
  10851. {
  10852. self.addSource(elem, fromJid);
  10853. },
  10854. 200
  10855. );
  10856. return;
  10857. }
  10858. console.log('addssrc', new Date().getTime());
  10859. console.log('ice', this.peerconnection.iceConnectionState);
  10860. var sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  10861. var mySdp = new SDP(this.peerconnection.localDescription.sdp);
  10862. $(elem).each(function (idx, content) {
  10863. var name = $(content).attr('name');
  10864. var lines = '';
  10865. $(content).find('ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]').each(function() {
  10866. var semantics = this.getAttribute('semantics');
  10867. var ssrcs = $(this).find('>source').map(function () {
  10868. return this.getAttribute('ssrc');
  10869. }).get();
  10870. if (ssrcs.length != 0) {
  10871. lines += 'a=ssrc-group:' + semantics + ' ' + ssrcs.join(' ') + '\r\n';
  10872. }
  10873. });
  10874. var tmp = $(content).find('source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]'); // can handle both >source and >description>source
  10875. tmp.each(function () {
  10876. var ssrc = $(this).attr('ssrc');
  10877. if(mySdp.containsSSRC(ssrc)){
  10878. /**
  10879. * This happens when multiple participants change their streams at the same time and
  10880. * ColibriFocus.modifySources have to wait for stable state. In the meantime multiple
  10881. * addssrc are scheduled for update IQ. See
  10882. */
  10883. console.warn("Got add stream request for my own ssrc: "+ssrc);
  10884. return;
  10885. }
  10886. $(this).find('>parameter').each(function () {
  10887. lines += 'a=ssrc:' + ssrc + ' ' + $(this).attr('name');
  10888. if ($(this).attr('value') && $(this).attr('value').length)
  10889. lines += ':' + $(this).attr('value');
  10890. lines += '\r\n';
  10891. });
  10892. });
  10893. sdp.media.forEach(function(media, idx) {
  10894. if (!SDPUtil.find_line(media, 'a=mid:' + name))
  10895. return;
  10896. sdp.media[idx] += lines;
  10897. if (!self.addssrc[idx]) self.addssrc[idx] = '';
  10898. self.addssrc[idx] += lines;
  10899. });
  10900. sdp.raw = sdp.session + sdp.media.join('');
  10901. });
  10902. this.modifySources();
  10903. };
  10904. JingleSession.prototype.removeSource = function (elem, fromJid) {
  10905. var self = this;
  10906. // FIXME: dirty waiting
  10907. if (!this.peerconnection.localDescription)
  10908. {
  10909. console.warn("removeSource - localDescription not ready yet")
  10910. setTimeout(function()
  10911. {
  10912. self.removeSource(elem, fromJid);
  10913. },
  10914. 200
  10915. );
  10916. return;
  10917. }
  10918. console.log('removessrc', new Date().getTime());
  10919. console.log('ice', this.peerconnection.iceConnectionState);
  10920. var sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  10921. var mySdp = new SDP(this.peerconnection.localDescription.sdp);
  10922. $(elem).each(function (idx, content) {
  10923. var name = $(content).attr('name');
  10924. var lines = '';
  10925. $(content).find('ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]').each(function() {
  10926. var semantics = this.getAttribute('semantics');
  10927. var ssrcs = $(this).find('>source').map(function () {
  10928. return this.getAttribute('ssrc');
  10929. }).get();
  10930. if (ssrcs.length != 0) {
  10931. lines += 'a=ssrc-group:' + semantics + ' ' + ssrcs.join(' ') + '\r\n';
  10932. }
  10933. });
  10934. var tmp = $(content).find('source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]'); // can handle both >source and >description>source
  10935. tmp.each(function () {
  10936. var ssrc = $(this).attr('ssrc');
  10937. // This should never happen, but can be useful for bug detection
  10938. if(mySdp.containsSSRC(ssrc)){
  10939. console.error("Got remove stream request for my own ssrc: "+ssrc);
  10940. return;
  10941. }
  10942. $(this).find('>parameter').each(function () {
  10943. lines += 'a=ssrc:' + ssrc + ' ' + $(this).attr('name');
  10944. if ($(this).attr('value') && $(this).attr('value').length)
  10945. lines += ':' + $(this).attr('value');
  10946. lines += '\r\n';
  10947. });
  10948. });
  10949. sdp.media.forEach(function(media, idx) {
  10950. if (!SDPUtil.find_line(media, 'a=mid:' + name))
  10951. return;
  10952. sdp.media[idx] += lines;
  10953. if (!self.removessrc[idx]) self.removessrc[idx] = '';
  10954. self.removessrc[idx] += lines;
  10955. });
  10956. sdp.raw = sdp.session + sdp.media.join('');
  10957. });
  10958. this.modifySources();
  10959. };
  10960. JingleSession.prototype.modifySources = function (successCallback) {
  10961. var self = this;
  10962. if (this.peerconnection.signalingState == 'closed') return;
  10963. if (!(this.addssrc.length || this.removessrc.length || this.pendingop !== null || this.switchstreams)){
  10964. // There is nothing to do since scheduled job might have been executed by another succeeding call
  10965. this.setLocalDescription();
  10966. if(successCallback){
  10967. successCallback();
  10968. }
  10969. return;
  10970. }
  10971. // FIXME: this is a big hack
  10972. // https://code.google.com/p/webrtc/issues/detail?id=2688
  10973. // ^ has been fixed.
  10974. if (!(this.peerconnection.signalingState == 'stable' && this.peerconnection.iceConnectionState == 'connected')) {
  10975. console.warn('modifySources not yet', this.peerconnection.signalingState, this.peerconnection.iceConnectionState);
  10976. this.wait = true;
  10977. window.setTimeout(function() { self.modifySources(successCallback); }, 250);
  10978. return;
  10979. }
  10980. if (this.wait) {
  10981. window.setTimeout(function() { self.modifySources(successCallback); }, 2500);
  10982. this.wait = false;
  10983. return;
  10984. }
  10985. // Reset switch streams flag
  10986. this.switchstreams = false;
  10987. var sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  10988. // add sources
  10989. this.addssrc.forEach(function(lines, idx) {
  10990. sdp.media[idx] += lines;
  10991. });
  10992. this.addssrc = [];
  10993. // remove sources
  10994. this.removessrc.forEach(function(lines, idx) {
  10995. lines = lines.split('\r\n');
  10996. lines.pop(); // remove empty last element;
  10997. lines.forEach(function(line) {
  10998. sdp.media[idx] = sdp.media[idx].replace(line + '\r\n', '');
  10999. });
  11000. });
  11001. this.removessrc = [];
  11002. // FIXME:
  11003. // this was a hack for the situation when only one peer exists
  11004. // in the conference.
  11005. // check if still required and remove
  11006. if (sdp.media[0])
  11007. sdp.media[0] = sdp.media[0].replace('a=recvonly', 'a=sendrecv');
  11008. if (sdp.media[1])
  11009. sdp.media[1] = sdp.media[1].replace('a=recvonly', 'a=sendrecv');
  11010. sdp.raw = sdp.session + sdp.media.join('');
  11011. this.peerconnection.setRemoteDescription(new RTCSessionDescription({type: 'offer', sdp: sdp.raw}),
  11012. function() {
  11013. if(self.signalingState == 'closed') {
  11014. console.error("createAnswer attempt on closed state");
  11015. return;
  11016. }
  11017. self.peerconnection.createAnswer(
  11018. function(modifiedAnswer) {
  11019. // change video direction, see https://github.com/jitsi/jitmeet/issues/41
  11020. if (self.pendingop !== null) {
  11021. var sdp = new SDP(modifiedAnswer.sdp);
  11022. if (sdp.media.length > 1) {
  11023. switch(self.pendingop) {
  11024. case 'mute':
  11025. sdp.media[1] = sdp.media[1].replace('a=sendrecv', 'a=recvonly');
  11026. break;
  11027. case 'unmute':
  11028. sdp.media[1] = sdp.media[1].replace('a=recvonly', 'a=sendrecv');
  11029. break;
  11030. }
  11031. sdp.raw = sdp.session + sdp.media.join('');
  11032. modifiedAnswer.sdp = sdp.raw;
  11033. }
  11034. self.pendingop = null;
  11035. }
  11036. // FIXME: pushing down an answer while ice connection state
  11037. // is still checking is bad...
  11038. //console.log(self.peerconnection.iceConnectionState);
  11039. // trying to work around another chrome bug
  11040. //modifiedAnswer.sdp = modifiedAnswer.sdp.replace(/a=setup:active/g, 'a=setup:actpass');
  11041. self.peerconnection.setLocalDescription(modifiedAnswer,
  11042. function() {
  11043. //console.log('modified setLocalDescription ok');
  11044. self.setLocalDescription();
  11045. if(successCallback){
  11046. successCallback();
  11047. }
  11048. },
  11049. function(error) {
  11050. console.error('modified setLocalDescription failed', error);
  11051. }
  11052. );
  11053. },
  11054. function(error) {
  11055. console.error('modified answer failed', error);
  11056. }
  11057. );
  11058. },
  11059. function(error) {
  11060. console.error('modify failed', error);
  11061. }
  11062. );
  11063. };
  11064. /**
  11065. * Switches video streams.
  11066. * @param new_stream new stream that will be used as video of this session.
  11067. * @param oldStream old video stream of this session.
  11068. * @param success_callback callback executed after successful stream switch.
  11069. */
  11070. JingleSession.prototype.switchStreams = function (new_stream, oldStream, success_callback) {
  11071. var self = this;
  11072. // Remember SDP to figure out added/removed SSRCs
  11073. var oldSdp = null;
  11074. if(self.peerconnection) {
  11075. if(self.peerconnection.localDescription) {
  11076. oldSdp = new SDP(self.peerconnection.localDescription.sdp);
  11077. }
  11078. self.peerconnection.removeStream(oldStream, true);
  11079. self.peerconnection.addStream(new_stream);
  11080. }
  11081. APP.RTC.switchVideoStreams(new_stream, oldStream);
  11082. // Conference is not active
  11083. if(!oldSdp || !self.peerconnection) {
  11084. success_callback();
  11085. return;
  11086. }
  11087. self.switchstreams = true;
  11088. self.modifySources(function() {
  11089. console.log('modify sources done');
  11090. success_callback();
  11091. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  11092. console.log("SDPs", oldSdp, newSdp);
  11093. self.notifyMySSRCUpdate(oldSdp, newSdp);
  11094. });
  11095. };
  11096. /**
  11097. * Figures out added/removed ssrcs and send update IQs.
  11098. * @param old_sdp SDP object for old description.
  11099. * @param new_sdp SDP object for new description.
  11100. */
  11101. JingleSession.prototype.notifyMySSRCUpdate = function (old_sdp, new_sdp) {
  11102. if (!(this.peerconnection.signalingState == 'stable' &&
  11103. this.peerconnection.iceConnectionState == 'connected')){
  11104. console.log("Too early to send updates");
  11105. return;
  11106. }
  11107. // send source-remove IQ.
  11108. sdpDiffer = new SDPDiffer(new_sdp, old_sdp);
  11109. var remove = $iq({to: this.peerjid, type: 'set'})
  11110. .c('jingle', {
  11111. xmlns: 'urn:xmpp:jingle:1',
  11112. action: 'source-remove',
  11113. initiator: this.initiator,
  11114. sid: this.sid
  11115. }
  11116. );
  11117. var removed = sdpDiffer.toJingle(remove);
  11118. if (removed) {
  11119. this.connection.sendIQ(remove,
  11120. function (res) {
  11121. console.info('got remove result', res);
  11122. },
  11123. function (err) {
  11124. console.error('got remove error', err);
  11125. }
  11126. );
  11127. } else {
  11128. console.log('removal not necessary');
  11129. }
  11130. // send source-add IQ.
  11131. var sdpDiffer = new SDPDiffer(old_sdp, new_sdp);
  11132. var add = $iq({to: this.peerjid, type: 'set'})
  11133. .c('jingle', {
  11134. xmlns: 'urn:xmpp:jingle:1',
  11135. action: 'source-add',
  11136. initiator: this.initiator,
  11137. sid: this.sid
  11138. }
  11139. );
  11140. var added = sdpDiffer.toJingle(add);
  11141. if (added) {
  11142. this.connection.sendIQ(add,
  11143. function (res) {
  11144. console.info('got add result', res);
  11145. },
  11146. function (err) {
  11147. console.error('got add error', err);
  11148. }
  11149. );
  11150. } else {
  11151. console.log('addition not necessary');
  11152. }
  11153. };
  11154. /**
  11155. * Determines whether the (local) video is mute i.e. all video tracks are
  11156. * disabled.
  11157. *
  11158. * @return <tt>true</tt> if the (local) video is mute i.e. all video tracks are
  11159. * disabled; otherwise, <tt>false</tt>
  11160. */
  11161. JingleSession.prototype.isVideoMute = function () {
  11162. var tracks = APP.RTC.localVideo.getVideoTracks();
  11163. var mute = true;
  11164. for (var i = 0; i < tracks.length; ++i) {
  11165. if (tracks[i].enabled) {
  11166. mute = false;
  11167. break;
  11168. }
  11169. }
  11170. return mute;
  11171. };
  11172. /**
  11173. * Mutes/unmutes the (local) video i.e. enables/disables all video tracks.
  11174. *
  11175. * @param mute <tt>true</tt> to mute the (local) video i.e. to disable all video
  11176. * tracks; otherwise, <tt>false</tt>
  11177. * @param callback a function to be invoked with <tt>mute</tt> after all video
  11178. * tracks have been enabled/disabled. The function may, optionally, return
  11179. * another function which is to be invoked after the whole mute/unmute operation
  11180. * has completed successfully.
  11181. * @param options an object which specifies optional arguments such as the
  11182. * <tt>boolean</tt> key <tt>byUser</tt> with default value <tt>true</tt> which
  11183. * specifies whether the method was initiated in response to a user command (in
  11184. * contrast to an automatic decision made by the application logic)
  11185. */
  11186. JingleSession.prototype.setVideoMute = function (mute, callback, options) {
  11187. var byUser;
  11188. if (options) {
  11189. byUser = options.byUser;
  11190. if (typeof byUser === 'undefined') {
  11191. byUser = true;
  11192. }
  11193. } else {
  11194. byUser = true;
  11195. }
  11196. // The user's command to mute the (local) video takes precedence over any
  11197. // automatic decision made by the application logic.
  11198. if (byUser) {
  11199. this.videoMuteByUser = mute;
  11200. } else if (this.videoMuteByUser) {
  11201. return;
  11202. }
  11203. var self = this;
  11204. var localCallback = function (mute) {
  11205. self.connection.emuc.addVideoInfoToPresence(mute);
  11206. self.connection.emuc.sendPresence();
  11207. return callback(mute)
  11208. };
  11209. if (mute == APP.RTC.localVideo.isMuted())
  11210. {
  11211. // Even if no change occurs, the specified callback is to be executed.
  11212. // The specified callback may, optionally, return a successCallback
  11213. // which is to be executed as well.
  11214. var successCallback = localCallback(mute);
  11215. if (successCallback) {
  11216. successCallback();
  11217. }
  11218. } else {
  11219. APP.RTC.localVideo.setMute(!mute);
  11220. this.hardMuteVideo(mute);
  11221. this.modifySources(localCallback(mute));
  11222. }
  11223. };
  11224. // SDP-based mute by going recvonly/sendrecv
  11225. // FIXME: should probably black out the screen as well
  11226. JingleSession.prototype.toggleVideoMute = function (callback) {
  11227. this.service.setVideoMute(APP.RTC.localVideo.isMuted(), callback);
  11228. };
  11229. JingleSession.prototype.hardMuteVideo = function (muted) {
  11230. this.pendingop = muted ? 'mute' : 'unmute';
  11231. };
  11232. JingleSession.prototype.sendMute = function (muted, content) {
  11233. var info = $iq({to: this.peerjid,
  11234. type: 'set'})
  11235. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  11236. action: 'session-info',
  11237. initiator: this.initiator,
  11238. sid: this.sid });
  11239. info.c(muted ? 'mute' : 'unmute', {xmlns: 'urn:xmpp:jingle:apps:rtp:info:1'});
  11240. info.attrs({'creator': this.me == this.initiator ? 'creator' : 'responder'});
  11241. if (content) {
  11242. info.attrs({'name': content});
  11243. }
  11244. this.connection.send(info);
  11245. };
  11246. JingleSession.prototype.sendRinging = function () {
  11247. var info = $iq({to: this.peerjid,
  11248. type: 'set'})
  11249. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  11250. action: 'session-info',
  11251. initiator: this.initiator,
  11252. sid: this.sid });
  11253. info.c('ringing', {xmlns: 'urn:xmpp:jingle:apps:rtp:info:1'});
  11254. this.connection.send(info);
  11255. };
  11256. JingleSession.prototype.getStats = function (interval) {
  11257. var self = this;
  11258. var recv = {audio: 0, video: 0};
  11259. var lost = {audio: 0, video: 0};
  11260. var lastrecv = {audio: 0, video: 0};
  11261. var lastlost = {audio: 0, video: 0};
  11262. var loss = {audio: 0, video: 0};
  11263. var delta = {audio: 0, video: 0};
  11264. this.statsinterval = window.setInterval(function () {
  11265. if (self && self.peerconnection && self.peerconnection.getStats) {
  11266. self.peerconnection.getStats(function (stats) {
  11267. var results = stats.result();
  11268. // TODO: there are so much statistics you can get from this..
  11269. for (var i = 0; i < results.length; ++i) {
  11270. if (results[i].type == 'ssrc') {
  11271. var packetsrecv = results[i].stat('packetsReceived');
  11272. var packetslost = results[i].stat('packetsLost');
  11273. if (packetsrecv && packetslost) {
  11274. packetsrecv = parseInt(packetsrecv, 10);
  11275. packetslost = parseInt(packetslost, 10);
  11276. if (results[i].stat('googFrameRateReceived')) {
  11277. lastlost.video = lost.video;
  11278. lastrecv.video = recv.video;
  11279. recv.video = packetsrecv;
  11280. lost.video = packetslost;
  11281. } else {
  11282. lastlost.audio = lost.audio;
  11283. lastrecv.audio = recv.audio;
  11284. recv.audio = packetsrecv;
  11285. lost.audio = packetslost;
  11286. }
  11287. }
  11288. }
  11289. }
  11290. delta.audio = recv.audio - lastrecv.audio;
  11291. delta.video = recv.video - lastrecv.video;
  11292. loss.audio = (delta.audio > 0) ? Math.ceil(100 * (lost.audio - lastlost.audio) / delta.audio) : 0;
  11293. loss.video = (delta.video > 0) ? Math.ceil(100 * (lost.video - lastlost.video) / delta.video) : 0;
  11294. $(document).trigger('packetloss.jingle', [self.sid, loss]);
  11295. });
  11296. }
  11297. }, interval || 3000);
  11298. return this.statsinterval;
  11299. };
  11300. JingleSession.onJingleError = function (session, error)
  11301. {
  11302. console.error("Jingle error", error);
  11303. }
  11304. JingleSession.onJingleFatalError = function (session, error)
  11305. {
  11306. this.service.sessionTerminated = true;
  11307. this.connection.emuc.doLeave();
  11308. APP.UI.messageHandler.showError("dialog.sorry",
  11309. "dialog.internalError");
  11310. }
  11311. JingleSession.prototype.setLocalDescription = function () {
  11312. // put our ssrcs into presence so other clients can identify our stream
  11313. var newssrcs = [];
  11314. var media = APP.simulcast.parseMedia(this.peerconnection.localDescription);
  11315. media.forEach(function (media) {
  11316. if(Object.keys(media.sources).length > 0) {
  11317. // TODO(gp) maybe exclude FID streams?
  11318. Object.keys(media.sources).forEach(function (ssrc) {
  11319. newssrcs.push({
  11320. 'ssrc': ssrc,
  11321. 'type': media.type,
  11322. 'direction': media.direction
  11323. });
  11324. });
  11325. }
  11326. else if(this.localStreamsSSRC && this.localStreamsSSRC[media.type])
  11327. {
  11328. newssrcs.push({
  11329. 'ssrc': this.localStreamsSSRC[media.type],
  11330. 'type': media.type,
  11331. 'direction': media.direction
  11332. });
  11333. }
  11334. });
  11335. console.log('new ssrcs', newssrcs);
  11336. // Have to clear presence map to get rid of removed streams
  11337. this.connection.emuc.clearPresenceMedia();
  11338. if (newssrcs.length > 0) {
  11339. for (var i = 1; i <= newssrcs.length; i ++) {
  11340. // Change video type to screen
  11341. if (newssrcs[i-1].type === 'video' && APP.desktopsharing.isUsingScreenStream()) {
  11342. newssrcs[i-1].type = 'screen';
  11343. }
  11344. this.connection.emuc.addMediaToPresence(i,
  11345. newssrcs[i-1].type, newssrcs[i-1].ssrc, newssrcs[i-1].direction);
  11346. }
  11347. this.connection.emuc.sendPresence();
  11348. }
  11349. }
  11350. // an attempt to work around https://github.com/jitsi/jitmeet/issues/32
  11351. function sendKeyframe(pc) {
  11352. console.log('sendkeyframe', pc.iceConnectionState);
  11353. if (pc.iceConnectionState !== 'connected') return; // safe...
  11354. pc.setRemoteDescription(
  11355. pc.remoteDescription,
  11356. function () {
  11357. pc.createAnswer(
  11358. function (modifiedAnswer) {
  11359. pc.setLocalDescription(
  11360. modifiedAnswer,
  11361. function () {
  11362. // noop
  11363. },
  11364. function (error) {
  11365. console.log('triggerKeyframe setLocalDescription failed', error);
  11366. APP.UI.messageHandler.showError();
  11367. }
  11368. );
  11369. },
  11370. function (error) {
  11371. console.log('triggerKeyframe createAnswer failed', error);
  11372. APP.UI.messageHandler.showError();
  11373. }
  11374. );
  11375. },
  11376. function (error) {
  11377. console.log('triggerKeyframe setRemoteDescription failed', error);
  11378. APP.UI.messageHandler.showError();
  11379. }
  11380. );
  11381. }
  11382. JingleSession.prototype.remoteStreamAdded = function (data, times) {
  11383. var self = this;
  11384. var thessrc;
  11385. var ssrc2jid = this.connection.emuc.ssrc2jid;
  11386. // look up an associated JID for a stream id
  11387. if (data.stream.id && data.stream.id.indexOf('mixedmslabel') === -1) {
  11388. // look only at a=ssrc: and _not_ at a=ssrc-group: lines
  11389. var ssrclines
  11390. = SDPUtil.find_lines(this.peerconnection.remoteDescription.sdp, 'a=ssrc:');
  11391. ssrclines = ssrclines.filter(function (line) {
  11392. // NOTE(gp) previously we filtered on the mslabel, but that property
  11393. // is not always present.
  11394. // return line.indexOf('mslabel:' + data.stream.label) !== -1;
  11395. return ((line.indexOf('msid:' + data.stream.id) !== -1));
  11396. });
  11397. if (ssrclines.length) {
  11398. thessrc = ssrclines[0].substring(7).split(' ')[0];
  11399. // We signal our streams (through Jingle to the focus) before we set
  11400. // our presence (through which peers associate remote streams to
  11401. // jids). So, it might arrive that a remote stream is added but
  11402. // ssrc2jid is not yet updated and thus data.peerjid cannot be
  11403. // successfully set. Here we wait for up to a second for the
  11404. // presence to arrive.
  11405. if (!ssrc2jid[thessrc]) {
  11406. if (typeof times === 'undefined')
  11407. {
  11408. times = 0;
  11409. }
  11410. if (times > 10)
  11411. {
  11412. console.warning('Waiting for jid timed out', thessrc);
  11413. }
  11414. else
  11415. {
  11416. setTimeout(function(d) {
  11417. return function() {
  11418. self.remoteStreamAdded(d, times++);
  11419. }
  11420. }(data), 250);
  11421. }
  11422. return;
  11423. }
  11424. // ok to overwrite the one from focus? might save work in colibri.js
  11425. console.log('associated jid', ssrc2jid[thessrc], data.peerjid);
  11426. if (ssrc2jid[thessrc]) {
  11427. data.peerjid = ssrc2jid[thessrc];
  11428. }
  11429. }
  11430. }
  11431. APP.RTC.createRemoteStream(data, this.sid, thessrc);
  11432. var isVideo = data.stream.getVideoTracks().length > 0;
  11433. // an attempt to work around https://github.com/jitsi/jitmeet/issues/32
  11434. if (isVideo &&
  11435. data.peerjid && this.peerjid === data.peerjid &&
  11436. data.stream.getVideoTracks().length === 0 &&
  11437. APP.RTC.localVideo.getTracks().length > 0) {
  11438. window.setTimeout(function () {
  11439. sendKeyframe(self.peerconnection);
  11440. }, 3000);
  11441. }
  11442. }
  11443. module.exports = JingleSession;
  11444. },{"../../service/RTC/RTCBrowserType":87,"./SDP":48,"./SDPDiffer":49,"./SDPUtil":50,"./TraceablePeerConnection":51}],48:[function(require,module,exports){
  11445. /* jshint -W117 */
  11446. var SDPUtil = require("./SDPUtil");
  11447. // SDP STUFF
  11448. function SDP(sdp) {
  11449. this.media = sdp.split('\r\nm=');
  11450. for (var i = 1; i < this.media.length; i++) {
  11451. this.media[i] = 'm=' + this.media[i];
  11452. if (i != this.media.length - 1) {
  11453. this.media[i] += '\r\n';
  11454. }
  11455. }
  11456. this.session = this.media.shift() + '\r\n';
  11457. this.raw = this.session + this.media.join('');
  11458. }
  11459. /**
  11460. * Returns map of MediaChannel mapped per channel idx.
  11461. */
  11462. SDP.prototype.getMediaSsrcMap = function() {
  11463. var self = this;
  11464. var media_ssrcs = {};
  11465. var tmp;
  11466. for (var mediaindex = 0; mediaindex < self.media.length; mediaindex++) {
  11467. tmp = SDPUtil.find_lines(self.media[mediaindex], 'a=ssrc:');
  11468. var mid = SDPUtil.parse_mid(SDPUtil.find_line(self.media[mediaindex], 'a=mid:'));
  11469. var media = {
  11470. mediaindex: mediaindex,
  11471. mid: mid,
  11472. ssrcs: {},
  11473. ssrcGroups: []
  11474. };
  11475. media_ssrcs[mediaindex] = media;
  11476. tmp.forEach(function (line) {
  11477. var linessrc = line.substring(7).split(' ')[0];
  11478. // allocate new ChannelSsrc
  11479. if(!media.ssrcs[linessrc]) {
  11480. media.ssrcs[linessrc] = {
  11481. ssrc: linessrc,
  11482. lines: []
  11483. };
  11484. }
  11485. media.ssrcs[linessrc].lines.push(line);
  11486. });
  11487. tmp = SDPUtil.find_lines(self.media[mediaindex], 'a=ssrc-group:');
  11488. tmp.forEach(function(line){
  11489. var semantics = line.substr(0, idx).substr(13);
  11490. var ssrcs = line.substr(14 + semantics.length).split(' ');
  11491. if (ssrcs.length != 0) {
  11492. media.ssrcGroups.push({
  11493. semantics: semantics,
  11494. ssrcs: ssrcs
  11495. });
  11496. }
  11497. });
  11498. }
  11499. return media_ssrcs;
  11500. };
  11501. /**
  11502. * Returns <tt>true</tt> if this SDP contains given SSRC.
  11503. * @param ssrc the ssrc to check.
  11504. * @returns {boolean} <tt>true</tt> if this SDP contains given SSRC.
  11505. */
  11506. SDP.prototype.containsSSRC = function(ssrc) {
  11507. var medias = this.getMediaSsrcMap();
  11508. var contains = false;
  11509. Object.keys(medias).forEach(function(mediaindex){
  11510. var media = medias[mediaindex];
  11511. //console.log("Check", channel, ssrc);
  11512. if(Object.keys(media.ssrcs).indexOf(ssrc) != -1){
  11513. contains = true;
  11514. }
  11515. });
  11516. return contains;
  11517. };
  11518. // remove iSAC and CN from SDP
  11519. SDP.prototype.mangle = function () {
  11520. var i, j, mline, lines, rtpmap, newdesc;
  11521. for (i = 0; i < this.media.length; i++) {
  11522. lines = this.media[i].split('\r\n');
  11523. lines.pop(); // remove empty last element
  11524. mline = SDPUtil.parse_mline(lines.shift());
  11525. if (mline.media != 'audio')
  11526. continue;
  11527. newdesc = '';
  11528. mline.fmt.length = 0;
  11529. for (j = 0; j < lines.length; j++) {
  11530. if (lines[j].substr(0, 9) == 'a=rtpmap:') {
  11531. rtpmap = SDPUtil.parse_rtpmap(lines[j]);
  11532. if (rtpmap.name == 'CN' || rtpmap.name == 'ISAC')
  11533. continue;
  11534. mline.fmt.push(rtpmap.id);
  11535. newdesc += lines[j] + '\r\n';
  11536. } else {
  11537. newdesc += lines[j] + '\r\n';
  11538. }
  11539. }
  11540. this.media[i] = SDPUtil.build_mline(mline) + '\r\n';
  11541. this.media[i] += newdesc;
  11542. }
  11543. this.raw = this.session + this.media.join('');
  11544. };
  11545. // remove lines matching prefix from session section
  11546. SDP.prototype.removeSessionLines = function(prefix) {
  11547. var self = this;
  11548. var lines = SDPUtil.find_lines(this.session, prefix);
  11549. lines.forEach(function(line) {
  11550. self.session = self.session.replace(line + '\r\n', '');
  11551. });
  11552. this.raw = this.session + this.media.join('');
  11553. return lines;
  11554. }
  11555. // remove lines matching prefix from a media section specified by mediaindex
  11556. // TODO: non-numeric mediaindex could match mid
  11557. SDP.prototype.removeMediaLines = function(mediaindex, prefix) {
  11558. var self = this;
  11559. var lines = SDPUtil.find_lines(this.media[mediaindex], prefix);
  11560. lines.forEach(function(line) {
  11561. self.media[mediaindex] = self.media[mediaindex].replace(line + '\r\n', '');
  11562. });
  11563. this.raw = this.session + this.media.join('');
  11564. return lines;
  11565. }
  11566. // add content's to a jingle element
  11567. SDP.prototype.toJingle = function (elem, thecreator, ssrcs) {
  11568. // console.log("SSRC" + ssrcs["audio"] + " - " + ssrcs["video"]);
  11569. var i, j, k, mline, ssrc, rtpmap, tmp, line, lines;
  11570. var self = this;
  11571. // new bundle plan
  11572. if (SDPUtil.find_line(this.session, 'a=group:')) {
  11573. lines = SDPUtil.find_lines(this.session, 'a=group:');
  11574. for (i = 0; i < lines.length; i++) {
  11575. tmp = lines[i].split(' ');
  11576. var semantics = tmp.shift().substr(8);
  11577. elem.c('group', {xmlns: 'urn:xmpp:jingle:apps:grouping:0', semantics:semantics});
  11578. for (j = 0; j < tmp.length; j++) {
  11579. elem.c('content', {name: tmp[j]}).up();
  11580. }
  11581. elem.up();
  11582. }
  11583. }
  11584. for (i = 0; i < this.media.length; i++) {
  11585. mline = SDPUtil.parse_mline(this.media[i].split('\r\n')[0]);
  11586. if (!(mline.media === 'audio' ||
  11587. mline.media === 'video' ||
  11588. mline.media === 'application'))
  11589. {
  11590. continue;
  11591. }
  11592. if (SDPUtil.find_line(this.media[i], 'a=ssrc:')) {
  11593. ssrc = SDPUtil.find_line(this.media[i], 'a=ssrc:').substring(7).split(' ')[0]; // take the first
  11594. } else {
  11595. if(ssrcs && ssrcs[mline.media])
  11596. {
  11597. ssrc = ssrcs[mline.media];
  11598. }
  11599. else
  11600. ssrc = false;
  11601. }
  11602. elem.c('content', {creator: thecreator, name: mline.media});
  11603. if (SDPUtil.find_line(this.media[i], 'a=mid:')) {
  11604. // prefer identifier from a=mid if present
  11605. var mid = SDPUtil.parse_mid(SDPUtil.find_line(this.media[i], 'a=mid:'));
  11606. elem.attrs({ name: mid });
  11607. }
  11608. if (SDPUtil.find_line(this.media[i], 'a=rtpmap:').length)
  11609. {
  11610. elem.c('description',
  11611. {xmlns: 'urn:xmpp:jingle:apps:rtp:1',
  11612. media: mline.media });
  11613. if (ssrc) {
  11614. elem.attrs({ssrc: ssrc});
  11615. }
  11616. for (j = 0; j < mline.fmt.length; j++) {
  11617. rtpmap = SDPUtil.find_line(this.media[i], 'a=rtpmap:' + mline.fmt[j]);
  11618. elem.c('payload-type', SDPUtil.parse_rtpmap(rtpmap));
  11619. // put any 'a=fmtp:' + mline.fmt[j] lines into <param name=foo value=bar/>
  11620. if (SDPUtil.find_line(this.media[i], 'a=fmtp:' + mline.fmt[j])) {
  11621. tmp = SDPUtil.parse_fmtp(SDPUtil.find_line(this.media[i], 'a=fmtp:' + mline.fmt[j]));
  11622. for (k = 0; k < tmp.length; k++) {
  11623. elem.c('parameter', tmp[k]).up();
  11624. }
  11625. }
  11626. this.RtcpFbToJingle(i, elem, mline.fmt[j]); // XEP-0293 -- map a=rtcp-fb
  11627. elem.up();
  11628. }
  11629. if (SDPUtil.find_line(this.media[i], 'a=crypto:', this.session)) {
  11630. elem.c('encryption', {required: 1});
  11631. var crypto = SDPUtil.find_lines(this.media[i], 'a=crypto:', this.session);
  11632. crypto.forEach(function(line) {
  11633. elem.c('crypto', SDPUtil.parse_crypto(line)).up();
  11634. });
  11635. elem.up(); // end of encryption
  11636. }
  11637. if (ssrc) {
  11638. // new style mapping
  11639. elem.c('source', { ssrc: ssrc, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  11640. // FIXME: group by ssrc and support multiple different ssrcs
  11641. var ssrclines = SDPUtil.find_lines(this.media[i], 'a=ssrc:');
  11642. if(ssrclines.length > 0) {
  11643. ssrclines.forEach(function (line) {
  11644. idx = line.indexOf(' ');
  11645. var linessrc = line.substr(0, idx).substr(7);
  11646. if (linessrc != ssrc) {
  11647. elem.up();
  11648. ssrc = linessrc;
  11649. elem.c('source', { ssrc: ssrc, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  11650. }
  11651. var kv = line.substr(idx + 1);
  11652. elem.c('parameter');
  11653. if (kv.indexOf(':') == -1) {
  11654. elem.attrs({ name: kv });
  11655. } else {
  11656. elem.attrs({ name: kv.split(':', 2)[0] });
  11657. elem.attrs({ value: kv.split(':', 2)[1] });
  11658. }
  11659. elem.up();
  11660. });
  11661. elem.up();
  11662. }
  11663. else
  11664. {
  11665. elem.up();
  11666. elem.c('source', { ssrc: ssrc, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  11667. elem.c('parameter');
  11668. elem.attrs({name: "cname", value:Math.random().toString(36).substring(7)});
  11669. elem.up();
  11670. var msid = null;
  11671. if(mline.media == "audio")
  11672. {
  11673. msid = APP.RTC.localAudio.getId();
  11674. }
  11675. else
  11676. {
  11677. msid = APP.RTC.localVideo.getId();
  11678. }
  11679. if(msid != null)
  11680. {
  11681. msid = msid.replace(/[\{,\}]/g,"");
  11682. elem.c('parameter');
  11683. elem.attrs({name: "msid", value:msid});
  11684. elem.up();
  11685. elem.c('parameter');
  11686. elem.attrs({name: "mslabel", value:msid});
  11687. elem.up();
  11688. elem.c('parameter');
  11689. elem.attrs({name: "label", value:msid});
  11690. elem.up();
  11691. elem.up();
  11692. }
  11693. }
  11694. // XEP-0339 handle ssrc-group attributes
  11695. var ssrc_group_lines = SDPUtil.find_lines(this.media[i], 'a=ssrc-group:');
  11696. ssrc_group_lines.forEach(function(line) {
  11697. idx = line.indexOf(' ');
  11698. var semantics = line.substr(0, idx).substr(13);
  11699. var ssrcs = line.substr(14 + semantics.length).split(' ');
  11700. if (ssrcs.length != 0) {
  11701. elem.c('ssrc-group', { semantics: semantics, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  11702. ssrcs.forEach(function(ssrc) {
  11703. elem.c('source', { ssrc: ssrc })
  11704. .up();
  11705. });
  11706. elem.up();
  11707. }
  11708. });
  11709. }
  11710. if (SDPUtil.find_line(this.media[i], 'a=rtcp-mux')) {
  11711. elem.c('rtcp-mux').up();
  11712. }
  11713. // XEP-0293 -- map a=rtcp-fb:*
  11714. this.RtcpFbToJingle(i, elem, '*');
  11715. // XEP-0294
  11716. if (SDPUtil.find_line(this.media[i], 'a=extmap:')) {
  11717. lines = SDPUtil.find_lines(this.media[i], 'a=extmap:');
  11718. for (j = 0; j < lines.length; j++) {
  11719. tmp = SDPUtil.parse_extmap(lines[j]);
  11720. elem.c('rtp-hdrext', { xmlns: 'urn:xmpp:jingle:apps:rtp:rtp-hdrext:0',
  11721. uri: tmp.uri,
  11722. id: tmp.value });
  11723. if (tmp.hasOwnProperty('direction')) {
  11724. switch (tmp.direction) {
  11725. case 'sendonly':
  11726. elem.attrs({senders: 'responder'});
  11727. break;
  11728. case 'recvonly':
  11729. elem.attrs({senders: 'initiator'});
  11730. break;
  11731. case 'sendrecv':
  11732. elem.attrs({senders: 'both'});
  11733. break;
  11734. case 'inactive':
  11735. elem.attrs({senders: 'none'});
  11736. break;
  11737. }
  11738. }
  11739. // TODO: handle params
  11740. elem.up();
  11741. }
  11742. }
  11743. elem.up(); // end of description
  11744. }
  11745. // map ice-ufrag/pwd, dtls fingerprint, candidates
  11746. this.TransportToJingle(i, elem);
  11747. if (SDPUtil.find_line(this.media[i], 'a=sendrecv', this.session)) {
  11748. elem.attrs({senders: 'both'});
  11749. } else if (SDPUtil.find_line(this.media[i], 'a=sendonly', this.session)) {
  11750. elem.attrs({senders: 'initiator'});
  11751. } else if (SDPUtil.find_line(this.media[i], 'a=recvonly', this.session)) {
  11752. elem.attrs({senders: 'responder'});
  11753. } else if (SDPUtil.find_line(this.media[i], 'a=inactive', this.session)) {
  11754. elem.attrs({senders: 'none'});
  11755. }
  11756. if (mline.port == '0') {
  11757. // estos hack to reject an m-line
  11758. elem.attrs({senders: 'rejected'});
  11759. }
  11760. elem.up(); // end of content
  11761. }
  11762. elem.up();
  11763. return elem;
  11764. };
  11765. SDP.prototype.TransportToJingle = function (mediaindex, elem) {
  11766. var i = mediaindex;
  11767. var tmp;
  11768. var self = this;
  11769. elem.c('transport');
  11770. // XEP-0343 DTLS/SCTP
  11771. if (SDPUtil.find_line(this.media[mediaindex], 'a=sctpmap:').length)
  11772. {
  11773. var sctpmap = SDPUtil.find_line(
  11774. this.media[i], 'a=sctpmap:', self.session);
  11775. if (sctpmap)
  11776. {
  11777. var sctpAttrs = SDPUtil.parse_sctpmap(sctpmap);
  11778. elem.c('sctpmap',
  11779. {
  11780. xmlns: 'urn:xmpp:jingle:transports:dtls-sctp:1',
  11781. number: sctpAttrs[0], /* SCTP port */
  11782. protocol: sctpAttrs[1], /* protocol */
  11783. });
  11784. // Optional stream count attribute
  11785. if (sctpAttrs.length > 2)
  11786. elem.attrs({ streams: sctpAttrs[2]});
  11787. elem.up();
  11788. }
  11789. }
  11790. // XEP-0320
  11791. var fingerprints = SDPUtil.find_lines(this.media[mediaindex], 'a=fingerprint:', this.session);
  11792. fingerprints.forEach(function(line) {
  11793. tmp = SDPUtil.parse_fingerprint(line);
  11794. tmp.xmlns = 'urn:xmpp:jingle:apps:dtls:0';
  11795. elem.c('fingerprint').t(tmp.fingerprint);
  11796. delete tmp.fingerprint;
  11797. line = SDPUtil.find_line(self.media[mediaindex], 'a=setup:', self.session);
  11798. if (line) {
  11799. tmp.setup = line.substr(8);
  11800. }
  11801. elem.attrs(tmp);
  11802. elem.up(); // end of fingerprint
  11803. });
  11804. tmp = SDPUtil.iceparams(this.media[mediaindex], this.session);
  11805. if (tmp) {
  11806. tmp.xmlns = 'urn:xmpp:jingle:transports:ice-udp:1';
  11807. elem.attrs(tmp);
  11808. // XEP-0176
  11809. if (SDPUtil.find_line(this.media[mediaindex], 'a=candidate:', this.session)) { // add any a=candidate lines
  11810. var lines = SDPUtil.find_lines(this.media[mediaindex], 'a=candidate:', this.session);
  11811. lines.forEach(function (line) {
  11812. elem.c('candidate', SDPUtil.candidateToJingle(line)).up();
  11813. });
  11814. }
  11815. }
  11816. elem.up(); // end of transport
  11817. }
  11818. SDP.prototype.RtcpFbToJingle = function (mediaindex, elem, payloadtype) { // XEP-0293
  11819. var lines = SDPUtil.find_lines(this.media[mediaindex], 'a=rtcp-fb:' + payloadtype);
  11820. lines.forEach(function (line) {
  11821. var tmp = SDPUtil.parse_rtcpfb(line);
  11822. if (tmp.type == 'trr-int') {
  11823. elem.c('rtcp-fb-trr-int', {xmlns: 'urn:xmpp:jingle:apps:rtp:rtcp-fb:0', value: tmp.params[0]});
  11824. elem.up();
  11825. } else {
  11826. elem.c('rtcp-fb', {xmlns: 'urn:xmpp:jingle:apps:rtp:rtcp-fb:0', type: tmp.type});
  11827. if (tmp.params.length > 0) {
  11828. elem.attrs({'subtype': tmp.params[0]});
  11829. }
  11830. elem.up();
  11831. }
  11832. });
  11833. };
  11834. SDP.prototype.RtcpFbFromJingle = function (elem, payloadtype) { // XEP-0293
  11835. var media = '';
  11836. var tmp = elem.find('>rtcp-fb-trr-int[xmlns="urn:xmpp:jingle:apps:rtp:rtcp-fb:0"]');
  11837. if (tmp.length) {
  11838. media += 'a=rtcp-fb:' + '*' + ' ' + 'trr-int' + ' ';
  11839. if (tmp.attr('value')) {
  11840. media += tmp.attr('value');
  11841. } else {
  11842. media += '0';
  11843. }
  11844. media += '\r\n';
  11845. }
  11846. tmp = elem.find('>rtcp-fb[xmlns="urn:xmpp:jingle:apps:rtp:rtcp-fb:0"]');
  11847. tmp.each(function () {
  11848. media += 'a=rtcp-fb:' + payloadtype + ' ' + $(this).attr('type');
  11849. if ($(this).attr('subtype')) {
  11850. media += ' ' + $(this).attr('subtype');
  11851. }
  11852. media += '\r\n';
  11853. });
  11854. return media;
  11855. };
  11856. // construct an SDP from a jingle stanza
  11857. SDP.prototype.fromJingle = function (jingle) {
  11858. var self = this;
  11859. this.raw = 'v=0\r\n' +
  11860. 'o=- ' + '1923518516' + ' 2 IN IP4 0.0.0.0\r\n' +// FIXME
  11861. 's=-\r\n' +
  11862. 't=0 0\r\n';
  11863. // http://tools.ietf.org/html/draft-ietf-mmusic-sdp-bundle-negotiation-04#section-8
  11864. if ($(jingle).find('>group[xmlns="urn:xmpp:jingle:apps:grouping:0"]').length) {
  11865. $(jingle).find('>group[xmlns="urn:xmpp:jingle:apps:grouping:0"]').each(function (idx, group) {
  11866. var contents = $(group).find('>content').map(function (idx, content) {
  11867. return content.getAttribute('name');
  11868. }).get();
  11869. if (contents.length > 0) {
  11870. self.raw += 'a=group:' + (group.getAttribute('semantics') || group.getAttribute('type')) + ' ' + contents.join(' ') + '\r\n';
  11871. }
  11872. });
  11873. }
  11874. this.session = this.raw;
  11875. jingle.find('>content').each(function () {
  11876. var m = self.jingle2media($(this));
  11877. self.media.push(m);
  11878. });
  11879. // reconstruct msid-semantic -- apparently not necessary
  11880. /*
  11881. var msid = SDPUtil.parse_ssrc(this.raw);
  11882. if (msid.hasOwnProperty('mslabel')) {
  11883. this.session += "a=msid-semantic: WMS " + msid.mslabel + "\r\n";
  11884. }
  11885. */
  11886. this.raw = this.session + this.media.join('');
  11887. };
  11888. // translate a jingle content element into an an SDP media part
  11889. SDP.prototype.jingle2media = function (content) {
  11890. var media = '',
  11891. desc = content.find('description'),
  11892. ssrc = desc.attr('ssrc'),
  11893. self = this,
  11894. tmp;
  11895. var sctp = content.find(
  11896. '>transport>sctpmap[xmlns="urn:xmpp:jingle:transports:dtls-sctp:1"]');
  11897. tmp = { media: desc.attr('media') };
  11898. tmp.port = '1';
  11899. if (content.attr('senders') == 'rejected') {
  11900. // estos hack to reject an m-line.
  11901. tmp.port = '0';
  11902. }
  11903. if (content.find('>transport>fingerprint').length || desc.find('encryption').length) {
  11904. if (sctp.length)
  11905. tmp.proto = 'DTLS/SCTP';
  11906. else
  11907. tmp.proto = 'RTP/SAVPF';
  11908. } else {
  11909. tmp.proto = 'RTP/AVPF';
  11910. }
  11911. if (!sctp.length)
  11912. {
  11913. tmp.fmt = desc.find('payload-type').map(
  11914. function () { return this.getAttribute('id'); }).get();
  11915. media += SDPUtil.build_mline(tmp) + '\r\n';
  11916. }
  11917. else
  11918. {
  11919. media += 'm=application 1 DTLS/SCTP ' + sctp.attr('number') + '\r\n';
  11920. media += 'a=sctpmap:' + sctp.attr('number') +
  11921. ' ' + sctp.attr('protocol');
  11922. var streamCount = sctp.attr('streams');
  11923. if (streamCount)
  11924. media += ' ' + streamCount + '\r\n';
  11925. else
  11926. media += '\r\n';
  11927. }
  11928. media += 'c=IN IP4 0.0.0.0\r\n';
  11929. if (!sctp.length)
  11930. media += 'a=rtcp:1 IN IP4 0.0.0.0\r\n';
  11931. tmp = content.find('>transport[xmlns="urn:xmpp:jingle:transports:ice-udp:1"]');
  11932. if (tmp.length) {
  11933. if (tmp.attr('ufrag')) {
  11934. media += SDPUtil.build_iceufrag(tmp.attr('ufrag')) + '\r\n';
  11935. }
  11936. if (tmp.attr('pwd')) {
  11937. media += SDPUtil.build_icepwd(tmp.attr('pwd')) + '\r\n';
  11938. }
  11939. tmp.find('>fingerprint').each(function () {
  11940. // FIXME: check namespace at some point
  11941. media += 'a=fingerprint:' + this.getAttribute('hash');
  11942. media += ' ' + $(this).text();
  11943. media += '\r\n';
  11944. if (this.getAttribute('setup')) {
  11945. media += 'a=setup:' + this.getAttribute('setup') + '\r\n';
  11946. }
  11947. });
  11948. }
  11949. switch (content.attr('senders')) {
  11950. case 'initiator':
  11951. media += 'a=sendonly\r\n';
  11952. break;
  11953. case 'responder':
  11954. media += 'a=recvonly\r\n';
  11955. break;
  11956. case 'none':
  11957. media += 'a=inactive\r\n';
  11958. break;
  11959. case 'both':
  11960. media += 'a=sendrecv\r\n';
  11961. break;
  11962. }
  11963. media += 'a=mid:' + content.attr('name') + '\r\n';
  11964. // <description><rtcp-mux/></description>
  11965. // see http://code.google.com/p/libjingle/issues/detail?id=309 -- no spec though
  11966. // and http://mail.jabber.org/pipermail/jingle/2011-December/001761.html
  11967. if (desc.find('rtcp-mux').length) {
  11968. media += 'a=rtcp-mux\r\n';
  11969. }
  11970. if (desc.find('encryption').length) {
  11971. desc.find('encryption>crypto').each(function () {
  11972. media += 'a=crypto:' + this.getAttribute('tag');
  11973. media += ' ' + this.getAttribute('crypto-suite');
  11974. media += ' ' + this.getAttribute('key-params');
  11975. if (this.getAttribute('session-params')) {
  11976. media += ' ' + this.getAttribute('session-params');
  11977. }
  11978. media += '\r\n';
  11979. });
  11980. }
  11981. desc.find('payload-type').each(function () {
  11982. media += SDPUtil.build_rtpmap(this) + '\r\n';
  11983. if ($(this).find('>parameter').length) {
  11984. media += 'a=fmtp:' + this.getAttribute('id') + ' ';
  11985. media += $(this).find('parameter').map(function () { return (this.getAttribute('name') ? (this.getAttribute('name') + '=') : '') + this.getAttribute('value'); }).get().join('; ');
  11986. media += '\r\n';
  11987. }
  11988. // xep-0293
  11989. media += self.RtcpFbFromJingle($(this), this.getAttribute('id'));
  11990. });
  11991. // xep-0293
  11992. media += self.RtcpFbFromJingle(desc, '*');
  11993. // xep-0294
  11994. tmp = desc.find('>rtp-hdrext[xmlns="urn:xmpp:jingle:apps:rtp:rtp-hdrext:0"]');
  11995. tmp.each(function () {
  11996. media += 'a=extmap:' + this.getAttribute('id') + ' ' + this.getAttribute('uri') + '\r\n';
  11997. });
  11998. content.find('>transport[xmlns="urn:xmpp:jingle:transports:ice-udp:1"]>candidate').each(function () {
  11999. media += SDPUtil.candidateFromJingle(this);
  12000. });
  12001. // XEP-0339 handle ssrc-group attributes
  12002. tmp = content.find('description>ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]').each(function() {
  12003. var semantics = this.getAttribute('semantics');
  12004. var ssrcs = $(this).find('>source').map(function() {
  12005. return this.getAttribute('ssrc');
  12006. }).get();
  12007. if (ssrcs.length != 0) {
  12008. media += 'a=ssrc-group:' + semantics + ' ' + ssrcs.join(' ') + '\r\n';
  12009. }
  12010. });
  12011. tmp = content.find('description>source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]');
  12012. tmp.each(function () {
  12013. var ssrc = this.getAttribute('ssrc');
  12014. $(this).find('>parameter').each(function () {
  12015. media += 'a=ssrc:' + ssrc + ' ' + this.getAttribute('name');
  12016. if (this.getAttribute('value') && this.getAttribute('value').length)
  12017. media += ':' + this.getAttribute('value');
  12018. media += '\r\n';
  12019. });
  12020. });
  12021. return media;
  12022. };
  12023. module.exports = SDP;
  12024. },{"./SDPUtil":50}],49:[function(require,module,exports){
  12025. function SDPDiffer(mySDP, otherSDP) {
  12026. this.mySDP = mySDP;
  12027. this.otherSDP = otherSDP;
  12028. }
  12029. /**
  12030. * Returns map of MediaChannel that contains only media not contained in <tt>otherSdp</tt>. Mapped by channel idx.
  12031. * @param otherSdp the other SDP to check ssrc with.
  12032. */
  12033. SDPDiffer.prototype.getNewMedia = function() {
  12034. // this could be useful in Array.prototype.
  12035. function arrayEquals(array) {
  12036. // if the other array is a falsy value, return
  12037. if (!array)
  12038. return false;
  12039. // compare lengths - can save a lot of time
  12040. if (this.length != array.length)
  12041. return false;
  12042. for (var i = 0, l=this.length; i < l; i++) {
  12043. // Check if we have nested arrays
  12044. if (this[i] instanceof Array && array[i] instanceof Array) {
  12045. // recurse into the nested arrays
  12046. if (!this[i].equals(array[i]))
  12047. return false;
  12048. }
  12049. else if (this[i] != array[i]) {
  12050. // Warning - two different object instances will never be equal: {x:20} != {x:20}
  12051. return false;
  12052. }
  12053. }
  12054. return true;
  12055. }
  12056. var myMedias = this.mySDP.getMediaSsrcMap();
  12057. var othersMedias = this.otherSDP.getMediaSsrcMap();
  12058. var newMedia = {};
  12059. Object.keys(othersMedias).forEach(function(othersMediaIdx) {
  12060. var myMedia = myMedias[othersMediaIdx];
  12061. var othersMedia = othersMedias[othersMediaIdx];
  12062. if(!myMedia && othersMedia) {
  12063. // Add whole channel
  12064. newMedia[othersMediaIdx] = othersMedia;
  12065. return;
  12066. }
  12067. // Look for new ssrcs accross the channel
  12068. Object.keys(othersMedia.ssrcs).forEach(function(ssrc) {
  12069. if(Object.keys(myMedia.ssrcs).indexOf(ssrc) === -1) {
  12070. // Allocate channel if we've found ssrc that doesn't exist in our channel
  12071. if(!newMedia[othersMediaIdx]){
  12072. newMedia[othersMediaIdx] = {
  12073. mediaindex: othersMedia.mediaindex,
  12074. mid: othersMedia.mid,
  12075. ssrcs: {},
  12076. ssrcGroups: []
  12077. };
  12078. }
  12079. newMedia[othersMediaIdx].ssrcs[ssrc] = othersMedia.ssrcs[ssrc];
  12080. }
  12081. });
  12082. // Look for new ssrc groups across the channels
  12083. othersMedia.ssrcGroups.forEach(function(otherSsrcGroup){
  12084. // try to match the other ssrc-group with an ssrc-group of ours
  12085. var matched = false;
  12086. for (var i = 0; i < myMedia.ssrcGroups.length; i++) {
  12087. var mySsrcGroup = myMedia.ssrcGroups[i];
  12088. if (otherSsrcGroup.semantics == mySsrcGroup.semantics
  12089. && arrayEquals.apply(otherSsrcGroup.ssrcs, [mySsrcGroup.ssrcs])) {
  12090. matched = true;
  12091. break;
  12092. }
  12093. }
  12094. if (!matched) {
  12095. // Allocate channel if we've found an ssrc-group that doesn't
  12096. // exist in our channel
  12097. if(!newMedia[othersMediaIdx]){
  12098. newMedia[othersMediaIdx] = {
  12099. mediaindex: othersMedia.mediaindex,
  12100. mid: othersMedia.mid,
  12101. ssrcs: {},
  12102. ssrcGroups: []
  12103. };
  12104. }
  12105. newMedia[othersMediaIdx].ssrcGroups.push(otherSsrcGroup);
  12106. }
  12107. });
  12108. });
  12109. return newMedia;
  12110. };
  12111. /**
  12112. * Sends SSRC update IQ.
  12113. * @param sdpMediaSsrcs SSRCs map obtained from SDP.getNewMedia. Cntains SSRCs to add/remove.
  12114. * @param sid session identifier that will be put into the IQ.
  12115. * @param initiator initiator identifier.
  12116. * @param toJid destination Jid
  12117. * @param isAdd indicates if this is remove or add operation.
  12118. */
  12119. SDPDiffer.prototype.toJingle = function(modify) {
  12120. var sdpMediaSsrcs = this.getNewMedia();
  12121. var self = this;
  12122. // FIXME: only announce video ssrcs since we mix audio and dont need
  12123. // the audio ssrcs therefore
  12124. var modified = false;
  12125. Object.keys(sdpMediaSsrcs).forEach(function(mediaindex){
  12126. modified = true;
  12127. var media = sdpMediaSsrcs[mediaindex];
  12128. modify.c('content', {name: media.mid});
  12129. modify.c('description', {xmlns:'urn:xmpp:jingle:apps:rtp:1', media: media.mid});
  12130. // FIXME: not completly sure this operates on blocks and / or handles different ssrcs correctly
  12131. // generate sources from lines
  12132. Object.keys(media.ssrcs).forEach(function(ssrcNum) {
  12133. var mediaSsrc = media.ssrcs[ssrcNum];
  12134. modify.c('source', { xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  12135. modify.attrs({ssrc: mediaSsrc.ssrc});
  12136. // iterate over ssrc lines
  12137. mediaSsrc.lines.forEach(function (line) {
  12138. var idx = line.indexOf(' ');
  12139. var kv = line.substr(idx + 1);
  12140. modify.c('parameter');
  12141. if (kv.indexOf(':') == -1) {
  12142. modify.attrs({ name: kv });
  12143. } else {
  12144. modify.attrs({ name: kv.split(':', 2)[0] });
  12145. modify.attrs({ value: kv.split(':', 2)[1] });
  12146. }
  12147. modify.up(); // end of parameter
  12148. });
  12149. modify.up(); // end of source
  12150. });
  12151. // generate source groups from lines
  12152. media.ssrcGroups.forEach(function(ssrcGroup) {
  12153. if (ssrcGroup.ssrcs.length != 0) {
  12154. modify.c('ssrc-group', {
  12155. semantics: ssrcGroup.semantics,
  12156. xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0'
  12157. });
  12158. ssrcGroup.ssrcs.forEach(function (ssrc) {
  12159. modify.c('source', { ssrc: ssrc })
  12160. .up(); // end of source
  12161. });
  12162. modify.up(); // end of ssrc-group
  12163. }
  12164. });
  12165. modify.up(); // end of description
  12166. modify.up(); // end of content
  12167. });
  12168. return modified;
  12169. };
  12170. module.exports = SDPDiffer;
  12171. },{}],50:[function(require,module,exports){
  12172. SDPUtil = {
  12173. iceparams: function (mediadesc, sessiondesc) {
  12174. var data = null;
  12175. if (SDPUtil.find_line(mediadesc, 'a=ice-ufrag:', sessiondesc) &&
  12176. SDPUtil.find_line(mediadesc, 'a=ice-pwd:', sessiondesc)) {
  12177. data = {
  12178. ufrag: SDPUtil.parse_iceufrag(SDPUtil.find_line(mediadesc, 'a=ice-ufrag:', sessiondesc)),
  12179. pwd: SDPUtil.parse_icepwd(SDPUtil.find_line(mediadesc, 'a=ice-pwd:', sessiondesc))
  12180. };
  12181. }
  12182. return data;
  12183. },
  12184. parse_iceufrag: function (line) {
  12185. return line.substring(12);
  12186. },
  12187. build_iceufrag: function (frag) {
  12188. return 'a=ice-ufrag:' + frag;
  12189. },
  12190. parse_icepwd: function (line) {
  12191. return line.substring(10);
  12192. },
  12193. build_icepwd: function (pwd) {
  12194. return 'a=ice-pwd:' + pwd;
  12195. },
  12196. parse_mid: function (line) {
  12197. return line.substring(6);
  12198. },
  12199. parse_mline: function (line) {
  12200. var parts = line.substring(2).split(' '),
  12201. data = {};
  12202. data.media = parts.shift();
  12203. data.port = parts.shift();
  12204. data.proto = parts.shift();
  12205. if (parts[parts.length - 1] === '') { // trailing whitespace
  12206. parts.pop();
  12207. }
  12208. data.fmt = parts;
  12209. return data;
  12210. },
  12211. build_mline: function (mline) {
  12212. return 'm=' + mline.media + ' ' + mline.port + ' ' + mline.proto + ' ' + mline.fmt.join(' ');
  12213. },
  12214. parse_rtpmap: function (line) {
  12215. var parts = line.substring(9).split(' '),
  12216. data = {};
  12217. data.id = parts.shift();
  12218. parts = parts[0].split('/');
  12219. data.name = parts.shift();
  12220. data.clockrate = parts.shift();
  12221. data.channels = parts.length ? parts.shift() : '1';
  12222. return data;
  12223. },
  12224. /**
  12225. * Parses SDP line "a=sctpmap:..." and extracts SCTP port from it.
  12226. * @param line eg. "a=sctpmap:5000 webrtc-datachannel"
  12227. * @returns [SCTP port number, protocol, streams]
  12228. */
  12229. parse_sctpmap: function (line)
  12230. {
  12231. var parts = line.substring(10).split(' ');
  12232. var sctpPort = parts[0];
  12233. var protocol = parts[1];
  12234. // Stream count is optional
  12235. var streamCount = parts.length > 2 ? parts[2] : null;
  12236. return [sctpPort, protocol, streamCount];// SCTP port
  12237. },
  12238. build_rtpmap: function (el) {
  12239. var line = 'a=rtpmap:' + el.getAttribute('id') + ' ' + el.getAttribute('name') + '/' + el.getAttribute('clockrate');
  12240. if (el.getAttribute('channels') && el.getAttribute('channels') != '1') {
  12241. line += '/' + el.getAttribute('channels');
  12242. }
  12243. return line;
  12244. },
  12245. parse_crypto: function (line) {
  12246. var parts = line.substring(9).split(' '),
  12247. data = {};
  12248. data.tag = parts.shift();
  12249. data['crypto-suite'] = parts.shift();
  12250. data['key-params'] = parts.shift();
  12251. if (parts.length) {
  12252. data['session-params'] = parts.join(' ');
  12253. }
  12254. return data;
  12255. },
  12256. parse_fingerprint: function (line) { // RFC 4572
  12257. var parts = line.substring(14).split(' '),
  12258. data = {};
  12259. data.hash = parts.shift();
  12260. data.fingerprint = parts.shift();
  12261. // TODO assert that fingerprint satisfies 2UHEX *(":" 2UHEX) ?
  12262. return data;
  12263. },
  12264. parse_fmtp: function (line) {
  12265. var parts = line.split(' '),
  12266. i, key, value,
  12267. data = [];
  12268. parts.shift();
  12269. parts = parts.join(' ').split(';');
  12270. for (i = 0; i < parts.length; i++) {
  12271. key = parts[i].split('=')[0];
  12272. while (key.length && key[0] == ' ') {
  12273. key = key.substring(1);
  12274. }
  12275. value = parts[i].split('=')[1];
  12276. if (key && value) {
  12277. data.push({name: key, value: value});
  12278. } else if (key) {
  12279. // rfc 4733 (DTMF) style stuff
  12280. data.push({name: '', value: key});
  12281. }
  12282. }
  12283. return data;
  12284. },
  12285. parse_icecandidate: function (line) {
  12286. var candidate = {},
  12287. elems = line.split(' ');
  12288. candidate.foundation = elems[0].substring(12);
  12289. candidate.component = elems[1];
  12290. candidate.protocol = elems[2].toLowerCase();
  12291. candidate.priority = elems[3];
  12292. candidate.ip = elems[4];
  12293. candidate.port = elems[5];
  12294. // elems[6] => "typ"
  12295. candidate.type = elems[7];
  12296. candidate.generation = 0; // default value, may be overwritten below
  12297. for (var i = 8; i < elems.length; i += 2) {
  12298. switch (elems[i]) {
  12299. case 'raddr':
  12300. candidate['rel-addr'] = elems[i + 1];
  12301. break;
  12302. case 'rport':
  12303. candidate['rel-port'] = elems[i + 1];
  12304. break;
  12305. case 'generation':
  12306. candidate.generation = elems[i + 1];
  12307. break;
  12308. case 'tcptype':
  12309. candidate.tcptype = elems[i + 1];
  12310. break;
  12311. default: // TODO
  12312. console.log('parse_icecandidate not translating "' + elems[i] + '" = "' + elems[i + 1] + '"');
  12313. }
  12314. }
  12315. candidate.network = '1';
  12316. candidate.id = Math.random().toString(36).substr(2, 10); // not applicable to SDP -- FIXME: should be unique, not just random
  12317. return candidate;
  12318. },
  12319. build_icecandidate: function (cand) {
  12320. var line = ['a=candidate:' + cand.foundation, cand.component, cand.protocol, cand.priority, cand.ip, cand.port, 'typ', cand.type].join(' ');
  12321. line += ' ';
  12322. switch (cand.type) {
  12323. case 'srflx':
  12324. case 'prflx':
  12325. case 'relay':
  12326. if (cand.hasOwnAttribute('rel-addr') && cand.hasOwnAttribute('rel-port')) {
  12327. line += 'raddr';
  12328. line += ' ';
  12329. line += cand['rel-addr'];
  12330. line += ' ';
  12331. line += 'rport';
  12332. line += ' ';
  12333. line += cand['rel-port'];
  12334. line += ' ';
  12335. }
  12336. break;
  12337. }
  12338. if (cand.hasOwnAttribute('tcptype')) {
  12339. line += 'tcptype';
  12340. line += ' ';
  12341. line += cand.tcptype;
  12342. line += ' ';
  12343. }
  12344. line += 'generation';
  12345. line += ' ';
  12346. line += cand.hasOwnAttribute('generation') ? cand.generation : '0';
  12347. return line;
  12348. },
  12349. parse_ssrc: function (desc) {
  12350. // proprietary mapping of a=ssrc lines
  12351. // TODO: see "Jingle RTP Source Description" by Juberti and P. Thatcher on google docs
  12352. // and parse according to that
  12353. var lines = desc.split('\r\n'),
  12354. data = {};
  12355. for (var i = 0; i < lines.length; i++) {
  12356. if (lines[i].substring(0, 7) == 'a=ssrc:') {
  12357. var idx = lines[i].indexOf(' ');
  12358. data[lines[i].substr(idx + 1).split(':', 2)[0]] = lines[i].substr(idx + 1).split(':', 2)[1];
  12359. }
  12360. }
  12361. return data;
  12362. },
  12363. parse_rtcpfb: function (line) {
  12364. var parts = line.substr(10).split(' ');
  12365. var data = {};
  12366. data.pt = parts.shift();
  12367. data.type = parts.shift();
  12368. data.params = parts;
  12369. return data;
  12370. },
  12371. parse_extmap: function (line) {
  12372. var parts = line.substr(9).split(' ');
  12373. var data = {};
  12374. data.value = parts.shift();
  12375. if (data.value.indexOf('/') != -1) {
  12376. data.direction = data.value.substr(data.value.indexOf('/') + 1);
  12377. data.value = data.value.substr(0, data.value.indexOf('/'));
  12378. } else {
  12379. data.direction = 'both';
  12380. }
  12381. data.uri = parts.shift();
  12382. data.params = parts;
  12383. return data;
  12384. },
  12385. find_line: function (haystack, needle, sessionpart) {
  12386. var lines = haystack.split('\r\n');
  12387. for (var i = 0; i < lines.length; i++) {
  12388. if (lines[i].substring(0, needle.length) == needle) {
  12389. return lines[i];
  12390. }
  12391. }
  12392. if (!sessionpart) {
  12393. return false;
  12394. }
  12395. // search session part
  12396. lines = sessionpart.split('\r\n');
  12397. for (var j = 0; j < lines.length; j++) {
  12398. if (lines[j].substring(0, needle.length) == needle) {
  12399. return lines[j];
  12400. }
  12401. }
  12402. return false;
  12403. },
  12404. find_lines: function (haystack, needle, sessionpart) {
  12405. var lines = haystack.split('\r\n'),
  12406. needles = [];
  12407. for (var i = 0; i < lines.length; i++) {
  12408. if (lines[i].substring(0, needle.length) == needle)
  12409. needles.push(lines[i]);
  12410. }
  12411. if (needles.length || !sessionpart) {
  12412. return needles;
  12413. }
  12414. // search session part
  12415. lines = sessionpart.split('\r\n');
  12416. for (var j = 0; j < lines.length; j++) {
  12417. if (lines[j].substring(0, needle.length) == needle) {
  12418. needles.push(lines[j]);
  12419. }
  12420. }
  12421. return needles;
  12422. },
  12423. candidateToJingle: function (line) {
  12424. // a=candidate:2979166662 1 udp 2113937151 192.168.2.100 57698 typ host generation 0
  12425. // <candidate component=... foundation=... generation=... id=... ip=... network=... port=... priority=... protocol=... type=.../>
  12426. if (line.indexOf('candidate:') === 0) {
  12427. line = 'a=' + line;
  12428. } else if (line.substring(0, 12) != 'a=candidate:') {
  12429. console.log('parseCandidate called with a line that is not a candidate line');
  12430. console.log(line);
  12431. return null;
  12432. }
  12433. if (line.substring(line.length - 2) == '\r\n') // chomp it
  12434. line = line.substring(0, line.length - 2);
  12435. var candidate = {},
  12436. elems = line.split(' '),
  12437. i;
  12438. if (elems[6] != 'typ') {
  12439. console.log('did not find typ in the right place');
  12440. console.log(line);
  12441. return null;
  12442. }
  12443. candidate.foundation = elems[0].substring(12);
  12444. candidate.component = elems[1];
  12445. candidate.protocol = elems[2].toLowerCase();
  12446. candidate.priority = elems[3];
  12447. candidate.ip = elems[4];
  12448. candidate.port = elems[5];
  12449. // elems[6] => "typ"
  12450. candidate.type = elems[7];
  12451. candidate.generation = '0'; // default, may be overwritten below
  12452. for (i = 8; i < elems.length; i += 2) {
  12453. switch (elems[i]) {
  12454. case 'raddr':
  12455. candidate['rel-addr'] = elems[i + 1];
  12456. break;
  12457. case 'rport':
  12458. candidate['rel-port'] = elems[i + 1];
  12459. break;
  12460. case 'generation':
  12461. candidate.generation = elems[i + 1];
  12462. break;
  12463. case 'tcptype':
  12464. candidate.tcptype = elems[i + 1];
  12465. break;
  12466. default: // TODO
  12467. console.log('not translating "' + elems[i] + '" = "' + elems[i + 1] + '"');
  12468. }
  12469. }
  12470. candidate.network = '1';
  12471. candidate.id = Math.random().toString(36).substr(2, 10); // not applicable to SDP -- FIXME: should be unique, not just random
  12472. return candidate;
  12473. },
  12474. candidateFromJingle: function (cand) {
  12475. var line = 'a=candidate:';
  12476. line += cand.getAttribute('foundation');
  12477. line += ' ';
  12478. line += cand.getAttribute('component');
  12479. line += ' ';
  12480. line += cand.getAttribute('protocol'); //.toUpperCase(); // chrome M23 doesn't like this
  12481. line += ' ';
  12482. line += cand.getAttribute('priority');
  12483. line += ' ';
  12484. line += cand.getAttribute('ip');
  12485. line += ' ';
  12486. line += cand.getAttribute('port');
  12487. line += ' ';
  12488. line += 'typ';
  12489. line += ' ' + cand.getAttribute('type');
  12490. line += ' ';
  12491. switch (cand.getAttribute('type')) {
  12492. case 'srflx':
  12493. case 'prflx':
  12494. case 'relay':
  12495. if (cand.getAttribute('rel-addr') && cand.getAttribute('rel-port')) {
  12496. line += 'raddr';
  12497. line += ' ';
  12498. line += cand.getAttribute('rel-addr');
  12499. line += ' ';
  12500. line += 'rport';
  12501. line += ' ';
  12502. line += cand.getAttribute('rel-port');
  12503. line += ' ';
  12504. }
  12505. break;
  12506. }
  12507. if (cand.getAttribute('protocol').toLowerCase() == 'tcp') {
  12508. line += 'tcptype';
  12509. line += ' ';
  12510. line += cand.getAttribute('tcptype');
  12511. line += ' ';
  12512. }
  12513. line += 'generation';
  12514. line += ' ';
  12515. line += cand.getAttribute('generation') || '0';
  12516. return line + '\r\n';
  12517. }
  12518. };
  12519. module.exports = SDPUtil;
  12520. },{}],51:[function(require,module,exports){
  12521. function TraceablePeerConnection(ice_config, constraints) {
  12522. var self = this;
  12523. var RTCPeerconnection = navigator.mozGetUserMedia ? mozRTCPeerConnection : webkitRTCPeerConnection;
  12524. this.peerconnection = new RTCPeerconnection(ice_config, constraints);
  12525. this.updateLog = [];
  12526. this.stats = {};
  12527. this.statsinterval = null;
  12528. this.maxstats = 0; // limit to 300 values, i.e. 5 minutes; set to 0 to disable
  12529. var Interop = require('sdp-interop').Interop;
  12530. this.interop = new Interop();
  12531. // override as desired
  12532. this.trace = function (what, info) {
  12533. //console.warn('WTRACE', what, info);
  12534. self.updateLog.push({
  12535. time: new Date(),
  12536. type: what,
  12537. value: info || ""
  12538. });
  12539. };
  12540. this.onicecandidate = null;
  12541. this.peerconnection.onicecandidate = function (event) {
  12542. self.trace('onicecandidate', JSON.stringify(event.candidate, null, ' '));
  12543. if (self.onicecandidate !== null) {
  12544. self.onicecandidate(event);
  12545. }
  12546. };
  12547. this.onaddstream = null;
  12548. this.peerconnection.onaddstream = function (event) {
  12549. self.trace('onaddstream', event.stream.id);
  12550. if (self.onaddstream !== null) {
  12551. self.onaddstream(event);
  12552. }
  12553. };
  12554. this.onremovestream = null;
  12555. this.peerconnection.onremovestream = function (event) {
  12556. self.trace('onremovestream', event.stream.id);
  12557. if (self.onremovestream !== null) {
  12558. self.onremovestream(event);
  12559. }
  12560. };
  12561. this.onsignalingstatechange = null;
  12562. this.peerconnection.onsignalingstatechange = function (event) {
  12563. self.trace('onsignalingstatechange', self.signalingState);
  12564. if (self.onsignalingstatechange !== null) {
  12565. self.onsignalingstatechange(event);
  12566. }
  12567. };
  12568. this.oniceconnectionstatechange = null;
  12569. this.peerconnection.oniceconnectionstatechange = function (event) {
  12570. self.trace('oniceconnectionstatechange', self.iceConnectionState);
  12571. if (self.oniceconnectionstatechange !== null) {
  12572. self.oniceconnectionstatechange(event);
  12573. }
  12574. };
  12575. this.onnegotiationneeded = null;
  12576. this.peerconnection.onnegotiationneeded = function (event) {
  12577. self.trace('onnegotiationneeded');
  12578. if (self.onnegotiationneeded !== null) {
  12579. self.onnegotiationneeded(event);
  12580. }
  12581. };
  12582. self.ondatachannel = null;
  12583. this.peerconnection.ondatachannel = function (event) {
  12584. self.trace('ondatachannel', event);
  12585. if (self.ondatachannel !== null) {
  12586. self.ondatachannel(event);
  12587. }
  12588. };
  12589. if (!navigator.mozGetUserMedia && this.maxstats) {
  12590. this.statsinterval = window.setInterval(function() {
  12591. self.peerconnection.getStats(function(stats) {
  12592. var results = stats.result();
  12593. for (var i = 0; i < results.length; ++i) {
  12594. //console.log(results[i].type, results[i].id, results[i].names())
  12595. var now = new Date();
  12596. results[i].names().forEach(function (name) {
  12597. var id = results[i].id + '-' + name;
  12598. if (!self.stats[id]) {
  12599. self.stats[id] = {
  12600. startTime: now,
  12601. endTime: now,
  12602. values: [],
  12603. times: []
  12604. };
  12605. }
  12606. self.stats[id].values.push(results[i].stat(name));
  12607. self.stats[id].times.push(now.getTime());
  12608. if (self.stats[id].values.length > self.maxstats) {
  12609. self.stats[id].values.shift();
  12610. self.stats[id].times.shift();
  12611. }
  12612. self.stats[id].endTime = now;
  12613. });
  12614. }
  12615. });
  12616. }, 1000);
  12617. }
  12618. };
  12619. dumpSDP = function(description) {
  12620. if (typeof description === 'undefined' || description == null) {
  12621. return '';
  12622. }
  12623. return 'type: ' + description.type + '\r\n' + description.sdp;
  12624. };
  12625. if (TraceablePeerConnection.prototype.__defineGetter__ !== undefined) {
  12626. TraceablePeerConnection.prototype.__defineGetter__('signalingState', function() { return this.peerconnection.signalingState; });
  12627. TraceablePeerConnection.prototype.__defineGetter__('iceConnectionState', function() { return this.peerconnection.iceConnectionState; });
  12628. TraceablePeerConnection.prototype.__defineGetter__('localDescription', function() {
  12629. this.trace('getLocalDescription::preTransform (Plan A)', dumpSDP(this.peerconnection.localDescription));
  12630. // if we're running on FF, transform to Plan B first.
  12631. var desc = this.peerconnection.localDescription;
  12632. if (navigator.mozGetUserMedia) {
  12633. desc = this.interop.toPlanB(desc);
  12634. } else {
  12635. desc = APP.simulcast.reverseTransformLocalDescription(this.peerconnection.localDescription);
  12636. }
  12637. this.trace('getLocalDescription::postTransform (Plan B)', dumpSDP(desc));
  12638. return desc;
  12639. });
  12640. TraceablePeerConnection.prototype.__defineGetter__('remoteDescription', function() {
  12641. this.trace('getRemoteDescription::preTransform (Plan A)', dumpSDP(this.peerconnection.remoteDescription));
  12642. // if we're running on FF, transform to Plan B first.
  12643. var desc = this.peerconnection.remoteDescription;
  12644. if (navigator.mozGetUserMedia) {
  12645. desc = this.interop.toPlanB(desc);
  12646. } else {
  12647. desc = APP.simulcast.reverseTransformRemoteDescription(this.peerconnection.remoteDescription);
  12648. }
  12649. this.trace('getRemoteDescription::postTransform (Plan B)', dumpSDP(desc));
  12650. return desc;
  12651. });
  12652. }
  12653. TraceablePeerConnection.prototype.addStream = function (stream) {
  12654. this.trace('addStream', stream.id);
  12655. APP.simulcast.resetSender();
  12656. try
  12657. {
  12658. this.peerconnection.addStream(stream);
  12659. }
  12660. catch (e)
  12661. {
  12662. console.error(e);
  12663. return;
  12664. }
  12665. };
  12666. TraceablePeerConnection.prototype.removeStream = function (stream, stopStreams) {
  12667. this.trace('removeStream', stream.id);
  12668. APP.simulcast.resetSender();
  12669. if(stopStreams) {
  12670. stream.getAudioTracks().forEach(function (track) {
  12671. track.stop();
  12672. });
  12673. stream.getVideoTracks().forEach(function (track) {
  12674. track.stop();
  12675. });
  12676. }
  12677. this.peerconnection.removeStream(stream);
  12678. };
  12679. TraceablePeerConnection.prototype.createDataChannel = function (label, opts) {
  12680. this.trace('createDataChannel', label, opts);
  12681. return this.peerconnection.createDataChannel(label, opts);
  12682. };
  12683. TraceablePeerConnection.prototype.setLocalDescription = function (description, successCallback, failureCallback) {
  12684. this.trace('setLocalDescription::preTransform (Plan B)', dumpSDP(description));
  12685. // if we're running on FF, transform to Plan A first.
  12686. if (navigator.mozGetUserMedia) {
  12687. description = this.interop.toPlanA(description);
  12688. } else {
  12689. description = APP.simulcast.transformLocalDescription(description);
  12690. }
  12691. this.trace('setLocalDescription::postTransform (Plan A)', dumpSDP(description));
  12692. var self = this;
  12693. this.peerconnection.setLocalDescription(description,
  12694. function () {
  12695. self.trace('setLocalDescriptionOnSuccess');
  12696. successCallback();
  12697. },
  12698. function (err) {
  12699. self.trace('setLocalDescriptionOnFailure', err);
  12700. failureCallback(err);
  12701. }
  12702. );
  12703. /*
  12704. if (this.statsinterval === null && this.maxstats > 0) {
  12705. // start gathering stats
  12706. }
  12707. */
  12708. };
  12709. TraceablePeerConnection.prototype.setRemoteDescription = function (description, successCallback, failureCallback) {
  12710. this.trace('setRemoteDescription::preTransform (Plan B)', dumpSDP(description));
  12711. // if we're running on FF, transform to Plan A first.
  12712. if (navigator.mozGetUserMedia) {
  12713. description = this.interop.toPlanA(description);
  12714. }
  12715. else {
  12716. description = APP.simulcast.transformRemoteDescription(description);
  12717. }
  12718. this.trace('setRemoteDescription::postTransform (Plan A)', dumpSDP(description));
  12719. var self = this;
  12720. this.peerconnection.setRemoteDescription(description,
  12721. function () {
  12722. self.trace('setRemoteDescriptionOnSuccess');
  12723. successCallback();
  12724. },
  12725. function (err) {
  12726. self.trace('setRemoteDescriptionOnFailure', err);
  12727. failureCallback(err);
  12728. }
  12729. );
  12730. /*
  12731. if (this.statsinterval === null && this.maxstats > 0) {
  12732. // start gathering stats
  12733. }
  12734. */
  12735. };
  12736. TraceablePeerConnection.prototype.close = function () {
  12737. this.trace('stop');
  12738. if (this.statsinterval !== null) {
  12739. window.clearInterval(this.statsinterval);
  12740. this.statsinterval = null;
  12741. }
  12742. this.peerconnection.close();
  12743. };
  12744. TraceablePeerConnection.prototype.createOffer = function (successCallback, failureCallback, constraints) {
  12745. var self = this;
  12746. this.trace('createOffer', JSON.stringify(constraints, null, ' '));
  12747. this.peerconnection.createOffer(
  12748. function (offer) {
  12749. self.trace('createOfferOnSuccess::preTransform (Plan A)', dumpSDP(offer));
  12750. // if we're running on FF, transform to Plan B first.
  12751. if (navigator.mozGetUserMedia) {
  12752. offer = self.interop.toPlanB(offer);
  12753. }
  12754. self.trace('createOfferOnSuccess::postTransform (Plan B)', dumpSDP(offer));
  12755. successCallback(offer);
  12756. },
  12757. function(err) {
  12758. self.trace('createOfferOnFailure', err);
  12759. failureCallback(err);
  12760. },
  12761. constraints
  12762. );
  12763. };
  12764. TraceablePeerConnection.prototype.createAnswer = function (successCallback, failureCallback, constraints) {
  12765. var self = this;
  12766. this.trace('createAnswer', JSON.stringify(constraints, null, ' '));
  12767. this.peerconnection.createAnswer(
  12768. function (answer) {
  12769. self.trace('createAnswerOnSuccess::preTransfom (Plan A)', dumpSDP(answer));
  12770. // if we're running on FF, transform to Plan A first.
  12771. if (navigator.mozGetUserMedia) {
  12772. answer = self.interop.toPlanB(answer);
  12773. } else {
  12774. answer = APP.simulcast.transformAnswer(answer);
  12775. }
  12776. self.trace('createAnswerOnSuccess::postTransfom (Plan B)', dumpSDP(answer));
  12777. successCallback(answer);
  12778. },
  12779. function(err) {
  12780. self.trace('createAnswerOnFailure', err);
  12781. failureCallback(err);
  12782. },
  12783. constraints
  12784. );
  12785. };
  12786. TraceablePeerConnection.prototype.addIceCandidate = function (candidate, successCallback, failureCallback) {
  12787. var self = this;
  12788. this.trace('addIceCandidate', JSON.stringify(candidate, null, ' '));
  12789. this.peerconnection.addIceCandidate(candidate);
  12790. /* maybe later
  12791. this.peerconnection.addIceCandidate(candidate,
  12792. function () {
  12793. self.trace('addIceCandidateOnSuccess');
  12794. successCallback();
  12795. },
  12796. function (err) {
  12797. self.trace('addIceCandidateOnFailure', err);
  12798. failureCallback(err);
  12799. }
  12800. );
  12801. */
  12802. };
  12803. TraceablePeerConnection.prototype.getStats = function(callback, errback) {
  12804. if (navigator.mozGetUserMedia) {
  12805. // ignore for now...
  12806. if(!errback)
  12807. errback = function () {
  12808. }
  12809. this.peerconnection.getStats(null,callback,errback);
  12810. } else {
  12811. this.peerconnection.getStats(callback);
  12812. }
  12813. };
  12814. module.exports = TraceablePeerConnection;
  12815. },{"sdp-interop":79}],52:[function(require,module,exports){
  12816. /* global $, $iq, APP, config, connection, UI, messageHandler,
  12817. roomName, sessionTerminated, Strophe, Util */
  12818. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  12819. var Settings = require("../settings/Settings");
  12820. var AuthenticationEvents
  12821. = require("../../service/authentication/AuthenticationEvents");
  12822. /**
  12823. * Contains logic responsible for enabling/disabling functionality available
  12824. * only to moderator users.
  12825. */
  12826. var connection = null;
  12827. var focusUserJid;
  12828. function createExpBackoffTimer(step) {
  12829. var count = 1;
  12830. return function (reset) {
  12831. // Reset call
  12832. if (reset) {
  12833. count = 1;
  12834. return;
  12835. }
  12836. // Calculate next timeout
  12837. var timeout = Math.pow(2, count - 1);
  12838. count += 1;
  12839. return timeout * step;
  12840. };
  12841. }
  12842. var getNextTimeout = createExpBackoffTimer(1000);
  12843. var getNextErrorTimeout = createExpBackoffTimer(1000);
  12844. // External authentication stuff
  12845. var externalAuthEnabled = false;
  12846. // Sip gateway can be enabled by configuring Jigasi host in config.js or
  12847. // it will be enabled automatically if focus detects the component through
  12848. // service discovery.
  12849. var sipGatewayEnabled = config.hosts.call_control !== undefined;
  12850. var eventEmitter = null;
  12851. var Moderator = {
  12852. isModerator: function () {
  12853. return connection && connection.emuc.isModerator();
  12854. },
  12855. isPeerModerator: function (peerJid) {
  12856. return connection &&
  12857. connection.emuc.getMemberRole(peerJid) === 'moderator';
  12858. },
  12859. isExternalAuthEnabled: function () {
  12860. return externalAuthEnabled;
  12861. },
  12862. isSipGatewayEnabled: function () {
  12863. return sipGatewayEnabled;
  12864. },
  12865. setConnection: function (con) {
  12866. connection = con;
  12867. },
  12868. init: function (xmpp, emitter) {
  12869. this.xmppService = xmpp;
  12870. eventEmitter = emitter;
  12871. // Message listener that talks to POPUP window
  12872. function listener(event) {
  12873. if (event.data && event.data.sessionId) {
  12874. if (event.origin !== window.location.origin) {
  12875. console.warn(
  12876. "Ignoring sessionId from different origin: " + event.origin);
  12877. return;
  12878. }
  12879. localStorage.setItem('sessionId', event.data.sessionId);
  12880. // After popup is closed we will authenticate
  12881. }
  12882. }
  12883. // Register
  12884. if (window.addEventListener) {
  12885. window.addEventListener("message", listener, false);
  12886. } else {
  12887. window.attachEvent("onmessage", listener);
  12888. }
  12889. },
  12890. onMucLeft: function (jid) {
  12891. console.info("Someone left is it focus ? " + jid);
  12892. var resource = Strophe.getResourceFromJid(jid);
  12893. if (resource === 'focus' && !this.xmppService.sessionTerminated) {
  12894. console.info(
  12895. "Focus has left the room - leaving conference");
  12896. //hangUp();
  12897. // We'd rather reload to have everything re-initialized
  12898. // FIXME: show some message before reload
  12899. location.reload();
  12900. }
  12901. },
  12902. setFocusUserJid: function (focusJid) {
  12903. if (!focusUserJid) {
  12904. focusUserJid = focusJid;
  12905. console.info("Focus jid set to: " + focusUserJid);
  12906. }
  12907. },
  12908. getFocusUserJid: function () {
  12909. return focusUserJid;
  12910. },
  12911. getFocusComponent: function () {
  12912. // Get focus component address
  12913. var focusComponent = config.hosts.focus;
  12914. // If not specified use default: 'focus.domain'
  12915. if (!focusComponent) {
  12916. focusComponent = 'focus.' + config.hosts.domain;
  12917. }
  12918. return focusComponent;
  12919. },
  12920. createConferenceIq: function (roomName) {
  12921. // Generate create conference IQ
  12922. var elem = $iq({to: Moderator.getFocusComponent(), type: 'set'});
  12923. // Session Id used for authentication
  12924. var sessionId = localStorage.getItem('sessionId');
  12925. var machineUID = Settings.getSettings().uid;
  12926. console.info(
  12927. "Session ID: " + sessionId + " machine UID: " + machineUID);
  12928. elem.c('conference', {
  12929. xmlns: 'http://jitsi.org/protocol/focus',
  12930. room: roomName,
  12931. 'machine-uid': machineUID
  12932. });
  12933. if (sessionId) {
  12934. elem.attrs({ 'session-id': sessionId});
  12935. }
  12936. if (config.hosts.bridge !== undefined) {
  12937. elem.c(
  12938. 'property',
  12939. { name: 'bridge', value: config.hosts.bridge})
  12940. .up();
  12941. }
  12942. // Tell the focus we have Jigasi configured
  12943. if (config.hosts.call_control !== undefined) {
  12944. elem.c(
  12945. 'property',
  12946. { name: 'call_control', value: config.hosts.call_control})
  12947. .up();
  12948. }
  12949. if (config.channelLastN !== undefined) {
  12950. elem.c(
  12951. 'property',
  12952. { name: 'channelLastN', value: config.channelLastN})
  12953. .up();
  12954. }
  12955. if (config.adaptiveLastN !== undefined) {
  12956. elem.c(
  12957. 'property',
  12958. { name: 'adaptiveLastN', value: config.adaptiveLastN})
  12959. .up();
  12960. }
  12961. if (config.adaptiveSimulcast !== undefined) {
  12962. elem.c(
  12963. 'property',
  12964. { name: 'adaptiveSimulcast', value: config.adaptiveSimulcast})
  12965. .up();
  12966. }
  12967. if (config.openSctp !== undefined) {
  12968. elem.c(
  12969. 'property',
  12970. { name: 'openSctp', value: config.openSctp})
  12971. .up();
  12972. }
  12973. if (config.enableFirefoxSupport !== undefined) {
  12974. elem.c(
  12975. 'property',
  12976. { name: 'enableFirefoxHacks',
  12977. value: config.enableFirefoxSupport})
  12978. .up();
  12979. }
  12980. elem.up();
  12981. return elem;
  12982. },
  12983. parseConfigOptions: function (resultIq) {
  12984. Moderator.setFocusUserJid(
  12985. $(resultIq).find('conference').attr('focusjid'));
  12986. var authenticationEnabled
  12987. = $(resultIq).find(
  12988. '>conference>property' +
  12989. '[name=\'authentication\'][value=\'true\']').length > 0;
  12990. console.info("Authentication enabled: " + authenticationEnabled);
  12991. externalAuthEnabled
  12992. = $(resultIq).find(
  12993. '>conference>property' +
  12994. '[name=\'externalAuth\'][value=\'true\']').length > 0;
  12995. console.info('External authentication enabled: ' + externalAuthEnabled);
  12996. if (!externalAuthEnabled) {
  12997. // We expect to receive sessionId in 'internal' authentication mode
  12998. var sessionId
  12999. = $(resultIq).find('conference').attr('session-id');
  13000. if (sessionId) {
  13001. console.info('Received sessionId: ' + sessionId);
  13002. localStorage.setItem('sessionId', sessionId);
  13003. }
  13004. }
  13005. var authIdentity = $(resultIq).find('>conference').attr('identity');
  13006. eventEmitter.emit(AuthenticationEvents.IDENTITY_UPDATED,
  13007. authenticationEnabled, authIdentity);
  13008. // Check if focus has auto-detected Jigasi component(this will be also
  13009. // included if we have passed our host from the config)
  13010. if ($(resultIq).find(
  13011. '>conference>property' +
  13012. '[name=\'sipGatewayEnabled\'][value=\'true\']').length) {
  13013. sipGatewayEnabled = true;
  13014. }
  13015. console.info("Sip gateway enabled: " + sipGatewayEnabled);
  13016. },
  13017. // FIXME: we need to show the fact that we're waiting for the focus
  13018. // to the user(or that focus is not available)
  13019. allocateConferenceFocus: function (roomName, callback) {
  13020. // Try to use focus user JID from the config
  13021. Moderator.setFocusUserJid(config.focusUserJid);
  13022. // Send create conference IQ
  13023. var iq = Moderator.createConferenceIq(roomName);
  13024. var self = this;
  13025. connection.sendIQ(
  13026. iq,
  13027. function (result) {
  13028. // Setup config options
  13029. Moderator.parseConfigOptions(result);
  13030. if ('true' === $(result).find('conference').attr('ready')) {
  13031. // Reset both timers
  13032. getNextTimeout(true);
  13033. getNextErrorTimeout(true);
  13034. // Exec callback
  13035. callback();
  13036. } else {
  13037. var waitMs = getNextTimeout();
  13038. console.info("Waiting for the focus... " + waitMs);
  13039. // Reset error timeout
  13040. getNextErrorTimeout(true);
  13041. window.setTimeout(
  13042. function () {
  13043. Moderator.allocateConferenceFocus(
  13044. roomName, callback);
  13045. }, waitMs);
  13046. }
  13047. },
  13048. function (error) {
  13049. // Invalid session ? remove and try again
  13050. // without session ID to get a new one
  13051. var invalidSession
  13052. = $(error).find('>error>session-invalid').length;
  13053. if (invalidSession) {
  13054. console.info("Session expired! - removing");
  13055. localStorage.removeItem("sessionId");
  13056. }
  13057. if ($(error).find('>error>graceful-shutdown').length) {
  13058. eventEmitter.emit(XMPPEvents.GRACEFUL_SHUTDOWN);
  13059. return;
  13060. }
  13061. // Check for error returned by the reservation system
  13062. var reservationErr = $(error).find('>error>reservation-error');
  13063. if (reservationErr.length) {
  13064. // Trigger error event
  13065. var errorCode = reservationErr.attr('error-code');
  13066. var errorMsg;
  13067. if ($(error).find('>error>text')) {
  13068. errorMsg = $(error).find('>error>text').text();
  13069. }
  13070. eventEmitter.emit(
  13071. XMPPEvents.RESERVATION_ERROR, errorCode, errorMsg);
  13072. return;
  13073. }
  13074. // Not authorized to create new room
  13075. if ($(error).find('>error>not-authorized').length) {
  13076. console.warn("Unauthorized to start the conference", error);
  13077. var toDomain
  13078. = Strophe.getDomainFromJid(error.getAttribute('to'));
  13079. if (toDomain === config.hosts.anonymousdomain) {
  13080. // we are connected with anonymous domain and
  13081. // only non anonymous users can create rooms
  13082. // we must authorize the user
  13083. self.xmppService.promptLogin();
  13084. } else {
  13085. // External authentication mode
  13086. eventEmitter.emit(
  13087. XMPPEvents.AUTHENTICATION_REQUIRED,
  13088. function () {
  13089. Moderator.allocateConferenceFocus(
  13090. roomName, callback);
  13091. });
  13092. }
  13093. return;
  13094. }
  13095. var waitMs = getNextErrorTimeout();
  13096. console.error("Focus error, retry after " + waitMs, error);
  13097. // Show message
  13098. var focusComponent = Moderator.getFocusComponent();
  13099. var retrySec = waitMs / 1000;
  13100. // FIXME: message is duplicated ?
  13101. // Do not show in case of session invalid
  13102. // which means just a retry
  13103. if (!invalidSession) {
  13104. APP.UI.messageHandler.notify(
  13105. null, "notify.focus",
  13106. 'disconnected', "notify.focusFail",
  13107. {component: focusComponent, ms: retrySec});
  13108. }
  13109. // Reset response timeout
  13110. getNextTimeout(true);
  13111. window.setTimeout(
  13112. function () {
  13113. Moderator.allocateConferenceFocus(roomName, callback);
  13114. }, waitMs);
  13115. }
  13116. );
  13117. },
  13118. getLoginUrl: function (roomName, urlCallback) {
  13119. var iq = $iq({to: Moderator.getFocusComponent(), type: 'get'});
  13120. iq.c('login-url', {
  13121. xmlns: 'http://jitsi.org/protocol/focus',
  13122. room: roomName,
  13123. 'machine-uid': Settings.getSettings().uid
  13124. });
  13125. connection.sendIQ(
  13126. iq,
  13127. function (result) {
  13128. var url = $(result).find('login-url').attr('url');
  13129. url = url = decodeURIComponent(url);
  13130. if (url) {
  13131. console.info("Got auth url: " + url);
  13132. urlCallback(url);
  13133. } else {
  13134. console.error(
  13135. "Failed to get auth url from the focus", result);
  13136. }
  13137. },
  13138. function (error) {
  13139. console.error("Get auth url error", error);
  13140. }
  13141. );
  13142. },
  13143. getPopupLoginUrl: function (roomName, urlCallback) {
  13144. var iq = $iq({to: Moderator.getFocusComponent(), type: 'get'});
  13145. iq.c('login-url', {
  13146. xmlns: 'http://jitsi.org/protocol/focus',
  13147. room: roomName,
  13148. 'machine-uid': Settings.getSettings().uid,
  13149. popup: true
  13150. });
  13151. connection.sendIQ(
  13152. iq,
  13153. function (result) {
  13154. var url = $(result).find('login-url').attr('url');
  13155. url = url = decodeURIComponent(url);
  13156. if (url) {
  13157. console.info("Got POPUP auth url: " + url);
  13158. urlCallback(url);
  13159. } else {
  13160. console.error(
  13161. "Failed to get POPUP auth url from the focus", result);
  13162. }
  13163. },
  13164. function (error) {
  13165. console.error('Get POPUP auth url error', error);
  13166. }
  13167. );
  13168. },
  13169. logout: function (callback) {
  13170. var iq = $iq({to: Moderator.getFocusComponent(), type: 'set'});
  13171. var sessionId = localStorage.getItem('sessionId');
  13172. if (!sessionId) {
  13173. callback();
  13174. return;
  13175. }
  13176. iq.c('logout', {
  13177. xmlns: 'http://jitsi.org/protocol/focus',
  13178. 'session-id': sessionId
  13179. });
  13180. connection.sendIQ(
  13181. iq,
  13182. function (result) {
  13183. var logoutUrl = $(result).find('logout').attr('logout-url');
  13184. if (logoutUrl) {
  13185. logoutUrl = decodeURIComponent(logoutUrl);
  13186. }
  13187. console.info("Log out OK, url: " + logoutUrl, result);
  13188. localStorage.removeItem('sessionId');
  13189. callback(logoutUrl);
  13190. },
  13191. function (error) {
  13192. console.error("Logout error", error);
  13193. }
  13194. );
  13195. }
  13196. };
  13197. module.exports = Moderator;
  13198. },{"../../service/authentication/AuthenticationEvents":92,"../../service/xmpp/XMPPEvents":96,"../settings/Settings":37}],53:[function(require,module,exports){
  13199. /* global $, $iq, config, connection, focusMucJid, messageHandler, Moderator,
  13200. Toolbar, Util */
  13201. var Moderator = require("./moderator");
  13202. var recordingToken = null;
  13203. var recordingEnabled;
  13204. /**
  13205. * Whether to use a jirecon component for recording, or use the videobridge
  13206. * through COLIBRI.
  13207. */
  13208. var useJirecon = (typeof config.hosts.jirecon != "undefined");
  13209. /**
  13210. * The ID of the jirecon recording session. Jirecon generates it when we
  13211. * initially start recording, and it needs to be used in subsequent requests
  13212. * to jirecon.
  13213. */
  13214. var jireconRid = null;
  13215. function setRecordingToken(token) {
  13216. recordingToken = token;
  13217. }
  13218. function setRecording(state, token, callback, connection) {
  13219. if (useJirecon){
  13220. setRecordingJirecon(state, token, callback, connection);
  13221. } else {
  13222. setRecordingColibri(state, token, callback, connection);
  13223. }
  13224. }
  13225. function setRecordingJirecon(state, token, callback, connection) {
  13226. if (state == recordingEnabled){
  13227. return;
  13228. }
  13229. var iq = $iq({to: config.hosts.jirecon, type: 'set'})
  13230. .c('recording', {xmlns: 'http://jitsi.org/protocol/jirecon',
  13231. action: state ? 'start' : 'stop',
  13232. mucjid: connection.emuc.roomjid});
  13233. if (!state){
  13234. iq.attrs({rid: jireconRid});
  13235. }
  13236. console.log('Start recording');
  13237. connection.sendIQ(
  13238. iq,
  13239. function (result) {
  13240. // TODO wait for an IQ with the real status, since this is
  13241. // provisional?
  13242. jireconRid = $(result).find('recording').attr('rid');
  13243. console.log('Recording ' + (state ? 'started' : 'stopped') +
  13244. '(jirecon)' + result);
  13245. recordingEnabled = state;
  13246. if (!state){
  13247. jireconRid = null;
  13248. }
  13249. callback(state);
  13250. },
  13251. function (error) {
  13252. console.log('Failed to start recording, error: ', error);
  13253. callback(recordingEnabled);
  13254. });
  13255. }
  13256. // Sends a COLIBRI message which enables or disables (according to 'state')
  13257. // the recording on the bridge. Waits for the result IQ and calls 'callback'
  13258. // with the new recording state, according to the IQ.
  13259. function setRecordingColibri(state, token, callback, connection) {
  13260. var elem = $iq({to: connection.emuc.focusMucJid, type: 'set'});
  13261. elem.c('conference', {
  13262. xmlns: 'http://jitsi.org/protocol/colibri'
  13263. });
  13264. elem.c('recording', {state: state, token: token});
  13265. connection.sendIQ(elem,
  13266. function (result) {
  13267. console.log('Set recording "', state, '". Result:', result);
  13268. var recordingElem = $(result).find('>conference>recording');
  13269. var newState = ('true' === recordingElem.attr('state'));
  13270. recordingEnabled = newState;
  13271. callback(newState);
  13272. },
  13273. function (error) {
  13274. console.warn(error);
  13275. callback(recordingEnabled);
  13276. }
  13277. );
  13278. }
  13279. var Recording = {
  13280. toggleRecording: function (tokenEmptyCallback,
  13281. startingCallback, startedCallback, connection) {
  13282. if (!Moderator.isModerator()) {
  13283. console.log(
  13284. 'non-focus, or conference not yet organized:' +
  13285. ' not enabling recording');
  13286. return;
  13287. }
  13288. var self = this;
  13289. // Jirecon does not (currently) support a token.
  13290. if (!recordingToken && !useJirecon) {
  13291. tokenEmptyCallback(function (value) {
  13292. setRecordingToken(value);
  13293. self.toggleRecording(tokenEmptyCallback,
  13294. startingCallback, startedCallback, connection);
  13295. });
  13296. return;
  13297. }
  13298. var oldState = recordingEnabled;
  13299. startingCallback(!oldState);
  13300. setRecording(!oldState,
  13301. recordingToken,
  13302. function (state) {
  13303. console.log("New recording state: ", state);
  13304. if (state === oldState) {
  13305. // FIXME: new focus:
  13306. // this will not work when moderator changes
  13307. // during active session. Then it will assume that
  13308. // recording status has changed to true, but it might have
  13309. // been already true(and we only received actual status from
  13310. // the focus).
  13311. //
  13312. // SO we start with status null, so that it is initialized
  13313. // here and will fail only after second click, so if invalid
  13314. // token was used we have to press the button twice before
  13315. // current status will be fetched and token will be reset.
  13316. //
  13317. // Reliable way would be to return authentication error.
  13318. // Or status update when moderator connects.
  13319. // Or we have to stop recording session when current
  13320. // moderator leaves the room.
  13321. // Failed to change, reset the token because it might
  13322. // have been wrong
  13323. setRecordingToken(null);
  13324. }
  13325. startedCallback(state);
  13326. },
  13327. connection
  13328. );
  13329. }
  13330. }
  13331. module.exports = Recording;
  13332. },{"./moderator":52}],54:[function(require,module,exports){
  13333. /* jshint -W117 */
  13334. /* a simple MUC connection plugin
  13335. * can only handle a single MUC room
  13336. */
  13337. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  13338. var Moderator = require("./moderator");
  13339. var JingleSession = require("./JingleSession");
  13340. var bridgeIsDown = false;
  13341. module.exports = function(XMPP, eventEmitter) {
  13342. Strophe.addConnectionPlugin('emuc', {
  13343. connection: null,
  13344. roomjid: null,
  13345. myroomjid: null,
  13346. members: {},
  13347. list_members: [], // so we can elect a new focus
  13348. presMap: {},
  13349. preziMap: {},
  13350. joined: false,
  13351. isOwner: false,
  13352. role: null,
  13353. focusMucJid: null,
  13354. ssrc2jid: {},
  13355. init: function (conn) {
  13356. this.connection = conn;
  13357. },
  13358. initPresenceMap: function (myroomjid) {
  13359. this.presMap['to'] = myroomjid;
  13360. this.presMap['xns'] = 'http://jabber.org/protocol/muc';
  13361. },
  13362. doJoin: function (jid, password) {
  13363. this.myroomjid = jid;
  13364. console.info("Joined MUC as " + this.myroomjid);
  13365. this.initPresenceMap(this.myroomjid);
  13366. if (!this.roomjid) {
  13367. this.roomjid = Strophe.getBareJidFromJid(jid);
  13368. // add handlers (just once)
  13369. this.connection.addHandler(this.onPresence.bind(this), null, 'presence', null, null, this.roomjid, {matchBare: true});
  13370. this.connection.addHandler(this.onPresenceUnavailable.bind(this), null, 'presence', 'unavailable', null, this.roomjid, {matchBare: true});
  13371. this.connection.addHandler(this.onPresenceError.bind(this), null, 'presence', 'error', null, this.roomjid, {matchBare: true});
  13372. this.connection.addHandler(this.onMessage.bind(this), null, 'message', null, null, this.roomjid, {matchBare: true});
  13373. }
  13374. if (password !== undefined) {
  13375. this.presMap['password'] = password;
  13376. }
  13377. this.sendPresence();
  13378. },
  13379. doLeave: function () {
  13380. console.log("do leave", this.myroomjid);
  13381. var pres = $pres({to: this.myroomjid, type: 'unavailable' });
  13382. this.presMap.length = 0;
  13383. this.connection.send(pres);
  13384. },
  13385. createNonAnonymousRoom: function () {
  13386. // http://xmpp.org/extensions/xep-0045.html#createroom-reserved
  13387. var getForm = $iq({type: 'get', to: this.roomjid})
  13388. .c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'})
  13389. .c('x', {xmlns: 'jabber:x:data', type: 'submit'});
  13390. var self = this;
  13391. this.connection.sendIQ(getForm, function (form) {
  13392. if (!$(form).find(
  13393. '>query>x[xmlns="jabber:x:data"]' +
  13394. '>field[var="muc#roomconfig_whois"]').length) {
  13395. console.error('non-anonymous rooms not supported');
  13396. return;
  13397. }
  13398. var formSubmit = $iq({to: this.roomjid, type: 'set'})
  13399. .c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'});
  13400. formSubmit.c('x', {xmlns: 'jabber:x:data', type: 'submit'});
  13401. formSubmit.c('field', {'var': 'FORM_TYPE'})
  13402. .c('value')
  13403. .t('http://jabber.org/protocol/muc#roomconfig').up().up();
  13404. formSubmit.c('field', {'var': 'muc#roomconfig_whois'})
  13405. .c('value').t('anyone').up().up();
  13406. self.connection.sendIQ(formSubmit);
  13407. }, function (error) {
  13408. console.error("Error getting room configuration form");
  13409. });
  13410. },
  13411. onPresence: function (pres) {
  13412. var from = pres.getAttribute('from');
  13413. // What is this for? A workaround for something?
  13414. if (pres.getAttribute('type')) {
  13415. return true;
  13416. }
  13417. // Parse etherpad tag.
  13418. var etherpad = $(pres).find('>etherpad');
  13419. if (etherpad.length) {
  13420. if (config.etherpad_base && !Moderator.isModerator()) {
  13421. eventEmitter.emit(XMPPEvents.ETHERPAD, etherpad.text());
  13422. }
  13423. }
  13424. // Parse prezi tag.
  13425. var presentation = $(pres).find('>prezi');
  13426. if (presentation.length) {
  13427. var url = presentation.attr('url');
  13428. var current = presentation.find('>current').text();
  13429. console.log('presentation info received from', from, url);
  13430. if (this.preziMap[from] == null) {
  13431. this.preziMap[from] = url;
  13432. $(document).trigger('presentationadded.muc', [from, url, current]);
  13433. }
  13434. else {
  13435. $(document).trigger('gotoslide.muc', [from, url, current]);
  13436. }
  13437. }
  13438. else if (this.preziMap[from] != null) {
  13439. var url = this.preziMap[from];
  13440. delete this.preziMap[from];
  13441. $(document).trigger('presentationremoved.muc', [from, url]);
  13442. }
  13443. // Parse audio info tag.
  13444. var audioMuted = $(pres).find('>audiomuted');
  13445. if (audioMuted.length) {
  13446. $(document).trigger('audiomuted.muc', [from, audioMuted.text()]);
  13447. }
  13448. // Parse video info tag.
  13449. var videoMuted = $(pres).find('>videomuted');
  13450. if (videoMuted.length) {
  13451. $(document).trigger('videomuted.muc', [from, videoMuted.text()]);
  13452. }
  13453. var stats = $(pres).find('>stats');
  13454. if (stats.length) {
  13455. var statsObj = {};
  13456. Strophe.forEachChild(stats[0], "stat", function (el) {
  13457. statsObj[el.getAttribute("name")] = el.getAttribute("value");
  13458. });
  13459. eventEmitter.emit(XMPPEvents.REMOTE_STATS, from, statsObj);
  13460. }
  13461. // Parse status.
  13462. if ($(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>status[code="201"]').length) {
  13463. this.isOwner = true;
  13464. this.createNonAnonymousRoom();
  13465. }
  13466. // Parse roles.
  13467. var member = {};
  13468. member.show = $(pres).find('>show').text();
  13469. member.status = $(pres).find('>status').text();
  13470. var tmp = $(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>item');
  13471. member.affiliation = tmp.attr('affiliation');
  13472. member.role = tmp.attr('role');
  13473. // Focus recognition
  13474. member.jid = tmp.attr('jid');
  13475. member.isFocus = false;
  13476. if (member.jid
  13477. && member.jid.indexOf(Moderator.getFocusUserJid() + "/") == 0) {
  13478. member.isFocus = true;
  13479. }
  13480. var nicktag = $(pres).find('>nick[xmlns="http://jabber.org/protocol/nick"]');
  13481. member.displayName = (nicktag.length > 0 ? nicktag.html() : null);
  13482. if (from == this.myroomjid) {
  13483. if (member.affiliation == 'owner') this.isOwner = true;
  13484. if (this.role !== member.role) {
  13485. this.role = member.role;
  13486. eventEmitter.emit(XMPPEvents.LOCALROLE_CHANGED,
  13487. from, member, pres, Moderator.isModerator());
  13488. }
  13489. if (!this.joined) {
  13490. this.joined = true;
  13491. eventEmitter.emit(XMPPEvents.MUC_JOINED, from, member);
  13492. this.list_members.push(from);
  13493. }
  13494. } else if (this.members[from] === undefined) {
  13495. // new participant
  13496. this.members[from] = member;
  13497. this.list_members.push(from);
  13498. console.log('entered', from, member);
  13499. if (member.isFocus) {
  13500. this.focusMucJid = from;
  13501. console.info("Ignore focus: " + from + ", real JID: " + member.jid);
  13502. }
  13503. else {
  13504. var id = $(pres).find('>userID').text();
  13505. var email = $(pres).find('>email');
  13506. if (email.length > 0) {
  13507. id = email.text();
  13508. }
  13509. eventEmitter.emit(XMPPEvents.MUC_ENTER, from, id, member.displayName);
  13510. }
  13511. } else {
  13512. // Presence update for existing participant
  13513. // Watch role change:
  13514. if (this.members[from].role != member.role) {
  13515. this.members[from].role = member.role;
  13516. eventEmitter.emit(XMPPEvents.MUC_ROLE_CHANGED,
  13517. member.role, member.displayName);
  13518. }
  13519. }
  13520. // Always trigger presence to update bindings
  13521. this.parsePresence(from, member, pres);
  13522. // Trigger status message update
  13523. if (member.status) {
  13524. eventEmitter.emit(XMPPEvents.PRESENCE_STATUS, from, member);
  13525. }
  13526. return true;
  13527. },
  13528. onPresenceUnavailable: function (pres) {
  13529. var from = pres.getAttribute('from');
  13530. // room destroyed ?
  13531. if ($(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]' +
  13532. '>destroy').length) {
  13533. var reason;
  13534. var reasonSelect = $(pres).find(
  13535. '>x[xmlns="http://jabber.org/protocol/muc#user"]' +
  13536. '>destroy>reason');
  13537. if (reasonSelect.length) {
  13538. reason = reasonSelect.text();
  13539. }
  13540. XMPP.disposeConference(false);
  13541. eventEmitter.emit(XMPPEvents.MUC_DESTROYED, reason);
  13542. return true;
  13543. }
  13544. // Status code 110 indicates that this notification is "self-presence".
  13545. if (!$(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>status[code="110"]').length) {
  13546. delete this.members[from];
  13547. this.list_members.splice(this.list_members.indexOf(from), 1);
  13548. this.onParticipantLeft(from);
  13549. }
  13550. // If the status code is 110 this means we're leaving and we would like
  13551. // to remove everyone else from our view, so we trigger the event.
  13552. else if (this.list_members.length > 1) {
  13553. for (var i = 0; i < this.list_members.length; i++) {
  13554. var member = this.list_members[i];
  13555. delete this.members[i];
  13556. this.list_members.splice(i, 1);
  13557. this.onParticipantLeft(member);
  13558. }
  13559. }
  13560. if ($(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>status[code="307"]').length) {
  13561. $(document).trigger('kicked.muc', [from]);
  13562. if (this.myroomjid === from) {
  13563. XMPP.disposeConference(false);
  13564. eventEmitter.emit(XMPPEvents.KICKED);
  13565. }
  13566. }
  13567. return true;
  13568. },
  13569. onPresenceError: function (pres) {
  13570. var from = pres.getAttribute('from');
  13571. if ($(pres).find('>error[type="auth"]>not-authorized[xmlns="urn:ietf:params:xml:ns:xmpp-stanzas"]').length) {
  13572. console.log('on password required', from);
  13573. var self = this;
  13574. eventEmitter.emit(XMPPEvents.PASSWORD_REQUIRED, function (value) {
  13575. self.doJoin(from, value);
  13576. });
  13577. } else if ($(pres).find(
  13578. '>error[type="cancel"]>not-allowed[xmlns="urn:ietf:params:xml:ns:xmpp-stanzas"]').length) {
  13579. var toDomain = Strophe.getDomainFromJid(pres.getAttribute('to'));
  13580. if (toDomain === config.hosts.anonymousdomain) {
  13581. // enter the room by replying with 'not-authorized'. This would
  13582. // result in reconnection from authorized domain.
  13583. // We're either missing Jicofo/Prosody config for anonymous
  13584. // domains or something is wrong.
  13585. // XMPP.promptLogin();
  13586. APP.UI.messageHandler.openReportDialog(null,
  13587. "dialog.joinError", pres);
  13588. } else {
  13589. console.warn('onPresError ', pres);
  13590. APP.UI.messageHandler.openReportDialog(null,
  13591. "dialog.connectError",
  13592. pres);
  13593. }
  13594. } else {
  13595. console.warn('onPresError ', pres);
  13596. APP.UI.messageHandler.openReportDialog(null,
  13597. "dialog.connectError",
  13598. pres);
  13599. }
  13600. return true;
  13601. },
  13602. sendMessage: function (body, nickname) {
  13603. var msg = $msg({to: this.roomjid, type: 'groupchat'});
  13604. msg.c('body', body).up();
  13605. if (nickname) {
  13606. msg.c('nick', {xmlns: 'http://jabber.org/protocol/nick'}).t(nickname).up().up();
  13607. }
  13608. this.connection.send(msg);
  13609. eventEmitter.emit(XMPPEvents.SENDING_CHAT_MESSAGE, body);
  13610. },
  13611. setSubject: function (subject) {
  13612. var msg = $msg({to: this.roomjid, type: 'groupchat'});
  13613. msg.c('subject', subject);
  13614. this.connection.send(msg);
  13615. console.log("topic changed to " + subject);
  13616. },
  13617. onMessage: function (msg) {
  13618. // FIXME: this is a hack. but jingle on muc makes nickchanges hard
  13619. var from = msg.getAttribute('from');
  13620. var nick =
  13621. $(msg).find('>nick[xmlns="http://jabber.org/protocol/nick"]')
  13622. .text() ||
  13623. Strophe.getResourceFromJid(from);
  13624. var txt = $(msg).find('>body').text();
  13625. var type = msg.getAttribute("type");
  13626. if (type == "error") {
  13627. eventEmitter.emit(XMPPEvents.CHAT_ERROR_RECEIVED,
  13628. $(msg).find('>text').text(), txt);
  13629. return true;
  13630. }
  13631. var subject = $(msg).find('>subject');
  13632. if (subject.length) {
  13633. var subjectText = subject.text();
  13634. if (subjectText || subjectText == "") {
  13635. eventEmitter.emit(XMPPEvents.SUBJECT_CHANGED, subjectText);
  13636. console.log("Subject is changed to " + subjectText);
  13637. }
  13638. }
  13639. if (txt) {
  13640. console.log('chat', nick, txt);
  13641. eventEmitter.emit(XMPPEvents.MESSAGE_RECEIVED,
  13642. from, nick, txt, this.myroomjid);
  13643. }
  13644. return true;
  13645. },
  13646. lockRoom: function (key, onSuccess, onError, onNotSupported) {
  13647. //http://xmpp.org/extensions/xep-0045.html#roomconfig
  13648. var ob = this;
  13649. this.connection.sendIQ($iq({to: this.roomjid, type: 'get'}).c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'}),
  13650. function (res) {
  13651. if ($(res).find('>query>x[xmlns="jabber:x:data"]>field[var="muc#roomconfig_roomsecret"]').length) {
  13652. var formsubmit = $iq({to: ob.roomjid, type: 'set'}).c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'});
  13653. formsubmit.c('x', {xmlns: 'jabber:x:data', type: 'submit'});
  13654. formsubmit.c('field', {'var': 'FORM_TYPE'}).c('value').t('http://jabber.org/protocol/muc#roomconfig').up().up();
  13655. formsubmit.c('field', {'var': 'muc#roomconfig_roomsecret'}).c('value').t(key).up().up();
  13656. // Fixes a bug in prosody 0.9.+ https://code.google.com/p/lxmppd/issues/detail?id=373
  13657. formsubmit.c('field', {'var': 'muc#roomconfig_whois'}).c('value').t('anyone').up().up();
  13658. // FIXME: is muc#roomconfig_passwordprotectedroom required?
  13659. ob.connection.sendIQ(formsubmit,
  13660. onSuccess,
  13661. onError);
  13662. } else {
  13663. onNotSupported();
  13664. }
  13665. }, onError);
  13666. },
  13667. kick: function (jid) {
  13668. var kickIQ = $iq({to: this.roomjid, type: 'set'})
  13669. .c('query', {xmlns: 'http://jabber.org/protocol/muc#admin'})
  13670. .c('item', {nick: Strophe.getResourceFromJid(jid), role: 'none'})
  13671. .c('reason').t('You have been kicked.').up().up().up();
  13672. this.connection.sendIQ(
  13673. kickIQ,
  13674. function (result) {
  13675. console.log('Kick participant with jid: ', jid, result);
  13676. },
  13677. function (error) {
  13678. console.log('Kick participant error: ', error);
  13679. });
  13680. },
  13681. sendPresence: function () {
  13682. var pres = $pres({to: this.presMap['to'] });
  13683. pres.c('x', {xmlns: this.presMap['xns']});
  13684. if (this.presMap['password']) {
  13685. pres.c('password').t(this.presMap['password']).up();
  13686. }
  13687. pres.up();
  13688. // Send XEP-0115 'c' stanza that contains our capabilities info
  13689. if (this.connection.caps) {
  13690. this.connection.caps.node = config.clientNode;
  13691. pres.c('c', this.connection.caps.generateCapsAttrs()).up();
  13692. }
  13693. pres.c('user-agent', {xmlns: 'http://jitsi.org/jitmeet/user-agent'})
  13694. .t(navigator.userAgent).up();
  13695. if (this.presMap['bridgeIsDown']) {
  13696. pres.c('bridgeIsDown').up();
  13697. }
  13698. if (this.presMap['email']) {
  13699. pres.c('email').t(this.presMap['email']).up();
  13700. }
  13701. if (this.presMap['userId']) {
  13702. pres.c('userId').t(this.presMap['userId']).up();
  13703. }
  13704. if (this.presMap['displayName']) {
  13705. // XEP-0172
  13706. pres.c('nick', {xmlns: 'http://jabber.org/protocol/nick'})
  13707. .t(this.presMap['displayName']).up();
  13708. }
  13709. if (this.presMap['audions']) {
  13710. pres.c('audiomuted', {xmlns: this.presMap['audions']})
  13711. .t(this.presMap['audiomuted']).up();
  13712. }
  13713. if (this.presMap['videons']) {
  13714. pres.c('videomuted', {xmlns: this.presMap['videons']})
  13715. .t(this.presMap['videomuted']).up();
  13716. }
  13717. if (this.presMap['statsns']) {
  13718. var stats = pres.c('stats', {xmlns: this.presMap['statsns']});
  13719. for (var stat in this.presMap["stats"])
  13720. if (this.presMap["stats"][stat] != null)
  13721. stats.c("stat", {name: stat, value: this.presMap["stats"][stat]}).up();
  13722. pres.up();
  13723. }
  13724. if (this.presMap['prezins']) {
  13725. pres.c('prezi',
  13726. {xmlns: this.presMap['prezins'],
  13727. 'url': this.presMap['preziurl']})
  13728. .c('current').t(this.presMap['prezicurrent']).up().up();
  13729. }
  13730. if (this.presMap['etherpadns']) {
  13731. pres.c('etherpad', {xmlns: this.presMap['etherpadns']})
  13732. .t(this.presMap['etherpadname']).up();
  13733. }
  13734. if (this.presMap['medians']) {
  13735. pres.c('media', {xmlns: this.presMap['medians']});
  13736. var sourceNumber = 0;
  13737. Object.keys(this.presMap).forEach(function (key) {
  13738. if (key.indexOf('source') >= 0) {
  13739. sourceNumber++;
  13740. }
  13741. });
  13742. if (sourceNumber > 0)
  13743. for (var i = 1; i <= sourceNumber / 3; i++) {
  13744. pres.c('source',
  13745. {type: this.presMap['source' + i + '_type'],
  13746. ssrc: this.presMap['source' + i + '_ssrc'],
  13747. direction: this.presMap['source' + i + '_direction']
  13748. || 'sendrecv' }
  13749. ).up();
  13750. }
  13751. }
  13752. pres.up();
  13753. this.connection.send(pres);
  13754. },
  13755. addDisplayNameToPresence: function (displayName) {
  13756. this.presMap['displayName'] = displayName;
  13757. },
  13758. addMediaToPresence: function (sourceNumber, mtype, ssrcs, direction) {
  13759. if (!this.presMap['medians'])
  13760. this.presMap['medians'] = 'http://estos.de/ns/mjs';
  13761. this.presMap['source' + sourceNumber + '_type'] = mtype;
  13762. this.presMap['source' + sourceNumber + '_ssrc'] = ssrcs;
  13763. this.presMap['source' + sourceNumber + '_direction'] = direction;
  13764. },
  13765. clearPresenceMedia: function () {
  13766. var self = this;
  13767. Object.keys(this.presMap).forEach(function (key) {
  13768. if (key.indexOf('source') != -1) {
  13769. delete self.presMap[key];
  13770. }
  13771. });
  13772. },
  13773. addPreziToPresence: function (url, currentSlide) {
  13774. this.presMap['prezins'] = 'http://jitsi.org/jitmeet/prezi';
  13775. this.presMap['preziurl'] = url;
  13776. this.presMap['prezicurrent'] = currentSlide;
  13777. },
  13778. removePreziFromPresence: function () {
  13779. delete this.presMap['prezins'];
  13780. delete this.presMap['preziurl'];
  13781. delete this.presMap['prezicurrent'];
  13782. },
  13783. addCurrentSlideToPresence: function (currentSlide) {
  13784. this.presMap['prezicurrent'] = currentSlide;
  13785. },
  13786. getPrezi: function (roomjid) {
  13787. return this.preziMap[roomjid];
  13788. },
  13789. addEtherpadToPresence: function (etherpadName) {
  13790. this.presMap['etherpadns'] = 'http://jitsi.org/jitmeet/etherpad';
  13791. this.presMap['etherpadname'] = etherpadName;
  13792. },
  13793. addAudioInfoToPresence: function (isMuted) {
  13794. this.presMap['audions'] = 'http://jitsi.org/jitmeet/audio';
  13795. this.presMap['audiomuted'] = isMuted.toString();
  13796. },
  13797. addVideoInfoToPresence: function (isMuted) {
  13798. this.presMap['videons'] = 'http://jitsi.org/jitmeet/video';
  13799. this.presMap['videomuted'] = isMuted.toString();
  13800. },
  13801. addConnectionInfoToPresence: function (stats) {
  13802. this.presMap['statsns'] = 'http://jitsi.org/jitmeet/stats';
  13803. this.presMap['stats'] = stats;
  13804. },
  13805. findJidFromResource: function (resourceJid) {
  13806. if (resourceJid &&
  13807. resourceJid === Strophe.getResourceFromJid(this.myroomjid)) {
  13808. return this.myroomjid;
  13809. }
  13810. var peerJid = null;
  13811. Object.keys(this.members).some(function (jid) {
  13812. peerJid = jid;
  13813. return Strophe.getResourceFromJid(jid) === resourceJid;
  13814. });
  13815. return peerJid;
  13816. },
  13817. addBridgeIsDownToPresence: function () {
  13818. this.presMap['bridgeIsDown'] = true;
  13819. },
  13820. addEmailToPresence: function (email) {
  13821. this.presMap['email'] = email;
  13822. },
  13823. addUserIdToPresence: function (userId) {
  13824. this.presMap['userId'] = userId;
  13825. },
  13826. isModerator: function () {
  13827. return this.role === 'moderator';
  13828. },
  13829. getMemberRole: function (peerJid) {
  13830. if (this.members[peerJid]) {
  13831. return this.members[peerJid].role;
  13832. }
  13833. return null;
  13834. },
  13835. onParticipantLeft: function (jid) {
  13836. eventEmitter.emit(XMPPEvents.MUC_LEFT, jid);
  13837. this.connection.jingle.terminateByJid(jid);
  13838. if (this.getPrezi(jid)) {
  13839. $(document).trigger('presentationremoved.muc',
  13840. [jid, this.getPrezi(jid)]);
  13841. }
  13842. Moderator.onMucLeft(jid);
  13843. },
  13844. parsePresence: function (from, memeber, pres) {
  13845. if($(pres).find(">bridgeIsDown").length > 0 && !bridgeIsDown) {
  13846. bridgeIsDown = true;
  13847. eventEmitter.emit(XMPPEvents.BRIDGE_DOWN);
  13848. }
  13849. if(memeber.isFocus)
  13850. return;
  13851. var self = this;
  13852. // Remove old ssrcs coming from the jid
  13853. Object.keys(this.ssrc2jid).forEach(function (ssrc) {
  13854. if (self.ssrc2jid[ssrc] == from) {
  13855. delete self.ssrc2jid[ssrc];
  13856. }
  13857. });
  13858. var changedStreams = [];
  13859. $(pres).find('>media[xmlns="http://estos.de/ns/mjs"]>source').each(function (idx, ssrc) {
  13860. //console.log(jid, 'assoc ssrc', ssrc.getAttribute('type'), ssrc.getAttribute('ssrc'));
  13861. var ssrcV = ssrc.getAttribute('ssrc');
  13862. self.ssrc2jid[ssrcV] = from;
  13863. JingleSession.notReceivedSSRCs.push(ssrcV);
  13864. var type = ssrc.getAttribute('type');
  13865. var direction = ssrc.getAttribute('direction');
  13866. changedStreams.push({type: type, direction: direction});
  13867. });
  13868. eventEmitter.emit(XMPPEvents.CHANGED_STREAMS, from, changedStreams);
  13869. var displayName = !config.displayJids
  13870. ? memeber.displayName : Strophe.getResourceFromJid(from);
  13871. if (displayName && displayName.length > 0)
  13872. {
  13873. eventEmitter.emit(XMPPEvents.DISPLAY_NAME_CHANGED, from, displayName);
  13874. }
  13875. var id = $(pres).find('>userID').text();
  13876. var email = $(pres).find('>email');
  13877. if(email.length > 0) {
  13878. id = email.text();
  13879. }
  13880. eventEmitter.emit(XMPPEvents.USER_ID_CHANGED, from, id);
  13881. }
  13882. });
  13883. };
  13884. },{"../../service/xmpp/XMPPEvents":96,"./JingleSession":47,"./moderator":52}],55:[function(require,module,exports){
  13885. /* jshint -W117 */
  13886. var JingleSession = require("./JingleSession");
  13887. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  13888. module.exports = function(XMPP, eventEmitter)
  13889. {
  13890. function CallIncomingJingle(sid, connection) {
  13891. var sess = connection.jingle.sessions[sid];
  13892. // TODO: do we check activecall == null?
  13893. connection.jingle.activecall = sess;
  13894. eventEmitter.emit(XMPPEvents.CALL_INCOMING, sess);
  13895. // TODO: check affiliation and/or role
  13896. console.log('emuc data for', sess.peerjid, connection.emuc.members[sess.peerjid]);
  13897. sess.usedrip = true; // not-so-naive trickle ice
  13898. sess.sendAnswer();
  13899. sess.accept();
  13900. };
  13901. Strophe.addConnectionPlugin('jingle', {
  13902. connection: null,
  13903. sessions: {},
  13904. jid2session: {},
  13905. ice_config: {iceServers: []},
  13906. pc_constraints: {},
  13907. activecall: null,
  13908. media_constraints: {
  13909. mandatory: {
  13910. 'OfferToReceiveAudio': true,
  13911. 'OfferToReceiveVideo': true
  13912. }
  13913. // MozDontOfferDataChannel: true when this is firefox
  13914. },
  13915. init: function (conn) {
  13916. this.connection = conn;
  13917. if (this.connection.disco) {
  13918. // http://xmpp.org/extensions/xep-0167.html#support
  13919. // http://xmpp.org/extensions/xep-0176.html#support
  13920. this.connection.disco.addFeature('urn:xmpp:jingle:1');
  13921. this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:1');
  13922. this.connection.disco.addFeature('urn:xmpp:jingle:transports:ice-udp:1');
  13923. this.connection.disco.addFeature('urn:xmpp:jingle:transports:dtls-sctp:1');
  13924. this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:audio');
  13925. this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:video');
  13926. // this is dealt with by SDP O/A so we don't need to annouce this
  13927. //this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:rtcp-fb:0'); // XEP-0293
  13928. //this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:rtp-hdrext:0'); // XEP-0294
  13929. if (config.useRtcpMux) {
  13930. this.connection.disco.addFeature('urn:ietf:rfc:5761'); // rtcp-mux
  13931. }
  13932. if (config.useBundle) {
  13933. this.connection.disco.addFeature('urn:ietf:rfc:5888'); // a=group, e.g. bundle
  13934. }
  13935. //this.connection.disco.addFeature('urn:ietf:rfc:5576'); // a=ssrc
  13936. }
  13937. this.connection.addHandler(this.onJingle.bind(this), 'urn:xmpp:jingle:1', 'iq', 'set', null, null);
  13938. },
  13939. onJingle: function (iq) {
  13940. var sid = $(iq).find('jingle').attr('sid');
  13941. var action = $(iq).find('jingle').attr('action');
  13942. var fromJid = iq.getAttribute('from');
  13943. // send ack first
  13944. var ack = $iq({type: 'result',
  13945. to: fromJid,
  13946. id: iq.getAttribute('id')
  13947. });
  13948. console.log('on jingle ' + action + ' from ' + fromJid, iq);
  13949. var sess = this.sessions[sid];
  13950. if ('session-initiate' != action) {
  13951. if (sess === null) {
  13952. ack.type = 'error';
  13953. ack.c('error', {type: 'cancel'})
  13954. .c('item-not-found', {xmlns: 'urn:ietf:params:xml:ns:xmpp-stanzas'}).up()
  13955. .c('unknown-session', {xmlns: 'urn:xmpp:jingle:errors:1'});
  13956. this.connection.send(ack);
  13957. return true;
  13958. }
  13959. // compare from to sess.peerjid (bare jid comparison for later compat with message-mode)
  13960. // local jid is not checked
  13961. if (Strophe.getBareJidFromJid(fromJid) != Strophe.getBareJidFromJid(sess.peerjid)) {
  13962. console.warn('jid mismatch for session id', sid, fromJid, sess.peerjid);
  13963. ack.type = 'error';
  13964. ack.c('error', {type: 'cancel'})
  13965. .c('item-not-found', {xmlns: 'urn:ietf:params:xml:ns:xmpp-stanzas'}).up()
  13966. .c('unknown-session', {xmlns: 'urn:xmpp:jingle:errors:1'});
  13967. this.connection.send(ack);
  13968. return true;
  13969. }
  13970. } else if (sess !== undefined) {
  13971. // existing session with same session id
  13972. // this might be out-of-order if the sess.peerjid is the same as from
  13973. ack.type = 'error';
  13974. ack.c('error', {type: 'cancel'})
  13975. .c('service-unavailable', {xmlns: 'urn:ietf:params:xml:ns:xmpp-stanzas'}).up();
  13976. console.warn('duplicate session id', sid);
  13977. this.connection.send(ack);
  13978. return true;
  13979. }
  13980. // FIXME: check for a defined action
  13981. this.connection.send(ack);
  13982. // see http://xmpp.org/extensions/xep-0166.html#concepts-session
  13983. switch (action) {
  13984. case 'session-initiate':
  13985. sess = new JingleSession(
  13986. $(iq).attr('to'), $(iq).find('jingle').attr('sid'),
  13987. this.connection, XMPP);
  13988. // configure session
  13989. sess.media_constraints = this.media_constraints;
  13990. sess.pc_constraints = this.pc_constraints;
  13991. sess.ice_config = this.ice_config;
  13992. sess.initiate(fromJid, false);
  13993. // FIXME: setRemoteDescription should only be done when this call is to be accepted
  13994. sess.setRemoteDescription($(iq).find('>jingle'), 'offer');
  13995. this.sessions[sess.sid] = sess;
  13996. this.jid2session[sess.peerjid] = sess;
  13997. // the callback should either
  13998. // .sendAnswer and .accept
  13999. // or .sendTerminate -- not necessarily synchronus
  14000. CallIncomingJingle(sess.sid, this.connection);
  14001. break;
  14002. case 'session-accept':
  14003. sess.setRemoteDescription($(iq).find('>jingle'), 'answer');
  14004. sess.accept();
  14005. $(document).trigger('callaccepted.jingle', [sess.sid]);
  14006. break;
  14007. case 'session-terminate':
  14008. // If this is not the focus sending the terminate, we have
  14009. // nothing more to do here.
  14010. if (Object.keys(this.sessions).length < 1
  14011. || !(this.sessions[Object.keys(this.sessions)[0]]
  14012. instanceof JingleSession))
  14013. {
  14014. break;
  14015. }
  14016. console.log('terminating...', sess.sid);
  14017. sess.terminate();
  14018. this.terminate(sess.sid);
  14019. if ($(iq).find('>jingle>reason').length) {
  14020. $(document).trigger('callterminated.jingle', [
  14021. sess.sid,
  14022. sess.peerjid,
  14023. $(iq).find('>jingle>reason>:first')[0].tagName,
  14024. $(iq).find('>jingle>reason>text').text()
  14025. ]);
  14026. } else {
  14027. $(document).trigger('callterminated.jingle',
  14028. [sess.sid, sess.peerjid]);
  14029. }
  14030. break;
  14031. case 'transport-info':
  14032. sess.addIceCandidate($(iq).find('>jingle>content'));
  14033. break;
  14034. case 'session-info':
  14035. var affected;
  14036. if ($(iq).find('>jingle>ringing[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').length) {
  14037. $(document).trigger('ringing.jingle', [sess.sid]);
  14038. } else if ($(iq).find('>jingle>mute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').length) {
  14039. affected = $(iq).find('>jingle>mute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').attr('name');
  14040. $(document).trigger('mute.jingle', [sess.sid, affected]);
  14041. } else if ($(iq).find('>jingle>unmute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').length) {
  14042. affected = $(iq).find('>jingle>unmute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').attr('name');
  14043. $(document).trigger('unmute.jingle', [sess.sid, affected]);
  14044. }
  14045. break;
  14046. case 'addsource': // FIXME: proprietary, un-jingleish
  14047. case 'source-add': // FIXME: proprietary
  14048. sess.addSource($(iq).find('>jingle>content'), fromJid);
  14049. break;
  14050. case 'removesource': // FIXME: proprietary, un-jingleish
  14051. case 'source-remove': // FIXME: proprietary
  14052. sess.removeSource($(iq).find('>jingle>content'), fromJid);
  14053. break;
  14054. default:
  14055. console.warn('jingle action not implemented', action);
  14056. break;
  14057. }
  14058. return true;
  14059. },
  14060. initiate: function (peerjid, myjid) { // initiate a new jinglesession to peerjid
  14061. var sess = new JingleSession(myjid || this.connection.jid,
  14062. Math.random().toString(36).substr(2, 12), // random string
  14063. this.connection, XMPP);
  14064. // configure session
  14065. sess.media_constraints = this.media_constraints;
  14066. sess.pc_constraints = this.pc_constraints;
  14067. sess.ice_config = this.ice_config;
  14068. sess.initiate(peerjid, true);
  14069. this.sessions[sess.sid] = sess;
  14070. this.jid2session[sess.peerjid] = sess;
  14071. sess.sendOffer();
  14072. return sess;
  14073. },
  14074. terminate: function (sid, reason, text) { // terminate by sessionid (or all sessions)
  14075. if (sid === null || sid === undefined) {
  14076. for (sid in this.sessions) {
  14077. if (this.sessions[sid].state != 'ended') {
  14078. this.sessions[sid].sendTerminate(reason || (!this.sessions[sid].active()) ? 'cancel' : null, text);
  14079. this.sessions[sid].terminate();
  14080. }
  14081. delete this.jid2session[this.sessions[sid].peerjid];
  14082. delete this.sessions[sid];
  14083. }
  14084. } else if (this.sessions.hasOwnProperty(sid)) {
  14085. if (this.sessions[sid].state != 'ended') {
  14086. this.sessions[sid].sendTerminate(reason || (!this.sessions[sid].active()) ? 'cancel' : null, text);
  14087. this.sessions[sid].terminate();
  14088. }
  14089. delete this.jid2session[this.sessions[sid].peerjid];
  14090. delete this.sessions[sid];
  14091. }
  14092. },
  14093. // Used to terminate a session when an unavailable presence is received.
  14094. terminateByJid: function (jid) {
  14095. if (this.jid2session.hasOwnProperty(jid)) {
  14096. var sess = this.jid2session[jid];
  14097. if (sess) {
  14098. sess.terminate();
  14099. console.log('peer went away silently', jid);
  14100. delete this.sessions[sess.sid];
  14101. delete this.jid2session[jid];
  14102. $(document).trigger('callterminated.jingle',
  14103. [sess.sid, jid], 'gone');
  14104. }
  14105. }
  14106. },
  14107. terminateRemoteByJid: function (jid, reason) {
  14108. if (this.jid2session.hasOwnProperty(jid)) {
  14109. var sess = this.jid2session[jid];
  14110. if (sess) {
  14111. sess.sendTerminate(reason || (!sess.active()) ? 'kick' : null);
  14112. sess.terminate();
  14113. console.log('terminate peer with jid', sess.sid, jid);
  14114. delete this.sessions[sess.sid];
  14115. delete this.jid2session[jid];
  14116. $(document).trigger('callterminated.jingle',
  14117. [sess.sid, jid, 'kicked']);
  14118. }
  14119. }
  14120. },
  14121. getStunAndTurnCredentials: function () {
  14122. // get stun and turn configuration from server via xep-0215
  14123. // uses time-limited credentials as described in
  14124. // http://tools.ietf.org/html/draft-uberti-behave-turn-rest-00
  14125. //
  14126. // see https://code.google.com/p/prosody-modules/source/browse/mod_turncredentials/mod_turncredentials.lua
  14127. // for a prosody module which implements this
  14128. //
  14129. // currently, this doesn't work with updateIce and therefore credentials with a long
  14130. // validity have to be fetched before creating the peerconnection
  14131. // TODO: implement refresh via updateIce as described in
  14132. // https://code.google.com/p/webrtc/issues/detail?id=1650
  14133. var self = this;
  14134. this.connection.sendIQ(
  14135. $iq({type: 'get', to: this.connection.domain})
  14136. .c('services', {xmlns: 'urn:xmpp:extdisco:1'}).c('service', {host: 'turn.' + this.connection.domain}),
  14137. function (res) {
  14138. var iceservers = [];
  14139. $(res).find('>services>service').each(function (idx, el) {
  14140. el = $(el);
  14141. var dict = {};
  14142. var type = el.attr('type');
  14143. switch (type) {
  14144. case 'stun':
  14145. dict.url = 'stun:' + el.attr('host');
  14146. if (el.attr('port')) {
  14147. dict.url += ':' + el.attr('port');
  14148. }
  14149. iceservers.push(dict);
  14150. break;
  14151. case 'turn':
  14152. case 'turns':
  14153. dict.url = type + ':';
  14154. if (el.attr('username')) { // https://code.google.com/p/webrtc/issues/detail?id=1508
  14155. if (navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./) && parseInt(navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./)[2], 10) < 28) {
  14156. dict.url += el.attr('username') + '@';
  14157. } else {
  14158. dict.username = el.attr('username'); // only works in M28
  14159. }
  14160. }
  14161. dict.url += el.attr('host');
  14162. if (el.attr('port') && el.attr('port') != '3478') {
  14163. dict.url += ':' + el.attr('port');
  14164. }
  14165. if (el.attr('transport') && el.attr('transport') != 'udp') {
  14166. dict.url += '?transport=' + el.attr('transport');
  14167. }
  14168. if (el.attr('password')) {
  14169. dict.credential = el.attr('password');
  14170. }
  14171. iceservers.push(dict);
  14172. break;
  14173. }
  14174. });
  14175. self.ice_config.iceServers = iceservers;
  14176. },
  14177. function (err) {
  14178. console.warn('getting turn credentials failed', err);
  14179. console.warn('is mod_turncredentials or similar installed?');
  14180. }
  14181. );
  14182. // implement push?
  14183. },
  14184. /**
  14185. * Populates the log data
  14186. */
  14187. populateData: function () {
  14188. var data = {};
  14189. Object.keys(this.sessions).forEach(function (sid) {
  14190. var session = this.sessions[sid];
  14191. if (session.peerconnection && session.peerconnection.updateLog) {
  14192. // FIXME: should probably be a .dump call
  14193. data["jingle_" + session.sid] = {
  14194. updateLog: session.peerconnection.updateLog,
  14195. stats: session.peerconnection.stats,
  14196. url: window.location.href
  14197. };
  14198. }
  14199. });
  14200. return data;
  14201. }
  14202. });
  14203. };
  14204. },{"../../service/xmpp/XMPPEvents":96,"./JingleSession":47}],56:[function(require,module,exports){
  14205. /* global Strophe */
  14206. module.exports = function () {
  14207. Strophe.addConnectionPlugin('logger', {
  14208. // logs raw stanzas and makes them available for download as JSON
  14209. connection: null,
  14210. log: [],
  14211. init: function (conn) {
  14212. this.connection = conn;
  14213. this.connection.rawInput = this.log_incoming.bind(this);
  14214. this.connection.rawOutput = this.log_outgoing.bind(this);
  14215. },
  14216. log_incoming: function (stanza) {
  14217. this.log.push([new Date().getTime(), 'incoming', stanza]);
  14218. },
  14219. log_outgoing: function (stanza) {
  14220. this.log.push([new Date().getTime(), 'outgoing', stanza]);
  14221. }
  14222. });
  14223. };
  14224. },{}],57:[function(require,module,exports){
  14225. /* global $, $iq, config, connection, focusMucJid, forceMuted,
  14226. setAudioMuted, Strophe */
  14227. /**
  14228. * Moderate connection plugin.
  14229. */
  14230. module.exports = function (XMPP) {
  14231. Strophe.addConnectionPlugin('moderate', {
  14232. connection: null,
  14233. init: function (conn) {
  14234. this.connection = conn;
  14235. this.connection.addHandler(this.onMute.bind(this),
  14236. 'http://jitsi.org/jitmeet/audio',
  14237. 'iq',
  14238. 'set',
  14239. null,
  14240. null);
  14241. },
  14242. setMute: function (jid, mute) {
  14243. console.info("set mute", mute);
  14244. var iqToFocus = $iq({to: this.connection.emuc.focusMucJid, type: 'set'})
  14245. .c('mute', {
  14246. xmlns: 'http://jitsi.org/jitmeet/audio',
  14247. jid: jid
  14248. })
  14249. .t(mute.toString())
  14250. .up();
  14251. this.connection.sendIQ(
  14252. iqToFocus,
  14253. function (result) {
  14254. console.log('set mute', result);
  14255. },
  14256. function (error) {
  14257. console.log('set mute error', error);
  14258. });
  14259. },
  14260. onMute: function (iq) {
  14261. var from = iq.getAttribute('from');
  14262. if (from !== this.connection.emuc.focusMucJid) {
  14263. console.warn("Ignored mute from non focus peer");
  14264. return false;
  14265. }
  14266. var mute = $(iq).find('mute');
  14267. if (mute.length) {
  14268. var doMuteAudio = mute.text() === "true";
  14269. APP.UI.setAudioMuted(doMuteAudio);
  14270. XMPP.forceMuted = doMuteAudio;
  14271. }
  14272. return true;
  14273. },
  14274. eject: function (jid) {
  14275. // We're not the focus, so can't terminate
  14276. //connection.jingle.terminateRemoteByJid(jid, 'kick');
  14277. this.connection.emuc.kick(jid);
  14278. }
  14279. });
  14280. }
  14281. },{}],58:[function(require,module,exports){
  14282. /* jshint -W117 */
  14283. module.exports = function() {
  14284. Strophe.addConnectionPlugin('rayo',
  14285. {
  14286. RAYO_XMLNS: 'urn:xmpp:rayo:1',
  14287. connection: null,
  14288. init: function (conn) {
  14289. this.connection = conn;
  14290. if (this.connection.disco) {
  14291. this.connection.disco.addFeature('urn:xmpp:rayo:client:1');
  14292. }
  14293. this.connection.addHandler(
  14294. this.onRayo.bind(this), this.RAYO_XMLNS, 'iq', 'set', null, null);
  14295. },
  14296. onRayo: function (iq) {
  14297. console.info("Rayo IQ", iq);
  14298. },
  14299. dial: function (to, from, roomName, roomPass) {
  14300. var self = this;
  14301. var req = $iq(
  14302. {
  14303. type: 'set',
  14304. to: this.connection.emuc.focusMucJid
  14305. }
  14306. );
  14307. req.c('dial',
  14308. {
  14309. xmlns: this.RAYO_XMLNS,
  14310. to: to,
  14311. from: from
  14312. });
  14313. req.c('header',
  14314. {
  14315. name: 'JvbRoomName',
  14316. value: roomName
  14317. }).up();
  14318. if (roomPass !== null && roomPass.length) {
  14319. req.c('header',
  14320. {
  14321. name: 'JvbRoomPassword',
  14322. value: roomPass
  14323. }).up();
  14324. }
  14325. this.connection.sendIQ(
  14326. req,
  14327. function (result) {
  14328. console.info('Dial result ', result);
  14329. var resource = $(result).find('ref').attr('uri');
  14330. this.call_resource = resource.substr('xmpp:'.length);
  14331. console.info(
  14332. "Received call resource: " + this.call_resource);
  14333. },
  14334. function (error) {
  14335. console.info('Dial error ', error);
  14336. }
  14337. );
  14338. },
  14339. hang_up: function () {
  14340. if (!this.call_resource) {
  14341. console.warn("No call in progress");
  14342. return;
  14343. }
  14344. var self = this;
  14345. var req = $iq(
  14346. {
  14347. type: 'set',
  14348. to: this.call_resource
  14349. }
  14350. );
  14351. req.c('hangup',
  14352. {
  14353. xmlns: this.RAYO_XMLNS
  14354. });
  14355. this.connection.sendIQ(
  14356. req,
  14357. function (result) {
  14358. console.info('Hangup result ', result);
  14359. self.call_resource = null;
  14360. },
  14361. function (error) {
  14362. console.info('Hangup error ', error);
  14363. self.call_resource = null;
  14364. }
  14365. );
  14366. }
  14367. }
  14368. );
  14369. };
  14370. },{}],59:[function(require,module,exports){
  14371. /**
  14372. * Strophe logger implementation. Logs from level WARN and above.
  14373. */
  14374. module.exports = function () {
  14375. Strophe.log = function (level, msg) {
  14376. switch (level) {
  14377. case Strophe.LogLevel.WARN:
  14378. console.warn("Strophe: " + msg);
  14379. break;
  14380. case Strophe.LogLevel.ERROR:
  14381. case Strophe.LogLevel.FATAL:
  14382. console.error("Strophe: " + msg);
  14383. break;
  14384. }
  14385. };
  14386. Strophe.getStatusString = function (status) {
  14387. switch (status) {
  14388. case Strophe.Status.ERROR:
  14389. return "ERROR";
  14390. case Strophe.Status.CONNECTING:
  14391. return "CONNECTING";
  14392. case Strophe.Status.CONNFAIL:
  14393. return "CONNFAIL";
  14394. case Strophe.Status.AUTHENTICATING:
  14395. return "AUTHENTICATING";
  14396. case Strophe.Status.AUTHFAIL:
  14397. return "AUTHFAIL";
  14398. case Strophe.Status.CONNECTED:
  14399. return "CONNECTED";
  14400. case Strophe.Status.DISCONNECTED:
  14401. return "DISCONNECTED";
  14402. case Strophe.Status.DISCONNECTING:
  14403. return "DISCONNECTING";
  14404. case Strophe.Status.ATTACHED:
  14405. return "ATTACHED";
  14406. default:
  14407. return "unknown";
  14408. }
  14409. };
  14410. };
  14411. },{}],60:[function(require,module,exports){
  14412. var Moderator = require("./moderator");
  14413. var EventEmitter = require("events");
  14414. var Recording = require("./recording");
  14415. var SDP = require("./SDP");
  14416. var Pako = require("pako");
  14417. var StreamEventTypes = require("../../service/RTC/StreamEventTypes");
  14418. var UIEvents = require("../../service/UI/UIEvents");
  14419. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  14420. var eventEmitter = new EventEmitter();
  14421. var connection = null;
  14422. var authenticatedUser = false;
  14423. function connect(jid, password, uiCredentials) {
  14424. var bosh
  14425. = (uiCredentials && uiCredentials.bosh? uiCredentials.bosh : null)
  14426. || config.bosh || '/http-bind';
  14427. connection = new Strophe.Connection(bosh);
  14428. Moderator.setConnection(connection);
  14429. if(uiCredentials) {
  14430. var email = uiCredentials.email;
  14431. var displayName = uiCredentials.displayName;
  14432. if (email) {
  14433. connection.emuc.addEmailToPresence(email);
  14434. } else {
  14435. connection.emuc.addUserIdToPresence(uiCredentials.uid);
  14436. }
  14437. if (displayName) {
  14438. connection.emuc.addDisplayNameToPresence(displayName);
  14439. }
  14440. }
  14441. if (connection.disco) {
  14442. // for chrome, add multistream cap
  14443. }
  14444. connection.jingle.pc_constraints = APP.RTC.getPCConstraints();
  14445. if (config.useIPv6) {
  14446. // https://code.google.com/p/webrtc/issues/detail?id=2828
  14447. if (!connection.jingle.pc_constraints.optional)
  14448. connection.jingle.pc_constraints.optional = [];
  14449. connection.jingle.pc_constraints.optional.push({googIPv6: true});
  14450. }
  14451. if(!password)
  14452. password = uiCredentials.password;
  14453. var anonymousConnectionFailed = false;
  14454. connection.connect(jid, password, function (status, msg) {
  14455. console.log('Strophe status changed to',
  14456. Strophe.getStatusString(status));
  14457. if (status === Strophe.Status.CONNECTED) {
  14458. if (config.useStunTurn) {
  14459. connection.jingle.getStunAndTurnCredentials();
  14460. }
  14461. APP.UI.disableConnect();
  14462. console.info("My Jabber ID: " + connection.jid);
  14463. if(password)
  14464. authenticatedUser = true;
  14465. maybeDoJoin();
  14466. } else if (status === Strophe.Status.CONNFAIL) {
  14467. if(msg === 'x-strophe-bad-non-anon-jid') {
  14468. anonymousConnectionFailed = true;
  14469. }
  14470. } else if (status === Strophe.Status.DISCONNECTED) {
  14471. if(anonymousConnectionFailed) {
  14472. // prompt user for username and password
  14473. XMPP.promptLogin();
  14474. }
  14475. } else if (status === Strophe.Status.AUTHFAIL) {
  14476. // wrong password or username, prompt user
  14477. XMPP.promptLogin();
  14478. }
  14479. });
  14480. }
  14481. function maybeDoJoin() {
  14482. if (connection && connection.connected &&
  14483. Strophe.getResourceFromJid(connection.jid)
  14484. && (APP.RTC.localAudio || APP.RTC.localVideo)) {
  14485. // .connected is true while connecting?
  14486. doJoin();
  14487. }
  14488. }
  14489. function doJoin() {
  14490. var roomName = APP.UI.generateRoomName();
  14491. Moderator.allocateConferenceFocus(
  14492. roomName, APP.UI.checkForNicknameAndJoin);
  14493. }
  14494. function initStrophePlugins()
  14495. {
  14496. require("./strophe.emuc")(XMPP, eventEmitter);
  14497. require("./strophe.jingle")(XMPP, eventEmitter);
  14498. require("./strophe.moderate")(XMPP);
  14499. require("./strophe.util")();
  14500. require("./strophe.rayo")();
  14501. require("./strophe.logger")();
  14502. }
  14503. function registerListeners() {
  14504. APP.RTC.addStreamListener(maybeDoJoin,
  14505. StreamEventTypes.EVENT_TYPE_LOCAL_CREATED);
  14506. APP.UI.addListener(UIEvents.NICKNAME_CHANGED, function (nickname) {
  14507. XMPP.addToPresence("displayName", nickname);
  14508. });
  14509. }
  14510. function setupEvents() {
  14511. $(window).bind('beforeunload', function () {
  14512. if (connection && connection.connected) {
  14513. // ensure signout
  14514. $.ajax({
  14515. type: 'POST',
  14516. url: config.bosh,
  14517. async: false,
  14518. cache: false,
  14519. contentType: 'application/xml',
  14520. data: "<body rid='" + (connection.rid || connection._proto.rid)
  14521. + "' xmlns='http://jabber.org/protocol/httpbind' sid='"
  14522. + (connection.sid || connection._proto.sid)
  14523. + "' type='terminate'>" +
  14524. "<presence xmlns='jabber:client' type='unavailable'/>" +
  14525. "</body>",
  14526. success: function (data) {
  14527. console.log('signed out');
  14528. console.log(data);
  14529. },
  14530. error: function (XMLHttpRequest, textStatus, errorThrown) {
  14531. console.log('signout error',
  14532. textStatus + ' (' + errorThrown + ')');
  14533. }
  14534. });
  14535. }
  14536. XMPP.disposeConference(true);
  14537. });
  14538. }
  14539. var XMPP = {
  14540. sessionTerminated: false,
  14541. /**
  14542. * Remembers if we were muted by the focus.
  14543. * @type {boolean}
  14544. */
  14545. forceMuted: false,
  14546. start: function (uiCredentials) {
  14547. setupEvents();
  14548. initStrophePlugins();
  14549. registerListeners();
  14550. Moderator.init(this, eventEmitter);
  14551. var configDomain = config.hosts.anonymousdomain || config.hosts.domain;
  14552. // Force authenticated domain if room is appended with '?login=true'
  14553. if (config.hosts.anonymousdomain &&
  14554. window.location.search.indexOf("login=true") !== -1) {
  14555. configDomain = config.hosts.domain;
  14556. }
  14557. var jid = uiCredentials.jid || configDomain || window.location.hostname;
  14558. connect(jid, null, uiCredentials);
  14559. },
  14560. promptLogin: function () {
  14561. APP.UI.showLoginPopup(connect);
  14562. },
  14563. joinRoom: function(roomName, useNicks, nick)
  14564. {
  14565. var roomjid;
  14566. roomjid = roomName;
  14567. if (useNicks) {
  14568. if (nick) {
  14569. roomjid += '/' + nick;
  14570. } else {
  14571. roomjid += '/' + Strophe.getNodeFromJid(connection.jid);
  14572. }
  14573. } else {
  14574. var tmpJid = Strophe.getNodeFromJid(connection.jid);
  14575. if(!authenticatedUser)
  14576. tmpJid = tmpJid.substr(0, 8);
  14577. roomjid += '/' + tmpJid;
  14578. }
  14579. connection.emuc.doJoin(roomjid);
  14580. },
  14581. myJid: function () {
  14582. if(!connection)
  14583. return null;
  14584. return connection.emuc.myroomjid;
  14585. },
  14586. myResource: function () {
  14587. if(!connection || ! connection.emuc.myroomjid)
  14588. return null;
  14589. return Strophe.getResourceFromJid(connection.emuc.myroomjid);
  14590. },
  14591. disposeConference: function (onUnload) {
  14592. eventEmitter.emit(XMPPEvents.DISPOSE_CONFERENCE, onUnload);
  14593. var handler = connection.jingle.activecall;
  14594. if (handler && handler.peerconnection) {
  14595. // FIXME: probably removing streams is not required and close() should
  14596. // be enough
  14597. if (APP.RTC.localAudio) {
  14598. handler.peerconnection.removeStream(APP.RTC.localAudio.getOriginalStream(), onUnload);
  14599. }
  14600. if (APP.RTC.localVideo) {
  14601. handler.peerconnection.removeStream(APP.RTC.localVideo.getOriginalStream(), onUnload);
  14602. }
  14603. handler.peerconnection.close();
  14604. }
  14605. connection.jingle.activecall = null;
  14606. if(!onUnload)
  14607. {
  14608. this.sessionTerminated = true;
  14609. connection.emuc.doLeave();
  14610. }
  14611. },
  14612. addListener: function(type, listener)
  14613. {
  14614. eventEmitter.on(type, listener);
  14615. },
  14616. removeListener: function (type, listener) {
  14617. eventEmitter.removeListener(type, listener);
  14618. },
  14619. allocateConferenceFocus: function(roomName, callback) {
  14620. Moderator.allocateConferenceFocus(roomName, callback);
  14621. },
  14622. getLoginUrl: function (roomName, callback) {
  14623. Moderator.getLoginUrl(roomName, callback);
  14624. },
  14625. getPopupLoginUrl: function (roomName, callback) {
  14626. Moderator.getPopupLoginUrl(roomName, callback);
  14627. },
  14628. isModerator: function () {
  14629. return Moderator.isModerator();
  14630. },
  14631. isSipGatewayEnabled: function () {
  14632. return Moderator.isSipGatewayEnabled();
  14633. },
  14634. isExternalAuthEnabled: function () {
  14635. return Moderator.isExternalAuthEnabled();
  14636. },
  14637. switchStreams: function (stream, oldStream, callback) {
  14638. if (connection && connection.jingle.activecall) {
  14639. // FIXME: will block switchInProgress on true value in case of exception
  14640. connection.jingle.activecall.switchStreams(stream, oldStream, callback);
  14641. } else {
  14642. // We are done immediately
  14643. console.warn("No conference handler or conference not started yet");
  14644. callback();
  14645. }
  14646. },
  14647. setVideoMute: function (mute, callback, options) {
  14648. if(connection && APP.RTC.localVideo && connection.jingle.activecall)
  14649. {
  14650. connection.jingle.activecall.setVideoMute(mute, callback, options);
  14651. }
  14652. },
  14653. setAudioMute: function (mute, callback) {
  14654. if (!(connection && APP.RTC.localAudio)) {
  14655. return false;
  14656. }
  14657. if (this.forceMuted && !mute) {
  14658. console.info("Asking focus for unmute");
  14659. connection.moderate.setMute(connection.emuc.myroomjid, mute);
  14660. // FIXME: wait for result before resetting muted status
  14661. this.forceMuted = false;
  14662. }
  14663. if (mute == APP.RTC.localAudio.isMuted()) {
  14664. // Nothing to do
  14665. return true;
  14666. }
  14667. // It is not clear what is the right way to handle multiple tracks.
  14668. // So at least make sure that they are all muted or all unmuted and
  14669. // that we send presence just once.
  14670. APP.RTC.localAudio.mute();
  14671. // isMuted is the opposite of audioEnabled
  14672. connection.emuc.addAudioInfoToPresence(mute);
  14673. connection.emuc.sendPresence();
  14674. callback();
  14675. return true;
  14676. },
  14677. // Really mute video, i.e. dont even send black frames
  14678. muteVideo: function (pc, unmute) {
  14679. // FIXME: this probably needs another of those lovely state safeguards...
  14680. // which checks for iceconn == connected and sigstate == stable
  14681. pc.setRemoteDescription(pc.remoteDescription,
  14682. function () {
  14683. pc.createAnswer(
  14684. function (answer) {
  14685. var sdp = new SDP(answer.sdp);
  14686. if (sdp.media.length > 1) {
  14687. if (unmute)
  14688. sdp.media[1] = sdp.media[1].replace('a=recvonly', 'a=sendrecv');
  14689. else
  14690. sdp.media[1] = sdp.media[1].replace('a=sendrecv', 'a=recvonly');
  14691. sdp.raw = sdp.session + sdp.media.join('');
  14692. answer.sdp = sdp.raw;
  14693. }
  14694. pc.setLocalDescription(answer,
  14695. function () {
  14696. console.log('mute SLD ok');
  14697. },
  14698. function (error) {
  14699. console.log('mute SLD error');
  14700. APP.UI.messageHandler.showError("dialog.error",
  14701. "dialog.SLDFailure");
  14702. }
  14703. );
  14704. },
  14705. function (error) {
  14706. console.log(error);
  14707. APP.UI.messageHandler.showError();
  14708. }
  14709. );
  14710. },
  14711. function (error) {
  14712. console.log('muteVideo SRD error');
  14713. APP.UI.messageHandler.showError("dialog.error",
  14714. "dialog.SRDFailure");
  14715. }
  14716. );
  14717. },
  14718. toggleRecording: function (tokenEmptyCallback,
  14719. startingCallback, startedCallback) {
  14720. Recording.toggleRecording(tokenEmptyCallback,
  14721. startingCallback, startedCallback, connection);
  14722. },
  14723. addToPresence: function (name, value, dontSend) {
  14724. switch (name)
  14725. {
  14726. case "displayName":
  14727. connection.emuc.addDisplayNameToPresence(value);
  14728. break;
  14729. case "etherpad":
  14730. connection.emuc.addEtherpadToPresence(value);
  14731. break;
  14732. case "prezi":
  14733. connection.emuc.addPreziToPresence(value, 0);
  14734. break;
  14735. case "preziSlide":
  14736. connection.emuc.addCurrentSlideToPresence(value);
  14737. break;
  14738. case "connectionQuality":
  14739. connection.emuc.addConnectionInfoToPresence(value);
  14740. break;
  14741. case "email":
  14742. connection.emuc.addEmailToPresence(value);
  14743. default :
  14744. console.log("Unknown tag for presence.");
  14745. return;
  14746. }
  14747. if(!dontSend)
  14748. connection.emuc.sendPresence();
  14749. },
  14750. /**
  14751. * Sends 'data' as a log message to the focus. Returns true iff a message
  14752. * was sent.
  14753. * @param data
  14754. * @returns {boolean} true iff a message was sent.
  14755. */
  14756. sendLogs: function (data) {
  14757. if(!connection.emuc.focusMucJid)
  14758. return false;
  14759. var deflate = true;
  14760. var content = JSON.stringify(data);
  14761. if (deflate) {
  14762. content = String.fromCharCode.apply(null, Pako.deflateRaw(content));
  14763. }
  14764. content = Base64.encode(content);
  14765. // XEP-0337-ish
  14766. var message = $msg({to: connection.emuc.focusMucJid, type: 'normal'});
  14767. message.c('log', { xmlns: 'urn:xmpp:eventlog',
  14768. id: 'PeerConnectionStats'});
  14769. message.c('message').t(content).up();
  14770. if (deflate) {
  14771. message.c('tag', {name: "deflated", value: "true"}).up();
  14772. }
  14773. message.up();
  14774. connection.send(message);
  14775. return true;
  14776. },
  14777. populateData: function () {
  14778. var data = {};
  14779. if (connection.jingle) {
  14780. data = connection.jingle.populateData();
  14781. }
  14782. return data;
  14783. },
  14784. getLogger: function () {
  14785. if(connection.logger)
  14786. return connection.logger.log;
  14787. return null;
  14788. },
  14789. getPrezi: function () {
  14790. return connection.emuc.getPrezi(this.myJid());
  14791. },
  14792. removePreziFromPresence: function () {
  14793. connection.emuc.removePreziFromPresence();
  14794. connection.emuc.sendPresence();
  14795. },
  14796. sendChatMessage: function (message, nickname) {
  14797. connection.emuc.sendMessage(message, nickname);
  14798. },
  14799. setSubject: function (topic) {
  14800. connection.emuc.setSubject(topic);
  14801. },
  14802. lockRoom: function (key, onSuccess, onError, onNotSupported) {
  14803. connection.emuc.lockRoom(key, onSuccess, onError, onNotSupported);
  14804. },
  14805. dial: function (to, from, roomName,roomPass) {
  14806. connection.rayo.dial(to, from, roomName,roomPass);
  14807. },
  14808. setMute: function (jid, mute) {
  14809. connection.moderate.setMute(jid, mute);
  14810. },
  14811. eject: function (jid) {
  14812. connection.moderate.eject(jid);
  14813. },
  14814. logout: function (callback) {
  14815. Moderator.logout(callback);
  14816. },
  14817. findJidFromResource: function (resource) {
  14818. return connection.emuc.findJidFromResource(resource);
  14819. },
  14820. getMembers: function () {
  14821. return connection.emuc.members;
  14822. },
  14823. getJidFromSSRC: function (ssrc) {
  14824. if(!connection)
  14825. return null;
  14826. return connection.emuc.ssrc2jid[ssrc];
  14827. },
  14828. getMUCJoined: function () {
  14829. return connection.emuc.joined;
  14830. },
  14831. getSessions: function () {
  14832. return connection.jingle.sessions;
  14833. }
  14834. };
  14835. module.exports = XMPP;
  14836. },{"../../service/RTC/StreamEventTypes":90,"../../service/UI/UIEvents":91,"../../service/xmpp/XMPPEvents":96,"./SDP":48,"./moderator":52,"./recording":53,"./strophe.emuc":54,"./strophe.jingle":55,"./strophe.logger":56,"./strophe.moderate":57,"./strophe.rayo":58,"./strophe.util":59,"events":97,"pako":62}],61:[function(require,module,exports){
  14837. // i18next, v1.7.7
  14838. // Copyright (c)2014 Jan Mühlemann (jamuhl).
  14839. // Distributed under MIT license
  14840. // http://i18next.com
  14841. (function() {
  14842. // add indexOf to non ECMA-262 standard compliant browsers
  14843. if (!Array.prototype.indexOf) {
  14844. Array.prototype.indexOf = function (searchElement /*, fromIndex */ ) {
  14845. "use strict";
  14846. if (this == null) {
  14847. throw new TypeError();
  14848. }
  14849. var t = Object(this);
  14850. var len = t.length >>> 0;
  14851. if (len === 0) {
  14852. return -1;
  14853. }
  14854. var n = 0;
  14855. if (arguments.length > 0) {
  14856. n = Number(arguments[1]);
  14857. if (n != n) { // shortcut for verifying if it's NaN
  14858. n = 0;
  14859. } else if (n != 0 && n != Infinity && n != -Infinity) {
  14860. n = (n > 0 || -1) * Math.floor(Math.abs(n));
  14861. }
  14862. }
  14863. if (n >= len) {
  14864. return -1;
  14865. }
  14866. var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);
  14867. for (; k < len; k++) {
  14868. if (k in t && t[k] === searchElement) {
  14869. return k;
  14870. }
  14871. }
  14872. return -1;
  14873. }
  14874. }
  14875. // add lastIndexOf to non ECMA-262 standard compliant browsers
  14876. if (!Array.prototype.lastIndexOf) {
  14877. Array.prototype.lastIndexOf = function(searchElement /*, fromIndex*/) {
  14878. "use strict";
  14879. if (this == null) {
  14880. throw new TypeError();
  14881. }
  14882. var t = Object(this);
  14883. var len = t.length >>> 0;
  14884. if (len === 0) {
  14885. return -1;
  14886. }
  14887. var n = len;
  14888. if (arguments.length > 1) {
  14889. n = Number(arguments[1]);
  14890. if (n != n) {
  14891. n = 0;
  14892. } else if (n != 0 && n != (1 / 0) && n != -(1 / 0)) {
  14893. n = (n > 0 || -1) * Math.floor(Math.abs(n));
  14894. }
  14895. }
  14896. var k = n >= 0 ? Math.min(n, len - 1) : len - Math.abs(n);
  14897. for (; k >= 0; k--) {
  14898. if (k in t && t[k] === searchElement) {
  14899. return k;
  14900. }
  14901. }
  14902. return -1;
  14903. };
  14904. }
  14905. // Add string trim for IE8.
  14906. if (typeof String.prototype.trim !== 'function') {
  14907. String.prototype.trim = function() {
  14908. return this.replace(/^\s+|\s+$/g, '');
  14909. }
  14910. }
  14911. var root = this
  14912. , $ = root.jQuery || root.Zepto
  14913. , i18n = {}
  14914. , resStore = {}
  14915. , currentLng
  14916. , replacementCounter = 0
  14917. , languages = []
  14918. , initialized = false
  14919. , sync = {};
  14920. // Export the i18next object for **CommonJS**.
  14921. // If we're not in CommonJS, add `i18n` to the
  14922. // global object or to jquery.
  14923. if (typeof module !== 'undefined' && module.exports) {
  14924. if (!$) {
  14925. try {
  14926. $ = require('jquery');
  14927. } catch(e) {
  14928. // just ignore
  14929. }
  14930. }
  14931. if ($) {
  14932. $.i18n = $.i18n || i18n;
  14933. }
  14934. module.exports = i18n;
  14935. } else {
  14936. if ($) {
  14937. $.i18n = $.i18n || i18n;
  14938. }
  14939. root.i18n = root.i18n || i18n;
  14940. }
  14941. sync = {
  14942. load: function(lngs, options, cb) {
  14943. if (options.useLocalStorage) {
  14944. sync._loadLocal(lngs, options, function(err, store) {
  14945. var missingLngs = [];
  14946. for (var i = 0, len = lngs.length; i < len; i++) {
  14947. if (!store[lngs[i]]) missingLngs.push(lngs[i]);
  14948. }
  14949. if (missingLngs.length > 0) {
  14950. sync._fetch(missingLngs, options, function(err, fetched) {
  14951. f.extend(store, fetched);
  14952. sync._storeLocal(fetched);
  14953. cb(null, store);
  14954. });
  14955. } else {
  14956. cb(null, store);
  14957. }
  14958. });
  14959. } else {
  14960. sync._fetch(lngs, options, function(err, store){
  14961. cb(null, store);
  14962. });
  14963. }
  14964. },
  14965. _loadLocal: function(lngs, options, cb) {
  14966. var store = {}
  14967. , nowMS = new Date().getTime();
  14968. if(window.localStorage) {
  14969. var todo = lngs.length;
  14970. f.each(lngs, function(key, lng) {
  14971. var local = window.localStorage.getItem('res_' + lng);
  14972. if (local) {
  14973. local = JSON.parse(local);
  14974. if (local.i18nStamp && local.i18nStamp + options.localStorageExpirationTime > nowMS) {
  14975. store[lng] = local;
  14976. }
  14977. }
  14978. todo--; // wait for all done befor callback
  14979. if (todo === 0) cb(null, store);
  14980. });
  14981. }
  14982. },
  14983. _storeLocal: function(store) {
  14984. if(window.localStorage) {
  14985. for (var m in store) {
  14986. store[m].i18nStamp = new Date().getTime();
  14987. f.localStorage.setItem('res_' + m, JSON.stringify(store[m]));
  14988. }
  14989. }
  14990. return;
  14991. },
  14992. _fetch: function(lngs, options, cb) {
  14993. var ns = options.ns
  14994. , store = {};
  14995. if (!options.dynamicLoad) {
  14996. var todo = ns.namespaces.length * lngs.length
  14997. , errors;
  14998. // load each file individual
  14999. f.each(ns.namespaces, function(nsIndex, nsValue) {
  15000. f.each(lngs, function(lngIndex, lngValue) {
  15001. // Call this once our translation has returned.
  15002. var loadComplete = function(err, data) {
  15003. if (err) {
  15004. errors = errors || [];
  15005. errors.push(err);
  15006. }
  15007. store[lngValue] = store[lngValue] || {};
  15008. store[lngValue][nsValue] = data;
  15009. todo--; // wait for all done befor callback
  15010. if (todo === 0) cb(errors, store);
  15011. };
  15012. if(typeof options.customLoad == 'function'){
  15013. // Use the specified custom callback.
  15014. options.customLoad(lngValue, nsValue, options, loadComplete);
  15015. } else {
  15016. //~ // Use our inbuilt sync.
  15017. sync._fetchOne(lngValue, nsValue, options, loadComplete);
  15018. }
  15019. });
  15020. });
  15021. } else {
  15022. // Call this once our translation has returned.
  15023. var loadComplete = function(err, data) {
  15024. cb(null, data);
  15025. };
  15026. if(typeof options.customLoad == 'function'){
  15027. // Use the specified custom callback.
  15028. options.customLoad(lngs, ns.namespaces, options, loadComplete);
  15029. } else {
  15030. var url = applyReplacement(options.resGetPath, { lng: lngs.join('+'), ns: ns.namespaces.join('+') });
  15031. // load all needed stuff once
  15032. f.ajax({
  15033. url: url,
  15034. success: function(data, status, xhr) {
  15035. f.log('loaded: ' + url);
  15036. loadComplete(null, data);
  15037. },
  15038. error : function(xhr, status, error) {
  15039. f.log('failed loading: ' + url);
  15040. loadComplete('failed loading resource.json error: ' + error);
  15041. },
  15042. dataType: "json",
  15043. async : options.getAsync
  15044. });
  15045. }
  15046. }
  15047. },
  15048. _fetchOne: function(lng, ns, options, done) {
  15049. var url = applyReplacement(options.resGetPath, { lng: lng, ns: ns });
  15050. f.ajax({
  15051. url: url,
  15052. success: function(data, status, xhr) {
  15053. f.log('loaded: ' + url);
  15054. done(null, data);
  15055. },
  15056. error : function(xhr, status, error) {
  15057. if ((status && status == 200) || (xhr && xhr.status && xhr.status == 200)) {
  15058. // file loaded but invalid json, stop waste time !
  15059. f.error('There is a typo in: ' + url);
  15060. } else if ((status && status == 404) || (xhr && xhr.status && xhr.status == 404)) {
  15061. f.log('Does not exist: ' + url);
  15062. } else {
  15063. var theStatus = status ? status : ((xhr && xhr.status) ? xhr.status : null);
  15064. f.log(theStatus + ' when loading ' + url);
  15065. }
  15066. done(error, {});
  15067. },
  15068. dataType: "json",
  15069. async : options.getAsync
  15070. });
  15071. },
  15072. postMissing: function(lng, ns, key, defaultValue, lngs) {
  15073. var payload = {};
  15074. payload[key] = defaultValue;
  15075. var urls = [];
  15076. if (o.sendMissingTo === 'fallback' && o.fallbackLng[0] !== false) {
  15077. for (var i = 0; i < o.fallbackLng.length; i++) {
  15078. urls.push({lng: o.fallbackLng[i], url: applyReplacement(o.resPostPath, { lng: o.fallbackLng[i], ns: ns })});
  15079. }
  15080. } else if (o.sendMissingTo === 'current' || (o.sendMissingTo === 'fallback' && o.fallbackLng[0] === false) ) {
  15081. urls.push({lng: lng, url: applyReplacement(o.resPostPath, { lng: lng, ns: ns })});
  15082. } else if (o.sendMissingTo === 'all') {
  15083. for (var i = 0, l = lngs.length; i < l; i++) {
  15084. urls.push({lng: lngs[i], url: applyReplacement(o.resPostPath, { lng: lngs[i], ns: ns })});
  15085. }
  15086. }
  15087. for (var y = 0, len = urls.length; y < len; y++) {
  15088. var item = urls[y];
  15089. f.ajax({
  15090. url: item.url,
  15091. type: o.sendType,
  15092. data: payload,
  15093. success: function(data, status, xhr) {
  15094. f.log('posted missing key \'' + key + '\' to: ' + item.url);
  15095. // add key to resStore
  15096. var keys = key.split('.');
  15097. var x = 0;
  15098. var value = resStore[item.lng][ns];
  15099. while (keys[x]) {
  15100. if (x === keys.length - 1) {
  15101. value = value[keys[x]] = defaultValue;
  15102. } else {
  15103. value = value[keys[x]] = value[keys[x]] || {};
  15104. }
  15105. x++;
  15106. }
  15107. },
  15108. error : function(xhr, status, error) {
  15109. f.log('failed posting missing key \'' + key + '\' to: ' + item.url);
  15110. },
  15111. dataType: "json",
  15112. async : o.postAsync
  15113. });
  15114. }
  15115. },
  15116. reload: reload
  15117. };
  15118. // defaults
  15119. var o = {
  15120. lng: undefined,
  15121. load: 'all',
  15122. preload: [],
  15123. lowerCaseLng: false,
  15124. returnObjectTrees: false,
  15125. fallbackLng: ['dev'],
  15126. fallbackNS: [],
  15127. detectLngQS: 'setLng',
  15128. detectLngFromLocalStorage: false,
  15129. ns: 'translation',
  15130. fallbackOnNull: true,
  15131. fallbackOnEmpty: false,
  15132. fallbackToDefaultNS: false,
  15133. nsseparator: ':',
  15134. keyseparator: '.',
  15135. selectorAttr: 'data-i18n',
  15136. debug: false,
  15137. resGetPath: 'locales/__lng__/__ns__.json',
  15138. resPostPath: 'locales/add/__lng__/__ns__',
  15139. getAsync: true,
  15140. postAsync: true,
  15141. resStore: undefined,
  15142. useLocalStorage: false,
  15143. localStorageExpirationTime: 7*24*60*60*1000,
  15144. dynamicLoad: false,
  15145. sendMissing: false,
  15146. sendMissingTo: 'fallback', // current | all
  15147. sendType: 'POST',
  15148. interpolationPrefix: '__',
  15149. interpolationSuffix: '__',
  15150. defaultVariables: false,
  15151. reusePrefix: '$t(',
  15152. reuseSuffix: ')',
  15153. pluralSuffix: '_plural',
  15154. pluralNotFound: ['plural_not_found', Math.random()].join(''),
  15155. contextNotFound: ['context_not_found', Math.random()].join(''),
  15156. escapeInterpolation: false,
  15157. indefiniteSuffix: '_indefinite',
  15158. indefiniteNotFound: ['indefinite_not_found', Math.random()].join(''),
  15159. setJqueryExt: true,
  15160. defaultValueFromContent: true,
  15161. useDataAttrOptions: false,
  15162. cookieExpirationTime: undefined,
  15163. useCookie: true,
  15164. cookieName: 'i18next',
  15165. cookieDomain: undefined,
  15166. objectTreeKeyHandler: undefined,
  15167. postProcess: undefined,
  15168. parseMissingKey: undefined,
  15169. missingKeyHandler: sync.postMissing,
  15170. shortcutFunction: 'sprintf' // or: defaultValue
  15171. };
  15172. function _extend(target, source) {
  15173. if (!source || typeof source === 'function') {
  15174. return target;
  15175. }
  15176. for (var attr in source) { target[attr] = source[attr]; }
  15177. return target;
  15178. }
  15179. function _deepExtend(target, source) {
  15180. for (var prop in source)
  15181. if (prop in target)
  15182. _deepExtend(target[prop], source[prop]);
  15183. else
  15184. target[prop] = source[prop];
  15185. return target;
  15186. }
  15187. function _each(object, callback, args) {
  15188. var name, i = 0,
  15189. length = object.length,
  15190. isObj = length === undefined || Object.prototype.toString.apply(object) !== '[object Array]' || typeof object === "function";
  15191. if (args) {
  15192. if (isObj) {
  15193. for (name in object) {
  15194. if (callback.apply(object[name], args) === false) {
  15195. break;
  15196. }
  15197. }
  15198. } else {
  15199. for ( ; i < length; ) {
  15200. if (callback.apply(object[i++], args) === false) {
  15201. break;
  15202. }
  15203. }
  15204. }
  15205. // A special, fast, case for the most common use of each
  15206. } else {
  15207. if (isObj) {
  15208. for (name in object) {
  15209. if (callback.call(object[name], name, object[name]) === false) {
  15210. break;
  15211. }
  15212. }
  15213. } else {
  15214. for ( ; i < length; ) {
  15215. if (callback.call(object[i], i, object[i++]) === false) {
  15216. break;
  15217. }
  15218. }
  15219. }
  15220. }
  15221. return object;
  15222. }
  15223. var _entityMap = {
  15224. "&": "&amp;",
  15225. "<": "&lt;",
  15226. ">": "&gt;",
  15227. '"': '&quot;',
  15228. "'": '&#39;',
  15229. "/": '&#x2F;'
  15230. };
  15231. function _escape(data) {
  15232. if (typeof data === 'string') {
  15233. return data.replace(/[&<>"'\/]/g, function (s) {
  15234. return _entityMap[s];
  15235. });
  15236. }else{
  15237. return data;
  15238. }
  15239. }
  15240. function _ajax(options) {
  15241. // v0.5.0 of https://github.com/goloroden/http.js
  15242. var getXhr = function (callback) {
  15243. // Use the native XHR object if the browser supports it.
  15244. if (window.XMLHttpRequest) {
  15245. return callback(null, new XMLHttpRequest());
  15246. } else if (window.ActiveXObject) {
  15247. // In Internet Explorer check for ActiveX versions of the XHR object.
  15248. try {
  15249. return callback(null, new ActiveXObject("Msxml2.XMLHTTP"));
  15250. } catch (e) {
  15251. return callback(null, new ActiveXObject("Microsoft.XMLHTTP"));
  15252. }
  15253. }
  15254. // If no XHR support was found, throw an error.
  15255. return callback(new Error());
  15256. };
  15257. var encodeUsingUrlEncoding = function (data) {
  15258. if(typeof data === 'string') {
  15259. return data;
  15260. }
  15261. var result = [];
  15262. for(var dataItem in data) {
  15263. if(data.hasOwnProperty(dataItem)) {
  15264. result.push(encodeURIComponent(dataItem) + '=' + encodeURIComponent(data[dataItem]));
  15265. }
  15266. }
  15267. return result.join('&');
  15268. };
  15269. var utf8 = function (text) {
  15270. text = text.replace(/\r\n/g, '\n');
  15271. var result = '';
  15272. for(var i = 0; i < text.length; i++) {
  15273. var c = text.charCodeAt(i);
  15274. if(c < 128) {
  15275. result += String.fromCharCode(c);
  15276. } else if((c > 127) && (c < 2048)) {
  15277. result += String.fromCharCode((c >> 6) | 192);
  15278. result += String.fromCharCode((c & 63) | 128);
  15279. } else {
  15280. result += String.fromCharCode((c >> 12) | 224);
  15281. result += String.fromCharCode(((c >> 6) & 63) | 128);
  15282. result += String.fromCharCode((c & 63) | 128);
  15283. }
  15284. }
  15285. return result;
  15286. };
  15287. var base64 = function (text) {
  15288. var keyStr = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
  15289. text = utf8(text);
  15290. var result = '',
  15291. chr1, chr2, chr3,
  15292. enc1, enc2, enc3, enc4,
  15293. i = 0;
  15294. do {
  15295. chr1 = text.charCodeAt(i++);
  15296. chr2 = text.charCodeAt(i++);
  15297. chr3 = text.charCodeAt(i++);
  15298. enc1 = chr1 >> 2;
  15299. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  15300. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  15301. enc4 = chr3 & 63;
  15302. if(isNaN(chr2)) {
  15303. enc3 = enc4 = 64;
  15304. } else if(isNaN(chr3)) {
  15305. enc4 = 64;
  15306. }
  15307. result +=
  15308. keyStr.charAt(enc1) +
  15309. keyStr.charAt(enc2) +
  15310. keyStr.charAt(enc3) +
  15311. keyStr.charAt(enc4);
  15312. chr1 = chr2 = chr3 = '';
  15313. enc1 = enc2 = enc3 = enc4 = '';
  15314. } while(i < text.length);
  15315. return result;
  15316. };
  15317. var mergeHeaders = function () {
  15318. // Use the first header object as base.
  15319. var result = arguments[0];
  15320. // Iterate through the remaining header objects and add them.
  15321. for(var i = 1; i < arguments.length; i++) {
  15322. var currentHeaders = arguments[i];
  15323. for(var header in currentHeaders) {
  15324. if(currentHeaders.hasOwnProperty(header)) {
  15325. result[header] = currentHeaders[header];
  15326. }
  15327. }
  15328. }
  15329. // Return the merged headers.
  15330. return result;
  15331. };
  15332. var ajax = function (method, url, options, callback) {
  15333. // Adjust parameters.
  15334. if(typeof options === 'function') {
  15335. callback = options;
  15336. options = {};
  15337. }
  15338. // Set default parameter values.
  15339. options.cache = options.cache || false;
  15340. options.data = options.data || {};
  15341. options.headers = options.headers || {};
  15342. options.jsonp = options.jsonp || false;
  15343. options.async = options.async === undefined ? true : options.async;
  15344. // Merge the various header objects.
  15345. var headers = mergeHeaders({
  15346. 'accept': '*/*',
  15347. 'content-type': 'application/x-www-form-urlencoded;charset=UTF-8'
  15348. }, ajax.headers, options.headers);
  15349. // Encode the data according to the content-type.
  15350. var payload;
  15351. if (headers['content-type'] === 'application/json') {
  15352. payload = JSON.stringify(options.data);
  15353. } else {
  15354. payload = encodeUsingUrlEncoding(options.data);
  15355. }
  15356. // Specially prepare GET requests: Setup the query string, handle caching and make a JSONP call
  15357. // if neccessary.
  15358. if(method === 'GET') {
  15359. // Setup the query string.
  15360. var queryString = [];
  15361. if(payload) {
  15362. queryString.push(payload);
  15363. payload = null;
  15364. }
  15365. // Handle caching.
  15366. if(!options.cache) {
  15367. queryString.push('_=' + (new Date()).getTime());
  15368. }
  15369. // If neccessary prepare the query string for a JSONP call.
  15370. if(options.jsonp) {
  15371. queryString.push('callback=' + options.jsonp);
  15372. queryString.push('jsonp=' + options.jsonp);
  15373. }
  15374. // Merge the query string and attach it to the url.
  15375. queryString = queryString.join('&');
  15376. if (queryString.length > 1) {
  15377. if (url.indexOf('?') > -1) {
  15378. url += '&' + queryString;
  15379. } else {
  15380. url += '?' + queryString;
  15381. }
  15382. }
  15383. // Make a JSONP call if neccessary.
  15384. if(options.jsonp) {
  15385. var head = document.getElementsByTagName('head')[0];
  15386. var script = document.createElement('script');
  15387. script.type = 'text/javascript';
  15388. script.src = url;
  15389. head.appendChild(script);
  15390. return;
  15391. }
  15392. }
  15393. // Since we got here, it is no JSONP request, so make a normal XHR request.
  15394. getXhr(function (err, xhr) {
  15395. if(err) return callback(err);
  15396. // Open the request.
  15397. xhr.open(method, url, options.async);
  15398. // Set the request headers.
  15399. for(var header in headers) {
  15400. if(headers.hasOwnProperty(header)) {
  15401. xhr.setRequestHeader(header, headers[header]);
  15402. }
  15403. }
  15404. // Handle the request events.
  15405. xhr.onreadystatechange = function () {
  15406. if(xhr.readyState === 4) {
  15407. var data = xhr.responseText || '';
  15408. // If no callback is given, return.
  15409. if(!callback) {
  15410. return;
  15411. }
  15412. // Return an object that provides access to the data as text and JSON.
  15413. callback(xhr.status, {
  15414. text: function () {
  15415. return data;
  15416. },
  15417. json: function () {
  15418. try {
  15419. return JSON.parse(data)
  15420. } catch (e) {
  15421. f.error('Can not parse JSON. URL: ' + url);
  15422. return {};
  15423. }
  15424. }
  15425. });
  15426. }
  15427. };
  15428. // Actually send the XHR request.
  15429. xhr.send(payload);
  15430. });
  15431. };
  15432. // Define the external interface.
  15433. var http = {
  15434. authBasic: function (username, password) {
  15435. ajax.headers['Authorization'] = 'Basic ' + base64(username + ':' + password);
  15436. },
  15437. connect: function (url, options, callback) {
  15438. return ajax('CONNECT', url, options, callback);
  15439. },
  15440. del: function (url, options, callback) {
  15441. return ajax('DELETE', url, options, callback);
  15442. },
  15443. get: function (url, options, callback) {
  15444. return ajax('GET', url, options, callback);
  15445. },
  15446. head: function (url, options, callback) {
  15447. return ajax('HEAD', url, options, callback);
  15448. },
  15449. headers: function (headers) {
  15450. ajax.headers = headers || {};
  15451. },
  15452. isAllowed: function (url, verb, callback) {
  15453. this.options(url, function (status, data) {
  15454. callback(data.text().indexOf(verb) !== -1);
  15455. });
  15456. },
  15457. options: function (url, options, callback) {
  15458. return ajax('OPTIONS', url, options, callback);
  15459. },
  15460. patch: function (url, options, callback) {
  15461. return ajax('PATCH', url, options, callback);
  15462. },
  15463. post: function (url, options, callback) {
  15464. return ajax('POST', url, options, callback);
  15465. },
  15466. put: function (url, options, callback) {
  15467. return ajax('PUT', url, options, callback);
  15468. },
  15469. trace: function (url, options, callback) {
  15470. return ajax('TRACE', url, options, callback);
  15471. }
  15472. };
  15473. var methode = options.type ? options.type.toLowerCase() : 'get';
  15474. http[methode](options.url, options, function (status, data) {
  15475. // file: protocol always gives status code 0, so check for data
  15476. if (status === 200 || (status === 0 && data.text())) {
  15477. options.success(data.json(), status, null);
  15478. } else {
  15479. options.error(data.text(), status, null);
  15480. }
  15481. });
  15482. }
  15483. var _cookie = {
  15484. create: function(name,value,minutes,domain) {
  15485. var expires;
  15486. if (minutes) {
  15487. var date = new Date();
  15488. date.setTime(date.getTime()+(minutes*60*1000));
  15489. expires = "; expires="+date.toGMTString();
  15490. }
  15491. else expires = "";
  15492. domain = (domain)? "domain="+domain+";" : "";
  15493. document.cookie = name+"="+value+expires+";"+domain+"path=/";
  15494. },
  15495. read: function(name) {
  15496. var nameEQ = name + "=";
  15497. var ca = document.cookie.split(';');
  15498. for(var i=0;i < ca.length;i++) {
  15499. var c = ca[i];
  15500. while (c.charAt(0)==' ') c = c.substring(1,c.length);
  15501. if (c.indexOf(nameEQ) === 0) return c.substring(nameEQ.length,c.length);
  15502. }
  15503. return null;
  15504. },
  15505. remove: function(name) {
  15506. this.create(name,"",-1);
  15507. }
  15508. };
  15509. var cookie_noop = {
  15510. create: function(name,value,minutes,domain) {},
  15511. read: function(name) { return null; },
  15512. remove: function(name) {}
  15513. };
  15514. // move dependent functions to a container so that
  15515. // they can be overriden easier in no jquery environment (node.js)
  15516. var f = {
  15517. extend: $ ? $.extend : _extend,
  15518. deepExtend: _deepExtend,
  15519. each: $ ? $.each : _each,
  15520. ajax: $ ? $.ajax : (typeof document !== 'undefined' ? _ajax : function() {}),
  15521. cookie: typeof document !== 'undefined' ? _cookie : cookie_noop,
  15522. detectLanguage: detectLanguage,
  15523. escape: _escape,
  15524. log: function(str) {
  15525. if (o.debug && typeof console !== "undefined") console.log(str);
  15526. },
  15527. error: function(str) {
  15528. if (typeof console !== "undefined") console.error(str);
  15529. },
  15530. getCountyIndexOfLng: function(lng) {
  15531. var lng_index = 0;
  15532. if (lng === 'nb-NO' || lng === 'nn-NO' || lng === 'nb-no' || lng === 'nn-no') lng_index = 1;
  15533. return lng_index;
  15534. },
  15535. toLanguages: function(lng) {
  15536. var log = this.log;
  15537. function applyCase(l) {
  15538. var ret = l;
  15539. if (typeof l === 'string' && l.indexOf('-') > -1) {
  15540. var parts = l.split('-');
  15541. ret = o.lowerCaseLng ?
  15542. parts[0].toLowerCase() + '-' + parts[1].toLowerCase() :
  15543. parts[0].toLowerCase() + '-' + parts[1].toUpperCase();
  15544. } else {
  15545. ret = o.lowerCaseLng ? l.toLowerCase() : l;
  15546. }
  15547. return ret;
  15548. }
  15549. var languages = [];
  15550. var whitelist = o.lngWhitelist || false;
  15551. var addLanguage = function(language){
  15552. //reject langs not whitelisted
  15553. if(!whitelist || whitelist.indexOf(language) > -1){
  15554. languages.push(language);
  15555. }else{
  15556. log('rejecting non-whitelisted language: ' + language);
  15557. }
  15558. };
  15559. if (typeof lng === 'string' && lng.indexOf('-') > -1) {
  15560. var parts = lng.split('-');
  15561. if (o.load !== 'unspecific') addLanguage(applyCase(lng));
  15562. if (o.load !== 'current') addLanguage(applyCase(parts[this.getCountyIndexOfLng(lng)]));
  15563. } else {
  15564. addLanguage(applyCase(lng));
  15565. }
  15566. for (var i = 0; i < o.fallbackLng.length; i++) {
  15567. if (languages.indexOf(o.fallbackLng[i]) === -1 && o.fallbackLng[i]) languages.push(applyCase(o.fallbackLng[i]));
  15568. }
  15569. return languages;
  15570. },
  15571. regexEscape: function(str) {
  15572. return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
  15573. },
  15574. regexReplacementEscape: function(strOrFn) {
  15575. if (typeof strOrFn === 'string') {
  15576. return strOrFn.replace(/\$/g, "$$$$");
  15577. } else {
  15578. return strOrFn;
  15579. }
  15580. },
  15581. localStorage: {
  15582. setItem: function(key, value) {
  15583. if (window.localStorage) {
  15584. try {
  15585. window.localStorage.setItem(key, value);
  15586. } catch (e) {
  15587. f.log('failed to set value for key "' + key + '" to localStorage.');
  15588. }
  15589. }
  15590. }
  15591. }
  15592. };
  15593. function init(options, cb) {
  15594. if (typeof options === 'function') {
  15595. cb = options;
  15596. options = {};
  15597. }
  15598. options = options || {};
  15599. // override defaults with passed in options
  15600. f.extend(o, options);
  15601. delete o.fixLng; /* passed in each time */
  15602. // override functions: .log(), .detectLanguage(), etc
  15603. if (o.functions) {
  15604. delete o.functions;
  15605. f.extend(f, options.functions);
  15606. }
  15607. // create namespace object if namespace is passed in as string
  15608. if (typeof o.ns == 'string') {
  15609. o.ns = { namespaces: [o.ns], defaultNs: o.ns};
  15610. }
  15611. // fallback namespaces
  15612. if (typeof o.fallbackNS == 'string') {
  15613. o.fallbackNS = [o.fallbackNS];
  15614. }
  15615. // fallback languages
  15616. if (typeof o.fallbackLng == 'string' || typeof o.fallbackLng == 'boolean') {
  15617. o.fallbackLng = [o.fallbackLng];
  15618. }
  15619. // escape prefix/suffix
  15620. o.interpolationPrefixEscaped = f.regexEscape(o.interpolationPrefix);
  15621. o.interpolationSuffixEscaped = f.regexEscape(o.interpolationSuffix);
  15622. if (!o.lng) o.lng = f.detectLanguage();
  15623. languages = f.toLanguages(o.lng);
  15624. currentLng = languages[0];
  15625. f.log('currentLng set to: ' + currentLng);
  15626. if (o.useCookie && f.cookie.read(o.cookieName) !== currentLng){ //cookie is unset or invalid
  15627. f.cookie.create(o.cookieName, currentLng, o.cookieExpirationTime, o.cookieDomain);
  15628. }
  15629. if (o.detectLngFromLocalStorage && typeof document !== 'undefined' && window.localStorage) {
  15630. f.localStorage.setItem('i18next_lng', currentLng);
  15631. }
  15632. var lngTranslate = translate;
  15633. if (options.fixLng) {
  15634. lngTranslate = function(key, options) {
  15635. options = options || {};
  15636. options.lng = options.lng || lngTranslate.lng;
  15637. return translate(key, options);
  15638. };
  15639. lngTranslate.lng = currentLng;
  15640. }
  15641. pluralExtensions.setCurrentLng(currentLng);
  15642. // add JQuery extensions
  15643. if ($ && o.setJqueryExt) addJqueryFunct();
  15644. // jQuery deferred
  15645. var deferred;
  15646. if ($ && $.Deferred) {
  15647. deferred = $.Deferred();
  15648. }
  15649. // return immidiatly if res are passed in
  15650. if (o.resStore) {
  15651. resStore = o.resStore;
  15652. initialized = true;
  15653. if (cb) cb(lngTranslate);
  15654. if (deferred) deferred.resolve(lngTranslate);
  15655. if (deferred) return deferred.promise();
  15656. return;
  15657. }
  15658. // languages to load
  15659. var lngsToLoad = f.toLanguages(o.lng);
  15660. if (typeof o.preload === 'string') o.preload = [o.preload];
  15661. for (var i = 0, l = o.preload.length; i < l; i++) {
  15662. var pres = f.toLanguages(o.preload[i]);
  15663. for (var y = 0, len = pres.length; y < len; y++) {
  15664. if (lngsToLoad.indexOf(pres[y]) < 0) {
  15665. lngsToLoad.push(pres[y]);
  15666. }
  15667. }
  15668. }
  15669. // else load them
  15670. i18n.sync.load(lngsToLoad, o, function(err, store) {
  15671. resStore = store;
  15672. initialized = true;
  15673. if (cb) cb(lngTranslate);
  15674. if (deferred) deferred.resolve(lngTranslate);
  15675. });
  15676. if (deferred) return deferred.promise();
  15677. }
  15678. function preload(lngs, cb) {
  15679. if (typeof lngs === 'string') lngs = [lngs];
  15680. for (var i = 0, l = lngs.length; i < l; i++) {
  15681. if (o.preload.indexOf(lngs[i]) < 0) {
  15682. o.preload.push(lngs[i]);
  15683. }
  15684. }
  15685. return init(cb);
  15686. }
  15687. function addResourceBundle(lng, ns, resources, deep) {
  15688. if (typeof ns !== 'string') {
  15689. resources = ns;
  15690. ns = o.ns.defaultNs;
  15691. } else if (o.ns.namespaces.indexOf(ns) < 0) {
  15692. o.ns.namespaces.push(ns);
  15693. }
  15694. resStore[lng] = resStore[lng] || {};
  15695. resStore[lng][ns] = resStore[lng][ns] || {};
  15696. if (deep) {
  15697. f.deepExtend(resStore[lng][ns], resources);
  15698. } else {
  15699. f.extend(resStore[lng][ns], resources);
  15700. }
  15701. }
  15702. function hasResourceBundle(lng, ns) {
  15703. if (typeof ns !== 'string') {
  15704. ns = o.ns.defaultNs;
  15705. }
  15706. resStore[lng] = resStore[lng] || {};
  15707. var res = resStore[lng][ns] || {};
  15708. var hasValues = false;
  15709. for(var prop in res) {
  15710. if (res.hasOwnProperty(prop)) {
  15711. hasValues = true;
  15712. }
  15713. }
  15714. return hasValues;
  15715. }
  15716. function removeResourceBundle(lng, ns) {
  15717. if (typeof ns !== 'string') {
  15718. ns = o.ns.defaultNs;
  15719. }
  15720. resStore[lng] = resStore[lng] || {};
  15721. resStore[lng][ns] = {};
  15722. }
  15723. function addResource(lng, ns, key, value) {
  15724. if (typeof ns !== 'string') {
  15725. resource = ns;
  15726. ns = o.ns.defaultNs;
  15727. } else if (o.ns.namespaces.indexOf(ns) < 0) {
  15728. o.ns.namespaces.push(ns);
  15729. }
  15730. resStore[lng] = resStore[lng] || {};
  15731. resStore[lng][ns] = resStore[lng][ns] || {};
  15732. var keys = key.split(o.keyseparator);
  15733. var x = 0;
  15734. var node = resStore[lng][ns];
  15735. var origRef = node;
  15736. while (keys[x]) {
  15737. if (x == keys.length - 1)
  15738. node[keys[x]] = value;
  15739. else {
  15740. if (node[keys[x]] == null)
  15741. node[keys[x]] = {};
  15742. node = node[keys[x]];
  15743. }
  15744. x++;
  15745. }
  15746. }
  15747. function addResources(lng, ns, resources) {
  15748. if (typeof ns !== 'string') {
  15749. resource = ns;
  15750. ns = o.ns.defaultNs;
  15751. } else if (o.ns.namespaces.indexOf(ns) < 0) {
  15752. o.ns.namespaces.push(ns);
  15753. }
  15754. for (var m in resources) {
  15755. if (typeof resources[m] === 'string') addResource(lng, ns, m, resources[m]);
  15756. }
  15757. }
  15758. function setDefaultNamespace(ns) {
  15759. o.ns.defaultNs = ns;
  15760. }
  15761. function loadNamespace(namespace, cb) {
  15762. loadNamespaces([namespace], cb);
  15763. }
  15764. function loadNamespaces(namespaces, cb) {
  15765. var opts = {
  15766. dynamicLoad: o.dynamicLoad,
  15767. resGetPath: o.resGetPath,
  15768. getAsync: o.getAsync,
  15769. customLoad: o.customLoad,
  15770. ns: { namespaces: namespaces, defaultNs: ''} /* new namespaces to load */
  15771. };
  15772. // languages to load
  15773. var lngsToLoad = f.toLanguages(o.lng);
  15774. if (typeof o.preload === 'string') o.preload = [o.preload];
  15775. for (var i = 0, l = o.preload.length; i < l; i++) {
  15776. var pres = f.toLanguages(o.preload[i]);
  15777. for (var y = 0, len = pres.length; y < len; y++) {
  15778. if (lngsToLoad.indexOf(pres[y]) < 0) {
  15779. lngsToLoad.push(pres[y]);
  15780. }
  15781. }
  15782. }
  15783. // check if we have to load
  15784. var lngNeedLoad = [];
  15785. for (var a = 0, lenA = lngsToLoad.length; a < lenA; a++) {
  15786. var needLoad = false;
  15787. var resSet = resStore[lngsToLoad[a]];
  15788. if (resSet) {
  15789. for (var b = 0, lenB = namespaces.length; b < lenB; b++) {
  15790. if (!resSet[namespaces[b]]) needLoad = true;
  15791. }
  15792. } else {
  15793. needLoad = true;
  15794. }
  15795. if (needLoad) lngNeedLoad.push(lngsToLoad[a]);
  15796. }
  15797. if (lngNeedLoad.length) {
  15798. i18n.sync._fetch(lngNeedLoad, opts, function(err, store) {
  15799. var todo = namespaces.length * lngNeedLoad.length;
  15800. // load each file individual
  15801. f.each(namespaces, function(nsIndex, nsValue) {
  15802. // append namespace to namespace array
  15803. if (o.ns.namespaces.indexOf(nsValue) < 0) {
  15804. o.ns.namespaces.push(nsValue);
  15805. }
  15806. f.each(lngNeedLoad, function(lngIndex, lngValue) {
  15807. resStore[lngValue] = resStore[lngValue] || {};
  15808. resStore[lngValue][nsValue] = store[lngValue][nsValue];
  15809. todo--; // wait for all done befor callback
  15810. if (todo === 0 && cb) {
  15811. if (o.useLocalStorage) i18n.sync._storeLocal(resStore);
  15812. cb();
  15813. }
  15814. });
  15815. });
  15816. });
  15817. } else {
  15818. if (cb) cb();
  15819. }
  15820. }
  15821. function setLng(lng, options, cb) {
  15822. if (typeof options === 'function') {
  15823. cb = options;
  15824. options = {};
  15825. } else if (!options) {
  15826. options = {};
  15827. }
  15828. options.lng = lng;
  15829. return init(options, cb);
  15830. }
  15831. function lng() {
  15832. return currentLng;
  15833. }
  15834. function reload(cb) {
  15835. resStore = {};
  15836. setLng(currentLng, cb);
  15837. }
  15838. function addJqueryFunct() {
  15839. // $.t shortcut
  15840. $.t = $.t || translate;
  15841. function parse(ele, key, options) {
  15842. if (key.length === 0) return;
  15843. var attr = 'text';
  15844. if (key.indexOf('[') === 0) {
  15845. var parts = key.split(']');
  15846. key = parts[1];
  15847. attr = parts[0].substr(1, parts[0].length-1);
  15848. }
  15849. if (key.indexOf(';') === key.length-1) {
  15850. key = key.substr(0, key.length-2);
  15851. }
  15852. var optionsToUse;
  15853. if (attr === 'html') {
  15854. optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.html() }, options) : options;
  15855. ele.html($.t(key, optionsToUse));
  15856. } else if (attr === 'text') {
  15857. optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.text() }, options) : options;
  15858. ele.text($.t(key, optionsToUse));
  15859. } else if (attr === 'prepend') {
  15860. optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.html() }, options) : options;
  15861. ele.prepend($.t(key, optionsToUse));
  15862. } else if (attr === 'append') {
  15863. optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.html() }, options) : options;
  15864. ele.append($.t(key, optionsToUse));
  15865. } else if (attr.indexOf("data-") === 0) {
  15866. var dataAttr = attr.substr(("data-").length);
  15867. optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.data(dataAttr) }, options) : options;
  15868. var translated = $.t(key, optionsToUse);
  15869. //we change into the data cache
  15870. ele.data(dataAttr, translated);
  15871. //we change into the dom
  15872. ele.attr(attr, translated);
  15873. } else {
  15874. optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.attr(attr) }, options) : options;
  15875. ele.attr(attr, $.t(key, optionsToUse));
  15876. }
  15877. }
  15878. function localize(ele, options) {
  15879. var key = ele.attr(o.selectorAttr);
  15880. if (!key && typeof key !== 'undefined' && key !== false) key = ele.text() || ele.val();
  15881. if (!key) return;
  15882. var target = ele
  15883. , targetSelector = ele.data("i18n-target");
  15884. if (targetSelector) {
  15885. target = ele.find(targetSelector) || ele;
  15886. }
  15887. if (!options && o.useDataAttrOptions === true) {
  15888. options = ele.data("i18n-options");
  15889. }
  15890. options = options || {};
  15891. if (key.indexOf(';') >= 0) {
  15892. var keys = key.split(';');
  15893. $.each(keys, function(m, k) {
  15894. if (k !== '') parse(target, k, options);
  15895. });
  15896. } else {
  15897. parse(target, key, options);
  15898. }
  15899. if (o.useDataAttrOptions === true) ele.data("i18n-options", options);
  15900. }
  15901. // fn
  15902. $.fn.i18n = function (options) {
  15903. return this.each(function() {
  15904. // localize element itself
  15905. localize($(this), options);
  15906. // localize childs
  15907. var elements = $(this).find('[' + o.selectorAttr + ']');
  15908. elements.each(function() {
  15909. localize($(this), options);
  15910. });
  15911. });
  15912. };
  15913. }
  15914. function applyReplacement(str, replacementHash, nestedKey, options) {
  15915. if (!str) return str;
  15916. options = options || replacementHash; // first call uses replacement hash combined with options
  15917. if (str.indexOf(options.interpolationPrefix || o.interpolationPrefix) < 0) return str;
  15918. var prefix = options.interpolationPrefix ? f.regexEscape(options.interpolationPrefix) : o.interpolationPrefixEscaped
  15919. , suffix = options.interpolationSuffix ? f.regexEscape(options.interpolationSuffix) : o.interpolationSuffixEscaped
  15920. , unEscapingSuffix = 'HTML'+suffix;
  15921. var hash = replacementHash.replace && typeof replacementHash.replace === 'object' ? replacementHash.replace : replacementHash;
  15922. f.each(hash, function(key, value) {
  15923. var nextKey = nestedKey ? nestedKey + o.keyseparator + key : key;
  15924. if (typeof value === 'object' && value !== null) {
  15925. str = applyReplacement(str, value, nextKey, options);
  15926. } else {
  15927. if (options.escapeInterpolation || o.escapeInterpolation) {
  15928. str = str.replace(new RegExp([prefix, nextKey, unEscapingSuffix].join(''), 'g'), f.regexReplacementEscape(value));
  15929. str = str.replace(new RegExp([prefix, nextKey, suffix].join(''), 'g'), f.regexReplacementEscape(f.escape(value)));
  15930. } else {
  15931. str = str.replace(new RegExp([prefix, nextKey, suffix].join(''), 'g'), f.regexReplacementEscape(value));
  15932. }
  15933. // str = options.escapeInterpolation;
  15934. }
  15935. });
  15936. return str;
  15937. }
  15938. // append it to functions
  15939. f.applyReplacement = applyReplacement;
  15940. function applyReuse(translated, options) {
  15941. var comma = ',';
  15942. var options_open = '{';
  15943. var options_close = '}';
  15944. var opts = f.extend({}, options);
  15945. delete opts.postProcess;
  15946. while (translated.indexOf(o.reusePrefix) != -1) {
  15947. replacementCounter++;
  15948. if (replacementCounter > o.maxRecursion) { break; } // safety net for too much recursion
  15949. var index_of_opening = translated.lastIndexOf(o.reusePrefix);
  15950. var index_of_end_of_closing = translated.indexOf(o.reuseSuffix, index_of_opening) + o.reuseSuffix.length;
  15951. var token = translated.substring(index_of_opening, index_of_end_of_closing);
  15952. var token_without_symbols = token.replace(o.reusePrefix, '').replace(o.reuseSuffix, '');
  15953. if (index_of_end_of_closing <= index_of_opening) {
  15954. f.error('there is an missing closing in following translation value', translated);
  15955. return '';
  15956. }
  15957. if (token_without_symbols.indexOf(comma) != -1) {
  15958. var index_of_token_end_of_closing = token_without_symbols.indexOf(comma);
  15959. 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) {
  15960. var index_of_opts_opening = token_without_symbols.indexOf(options_open, index_of_token_end_of_closing);
  15961. var index_of_opts_end_of_closing = token_without_symbols.indexOf(options_close, index_of_opts_opening) + options_close.length;
  15962. try {
  15963. opts = f.extend(opts, JSON.parse(token_without_symbols.substring(index_of_opts_opening, index_of_opts_end_of_closing)));
  15964. token_without_symbols = token_without_symbols.substring(0, index_of_token_end_of_closing);
  15965. } catch (e) {
  15966. }
  15967. }
  15968. }
  15969. var translated_token = _translate(token_without_symbols, opts);
  15970. translated = translated.replace(token, f.regexReplacementEscape(translated_token));
  15971. }
  15972. return translated;
  15973. }
  15974. function hasContext(options) {
  15975. return (options.context && (typeof options.context == 'string' || typeof options.context == 'number'));
  15976. }
  15977. function needsPlural(options, lng) {
  15978. return (options.count !== undefined && typeof options.count != 'string'/* && pluralExtensions.needsPlural(lng, options.count)*/);
  15979. }
  15980. function needsIndefiniteArticle(options) {
  15981. return (options.indefinite_article !== undefined && typeof options.indefinite_article != 'string' && options.indefinite_article);
  15982. }
  15983. function exists(key, options) {
  15984. options = options || {};
  15985. var notFound = _getDefaultValue(key, options)
  15986. , found = _find(key, options);
  15987. return found !== undefined || found === notFound;
  15988. }
  15989. function translate(key, options) {
  15990. options = options || {};
  15991. if (!initialized) {
  15992. f.log('i18next not finished initialization. you might have called t function before loading resources finished.')
  15993. return options.defaultValue || '';
  15994. };
  15995. replacementCounter = 0;
  15996. return _translate.apply(null, arguments);
  15997. }
  15998. function _getDefaultValue(key, options) {
  15999. return (options.defaultValue !== undefined) ? options.defaultValue : key;
  16000. }
  16001. function _injectSprintfProcessor() {
  16002. var values = [];
  16003. // mh: build array from second argument onwards
  16004. for (var i = 1; i < arguments.length; i++) {
  16005. values.push(arguments[i]);
  16006. }
  16007. return {
  16008. postProcess: 'sprintf',
  16009. sprintf: values
  16010. };
  16011. }
  16012. function _translate(potentialKeys, options) {
  16013. if (options && typeof options !== 'object') {
  16014. if (o.shortcutFunction === 'sprintf') {
  16015. // mh: gettext like sprintf syntax found, automatically create sprintf processor
  16016. options = _injectSprintfProcessor.apply(null, arguments);
  16017. } else if (o.shortcutFunction === 'defaultValue') {
  16018. options = {
  16019. defaultValue: options
  16020. }
  16021. }
  16022. } else {
  16023. options = options || {};
  16024. }
  16025. if (typeof o.defaultVariables === 'object') {
  16026. options = f.extend({}, o.defaultVariables, options);
  16027. }
  16028. if (potentialKeys === undefined || potentialKeys === null || potentialKeys === '') return '';
  16029. if (typeof potentialKeys === 'string') {
  16030. potentialKeys = [potentialKeys];
  16031. }
  16032. var key = potentialKeys[0];
  16033. if (potentialKeys.length > 1) {
  16034. for (var i = 0; i < potentialKeys.length; i++) {
  16035. key = potentialKeys[i];
  16036. if (exists(key, options)) {
  16037. break;
  16038. }
  16039. }
  16040. }
  16041. var notFound = _getDefaultValue(key, options)
  16042. , found = _find(key, options)
  16043. , lngs = options.lng ? f.toLanguages(options.lng, options.fallbackLng) : languages
  16044. , ns = options.ns || o.ns.defaultNs
  16045. , parts;
  16046. // split ns and key
  16047. if (key.indexOf(o.nsseparator) > -1) {
  16048. parts = key.split(o.nsseparator);
  16049. ns = parts[0];
  16050. key = parts[1];
  16051. }
  16052. if (found === undefined && o.sendMissing && typeof o.missingKeyHandler === 'function') {
  16053. if (options.lng) {
  16054. o.missingKeyHandler(lngs[0], ns, key, notFound, lngs);
  16055. } else {
  16056. o.missingKeyHandler(o.lng, ns, key, notFound, lngs);
  16057. }
  16058. }
  16059. var postProcessor = options.postProcess || o.postProcess;
  16060. if (found !== undefined && postProcessor) {
  16061. if (postProcessors[postProcessor]) {
  16062. found = postProcessors[postProcessor](found, key, options);
  16063. }
  16064. }
  16065. // process notFound if function exists
  16066. var splitNotFound = notFound;
  16067. if (notFound.indexOf(o.nsseparator) > -1) {
  16068. parts = notFound.split(o.nsseparator);
  16069. splitNotFound = parts[1];
  16070. }
  16071. if (splitNotFound === key && o.parseMissingKey) {
  16072. notFound = o.parseMissingKey(notFound);
  16073. }
  16074. if (found === undefined) {
  16075. notFound = applyReplacement(notFound, options);
  16076. notFound = applyReuse(notFound, options);
  16077. if (postProcessor && postProcessors[postProcessor]) {
  16078. var val = _getDefaultValue(key, options);
  16079. found = postProcessors[postProcessor](val, key, options);
  16080. }
  16081. }
  16082. return (found !== undefined) ? found : notFound;
  16083. }
  16084. function _find(key, options) {
  16085. options = options || {};
  16086. var optionWithoutCount, translated
  16087. , notFound = _getDefaultValue(key, options)
  16088. , lngs = languages;
  16089. if (!resStore) { return notFound; } // no resStore to translate from
  16090. // CI mode
  16091. if (lngs[0].toLowerCase() === 'cimode') return notFound;
  16092. // passed in lng
  16093. if (options.lngs) lngs = options.lngs;
  16094. if (options.lng) {
  16095. lngs = f.toLanguages(options.lng, options.fallbackLng);
  16096. if (!resStore[lngs[0]]) {
  16097. var oldAsync = o.getAsync;
  16098. o.getAsync = false;
  16099. i18n.sync.load(lngs, o, function(err, store) {
  16100. f.extend(resStore, store);
  16101. o.getAsync = oldAsync;
  16102. });
  16103. }
  16104. }
  16105. var ns = options.ns || o.ns.defaultNs;
  16106. if (key.indexOf(o.nsseparator) > -1) {
  16107. var parts = key.split(o.nsseparator);
  16108. ns = parts[0];
  16109. key = parts[1];
  16110. }
  16111. if (hasContext(options)) {
  16112. optionWithoutCount = f.extend({}, options);
  16113. delete optionWithoutCount.context;
  16114. optionWithoutCount.defaultValue = o.contextNotFound;
  16115. var contextKey = ns + o.nsseparator + key + '_' + options.context;
  16116. translated = translate(contextKey, optionWithoutCount);
  16117. if (translated != o.contextNotFound) {
  16118. return applyReplacement(translated, { context: options.context }); // apply replacement for context only
  16119. } // else continue translation with original/nonContext key
  16120. }
  16121. if (needsPlural(options, lngs[0])) {
  16122. optionWithoutCount = f.extend({ lngs: [lngs[0]]}, options);
  16123. delete optionWithoutCount.count;
  16124. delete optionWithoutCount.lng;
  16125. optionWithoutCount.defaultValue = o.pluralNotFound;
  16126. var pluralKey;
  16127. if (!pluralExtensions.needsPlural(lngs[0], options.count)) {
  16128. pluralKey = ns + o.nsseparator + key;
  16129. } else {
  16130. pluralKey = ns + o.nsseparator + key + o.pluralSuffix;
  16131. var pluralExtension = pluralExtensions.get(lngs[0], options.count);
  16132. if (pluralExtension >= 0) {
  16133. pluralKey = pluralKey + '_' + pluralExtension;
  16134. } else if (pluralExtension === 1) {
  16135. pluralKey = ns + o.nsseparator + key; // singular
  16136. }
  16137. }
  16138. translated = translate(pluralKey, optionWithoutCount);
  16139. if (translated != o.pluralNotFound) {
  16140. return applyReplacement(translated, {
  16141. count: options.count,
  16142. interpolationPrefix: options.interpolationPrefix,
  16143. interpolationSuffix: options.interpolationSuffix
  16144. }); // apply replacement for count only
  16145. } else if (lngs.length > 1) {
  16146. // remove failed lng
  16147. var clone = lngs.slice();
  16148. clone.shift();
  16149. options = f.extend(options, { lngs: clone });
  16150. delete options.lng;
  16151. // retry with fallbacks
  16152. translated = translate(ns + o.nsseparator + key, options);
  16153. if (translated != o.pluralNotFound) return translated;
  16154. } else {
  16155. return translated;
  16156. }
  16157. }
  16158. if (needsIndefiniteArticle(options)) {
  16159. var optionsWithoutIndef = f.extend({}, options);
  16160. delete optionsWithoutIndef.indefinite_article;
  16161. optionsWithoutIndef.defaultValue = o.indefiniteNotFound;
  16162. // If we don't have a count, we want the indefinite, if we do have a count, and needsPlural is false
  16163. var indefiniteKey = ns + o.nsseparator + key + (((options.count && !needsPlural(options, lngs[0])) || !options.count) ? o.indefiniteSuffix : "");
  16164. translated = translate(indefiniteKey, optionsWithoutIndef);
  16165. if (translated != o.indefiniteNotFound) {
  16166. return translated;
  16167. }
  16168. }
  16169. var found;
  16170. var keys = key.split(o.keyseparator);
  16171. for (var i = 0, len = lngs.length; i < len; i++ ) {
  16172. if (found !== undefined) break;
  16173. var l = lngs[i];
  16174. var x = 0;
  16175. var value = resStore[l] && resStore[l][ns];
  16176. while (keys[x]) {
  16177. value = value && value[keys[x]];
  16178. x++;
  16179. }
  16180. if (value !== undefined) {
  16181. var valueType = Object.prototype.toString.apply(value);
  16182. if (typeof value === 'string') {
  16183. value = applyReplacement(value, options);
  16184. value = applyReuse(value, options);
  16185. } else if (valueType === '[object Array]' && !o.returnObjectTrees && !options.returnObjectTrees) {
  16186. value = value.join('\n');
  16187. value = applyReplacement(value, options);
  16188. value = applyReuse(value, options);
  16189. } else if (value === null && o.fallbackOnNull === true) {
  16190. value = undefined;
  16191. } else if (value !== null) {
  16192. if (!o.returnObjectTrees && !options.returnObjectTrees) {
  16193. if (o.objectTreeKeyHandler && typeof o.objectTreeKeyHandler == 'function') {
  16194. value = o.objectTreeKeyHandler(key, value, l, ns, options);
  16195. } else {
  16196. value = 'key \'' + ns + ':' + key + ' (' + l + ')\' ' +
  16197. 'returned an object instead of string.';
  16198. f.log(value);
  16199. }
  16200. } else if (valueType !== '[object Number]' && valueType !== '[object Function]' && valueType !== '[object RegExp]') {
  16201. var copy = (valueType === '[object Array]') ? [] : {}; // apply child translation on a copy
  16202. f.each(value, function(m) {
  16203. copy[m] = _translate(ns + o.nsseparator + key + o.keyseparator + m, options);
  16204. });
  16205. value = copy;
  16206. }
  16207. }
  16208. if (typeof value === 'string' && value.trim() === '' && o.fallbackOnEmpty === true)
  16209. value = undefined;
  16210. found = value;
  16211. }
  16212. }
  16213. if (found === undefined && !options.isFallbackLookup && (o.fallbackToDefaultNS === true || (o.fallbackNS && o.fallbackNS.length > 0))) {
  16214. // set flag for fallback lookup - avoid recursion
  16215. options.isFallbackLookup = true;
  16216. if (o.fallbackNS.length) {
  16217. for (var y = 0, lenY = o.fallbackNS.length; y < lenY; y++) {
  16218. found = _find(o.fallbackNS[y] + o.nsseparator + key, options);
  16219. if (found || (found==="" && o.fallbackOnEmpty === false)) {
  16220. /* compare value without namespace */
  16221. var foundValue = found.indexOf(o.nsseparator) > -1 ? found.split(o.nsseparator)[1] : found
  16222. , notFoundValue = notFound.indexOf(o.nsseparator) > -1 ? notFound.split(o.nsseparator)[1] : notFound;
  16223. if (foundValue !== notFoundValue) break;
  16224. }
  16225. }
  16226. } else {
  16227. found = _find(key, options); // fallback to default NS
  16228. }
  16229. options.isFallbackLookup = false;
  16230. }
  16231. return found;
  16232. }
  16233. function detectLanguage() {
  16234. var detectedLng;
  16235. var whitelist = o.lngWhitelist || [];
  16236. var userLngChoices = [];
  16237. // get from qs
  16238. var qsParm = [];
  16239. if (typeof window !== 'undefined') {
  16240. (function() {
  16241. var query = window.location.search.substring(1);
  16242. var params = query.split('&');
  16243. for (var i=0; i<params.length; i++) {
  16244. var pos = params[i].indexOf('=');
  16245. if (pos > 0) {
  16246. var key = params[i].substring(0,pos);
  16247. if (key == o.detectLngQS) {
  16248. userLngChoices.push(params[i].substring(pos+1));
  16249. }
  16250. }
  16251. }
  16252. })();
  16253. }
  16254. // get from cookie
  16255. if (o.useCookie && typeof document !== 'undefined') {
  16256. var c = f.cookie.read(o.cookieName);
  16257. if (c) userLngChoices.push(c);
  16258. }
  16259. // get from localStorage
  16260. if (o.detectLngFromLocalStorage && typeof window !== 'undefined' && window.localStorage) {
  16261. userLngChoices.push(window.localStorage.getItem('i18next_lng'));
  16262. }
  16263. // get from navigator
  16264. if (typeof navigator !== 'undefined') {
  16265. if (navigator.languages) { // chrome only; not an array, so can't use .push.apply instead of iterating
  16266. for (var i=0;i<navigator.languages.length;i++) {
  16267. userLngChoices.push(navigator.languages[i]);
  16268. }
  16269. }
  16270. if (navigator.userLanguage) {
  16271. userLngChoices.push(navigator.userLanguage);
  16272. }
  16273. if (navigator.language) {
  16274. userLngChoices.push(navigator.language);
  16275. }
  16276. }
  16277. (function() {
  16278. for (var i=0;i<userLngChoices.length;i++) {
  16279. var lng = userLngChoices[i];
  16280. if (lng.indexOf('-') > -1) {
  16281. var parts = lng.split('-');
  16282. lng = o.lowerCaseLng ?
  16283. parts[0].toLowerCase() + '-' + parts[1].toLowerCase() :
  16284. parts[0].toLowerCase() + '-' + parts[1].toUpperCase();
  16285. }
  16286. if (whitelist.length === 0 || whitelist.indexOf(lng) > -1) {
  16287. detectedLng = lng;
  16288. break;
  16289. }
  16290. }
  16291. })();
  16292. //fallback
  16293. if (!detectedLng){
  16294. detectedLng = o.fallbackLng[0];
  16295. }
  16296. return detectedLng;
  16297. }
  16298. // definition http://translate.sourceforge.net/wiki/l10n/pluralforms
  16299. /* [code, name, numbers, pluralsType] */
  16300. var _rules = [
  16301. ["ach", "Acholi", [1,2], 1],
  16302. ["af", "Afrikaans",[1,2], 2],
  16303. ["ak", "Akan", [1,2], 1],
  16304. ["am", "Amharic", [1,2], 1],
  16305. ["an", "Aragonese",[1,2], 2],
  16306. ["ar", "Arabic", [0,1,2,3,11,100],5],
  16307. ["arn", "Mapudungun",[1,2], 1],
  16308. ["ast", "Asturian", [1,2], 2],
  16309. ["ay", "Aymará", [1], 3],
  16310. ["az", "Azerbaijani",[1,2],2],
  16311. ["be", "Belarusian",[1,2,5],4],
  16312. ["bg", "Bulgarian",[1,2], 2],
  16313. ["bn", "Bengali", [1,2], 2],
  16314. ["bo", "Tibetan", [1], 3],
  16315. ["br", "Breton", [1,2], 1],
  16316. ["bs", "Bosnian", [1,2,5],4],
  16317. ["ca", "Catalan", [1,2], 2],
  16318. ["cgg", "Chiga", [1], 3],
  16319. ["cs", "Czech", [1,2,5],6],
  16320. ["csb", "Kashubian",[1,2,5],7],
  16321. ["cy", "Welsh", [1,2,3,8],8],
  16322. ["da", "Danish", [1,2], 2],
  16323. ["de", "German", [1,2], 2],
  16324. ["dev", "Development Fallback", [1,2], 2],
  16325. ["dz", "Dzongkha", [1], 3],
  16326. ["el", "Greek", [1,2], 2],
  16327. ["en", "English", [1,2], 2],
  16328. ["eo", "Esperanto",[1,2], 2],
  16329. ["es", "Spanish", [1,2], 2],
  16330. ["es_ar","Argentinean Spanish", [1,2], 2],
  16331. ["et", "Estonian", [1,2], 2],
  16332. ["eu", "Basque", [1,2], 2],
  16333. ["fa", "Persian", [1], 3],
  16334. ["fi", "Finnish", [1,2], 2],
  16335. ["fil", "Filipino", [1,2], 1],
  16336. ["fo", "Faroese", [1,2], 2],
  16337. ["fr", "French", [1,2], 9],
  16338. ["fur", "Friulian", [1,2], 2],
  16339. ["fy", "Frisian", [1,2], 2],
  16340. ["ga", "Irish", [1,2,3,7,11],10],
  16341. ["gd", "Scottish Gaelic",[1,2,3,20],11],
  16342. ["gl", "Galician", [1,2], 2],
  16343. ["gu", "Gujarati", [1,2], 2],
  16344. ["gun", "Gun", [1,2], 1],
  16345. ["ha", "Hausa", [1,2], 2],
  16346. ["he", "Hebrew", [1,2], 2],
  16347. ["hi", "Hindi", [1,2], 2],
  16348. ["hr", "Croatian", [1,2,5],4],
  16349. ["hu", "Hungarian",[1,2], 2],
  16350. ["hy", "Armenian", [1,2], 2],
  16351. ["ia", "Interlingua",[1,2],2],
  16352. ["id", "Indonesian",[1], 3],
  16353. ["is", "Icelandic",[1,2], 12],
  16354. ["it", "Italian", [1,2], 2],
  16355. ["ja", "Japanese", [1], 3],
  16356. ["jbo", "Lojban", [1], 3],
  16357. ["jv", "Javanese", [0,1], 13],
  16358. ["ka", "Georgian", [1], 3],
  16359. ["kk", "Kazakh", [1], 3],
  16360. ["km", "Khmer", [1], 3],
  16361. ["kn", "Kannada", [1,2], 2],
  16362. ["ko", "Korean", [1], 3],
  16363. ["ku", "Kurdish", [1,2], 2],
  16364. ["kw", "Cornish", [1,2,3,4],14],
  16365. ["ky", "Kyrgyz", [1], 3],
  16366. ["lb", "Letzeburgesch",[1,2],2],
  16367. ["ln", "Lingala", [1,2], 1],
  16368. ["lo", "Lao", [1], 3],
  16369. ["lt", "Lithuanian",[1,2,10],15],
  16370. ["lv", "Latvian", [1,2,0],16],
  16371. ["mai", "Maithili", [1,2], 2],
  16372. ["mfe", "Mauritian Creole",[1,2],1],
  16373. ["mg", "Malagasy", [1,2], 1],
  16374. ["mi", "Maori", [1,2], 1],
  16375. ["mk", "Macedonian",[1,2],17],
  16376. ["ml", "Malayalam",[1,2], 2],
  16377. ["mn", "Mongolian",[1,2], 2],
  16378. ["mnk", "Mandinka", [0,1,2],18],
  16379. ["mr", "Marathi", [1,2], 2],
  16380. ["ms", "Malay", [1], 3],
  16381. ["mt", "Maltese", [1,2,11,20],19],
  16382. ["nah", "Nahuatl", [1,2], 2],
  16383. ["nap", "Neapolitan",[1,2], 2],
  16384. ["nb", "Norwegian Bokmal",[1,2],2],
  16385. ["ne", "Nepali", [1,2], 2],
  16386. ["nl", "Dutch", [1,2], 2],
  16387. ["nn", "Norwegian Nynorsk",[1,2],2],
  16388. ["no", "Norwegian",[1,2], 2],
  16389. ["nso", "Northern Sotho",[1,2],2],
  16390. ["oc", "Occitan", [1,2], 1],
  16391. ["or", "Oriya", [2,1], 2],
  16392. ["pa", "Punjabi", [1,2], 2],
  16393. ["pap", "Papiamento",[1,2], 2],
  16394. ["pl", "Polish", [1,2,5],7],
  16395. ["pms", "Piemontese",[1,2], 2],
  16396. ["ps", "Pashto", [1,2], 2],
  16397. ["pt", "Portuguese",[1,2], 2],
  16398. ["pt_br","Brazilian Portuguese",[1,2], 2],
  16399. ["rm", "Romansh", [1,2], 2],
  16400. ["ro", "Romanian", [1,2,20],20],
  16401. ["ru", "Russian", [1,2,5],4],
  16402. ["sah", "Yakut", [1], 3],
  16403. ["sco", "Scots", [1,2], 2],
  16404. ["se", "Northern Sami",[1,2], 2],
  16405. ["si", "Sinhala", [1,2], 2],
  16406. ["sk", "Slovak", [1,2,5],6],
  16407. ["sl", "Slovenian",[5,1,2,3],21],
  16408. ["so", "Somali", [1,2], 2],
  16409. ["son", "Songhay", [1,2], 2],
  16410. ["sq", "Albanian", [1,2], 2],
  16411. ["sr", "Serbian", [1,2,5],4],
  16412. ["su", "Sundanese",[1], 3],
  16413. ["sv", "Swedish", [1,2], 2],
  16414. ["sw", "Swahili", [1,2], 2],
  16415. ["ta", "Tamil", [1,2], 2],
  16416. ["te", "Telugu", [1,2], 2],
  16417. ["tg", "Tajik", [1,2], 1],
  16418. ["th", "Thai", [1], 3],
  16419. ["ti", "Tigrinya", [1,2], 1],
  16420. ["tk", "Turkmen", [1,2], 2],
  16421. ["tr", "Turkish", [1,2], 1],
  16422. ["tt", "Tatar", [1], 3],
  16423. ["ug", "Uyghur", [1], 3],
  16424. ["uk", "Ukrainian",[1,2,5],4],
  16425. ["ur", "Urdu", [1,2], 2],
  16426. ["uz", "Uzbek", [1,2], 1],
  16427. ["vi", "Vietnamese",[1], 3],
  16428. ["wa", "Walloon", [1,2], 1],
  16429. ["wo", "Wolof", [1], 3],
  16430. ["yo", "Yoruba", [1,2], 2],
  16431. ["zh", "Chinese", [1], 3]
  16432. ];
  16433. var _rulesPluralsTypes = {
  16434. 1: function(n) {return Number(n > 1);},
  16435. 2: function(n) {return Number(n != 1);},
  16436. 3: function(n) {return 0;},
  16437. 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);},
  16438. 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);},
  16439. 6: function(n) {return Number((n==1) ? 0 : (n>=2 && n<=4) ? 1 : 2);},
  16440. 7: function(n) {return Number(n==1 ? 0 : n%10>=2 && n%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2);},
  16441. 8: function(n) {return Number((n==1) ? 0 : (n==2) ? 1 : (n != 8 && n != 11) ? 2 : 3);},
  16442. 9: function(n) {return Number(n >= 2);},
  16443. 10: function(n) {return Number(n==1 ? 0 : n==2 ? 1 : n<7 ? 2 : n<11 ? 3 : 4) ;},
  16444. 11: function(n) {return Number((n==1 || n==11) ? 0 : (n==2 || n==12) ? 1 : (n > 2 && n < 20) ? 2 : 3);},
  16445. 12: function(n) {return Number(n%10!=1 || n%100==11);},
  16446. 13: function(n) {return Number(n !== 0);},
  16447. 14: function(n) {return Number((n==1) ? 0 : (n==2) ? 1 : (n == 3) ? 2 : 3);},
  16448. 15: function(n) {return Number(n%10==1 && n%100!=11 ? 0 : n%10>=2 && (n%100<10 || n%100>=20) ? 1 : 2);},
  16449. 16: function(n) {return Number(n%10==1 && n%100!=11 ? 0 : n !== 0 ? 1 : 2);},
  16450. 17: function(n) {return Number(n==1 || n%10==1 ? 0 : 1);},
  16451. 18: function(n) {return Number(0 ? 0 : n==1 ? 1 : 2);},
  16452. 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);},
  16453. 20: function(n) {return Number(n==1 ? 0 : (n===0 || (n%100 > 0 && n%100 < 20)) ? 1 : 2);},
  16454. 21: function(n) {return Number(n%100==1 ? 1 : n%100==2 ? 2 : n%100==3 || n%100==4 ? 3 : 0); }
  16455. };
  16456. var pluralExtensions = {
  16457. rules: (function () {
  16458. var l, rules = {};
  16459. for (l=_rules.length; l-- ;) {
  16460. rules[_rules[l][0]] = {
  16461. name: _rules[l][1],
  16462. numbers: _rules[l][2],
  16463. plurals: _rulesPluralsTypes[_rules[l][3]]
  16464. }
  16465. }
  16466. return rules;
  16467. }()),
  16468. // you can add your own pluralExtensions
  16469. addRule: function(lng, obj) {
  16470. pluralExtensions.rules[lng] = obj;
  16471. },
  16472. setCurrentLng: function(lng) {
  16473. if (!pluralExtensions.currentRule || pluralExtensions.currentRule.lng !== lng) {
  16474. var parts = lng.split('-');
  16475. pluralExtensions.currentRule = {
  16476. lng: lng,
  16477. rule: pluralExtensions.rules[parts[0]]
  16478. };
  16479. }
  16480. },
  16481. needsPlural: function(lng, count) {
  16482. var parts = lng.split('-');
  16483. var ext;
  16484. if (pluralExtensions.currentRule && pluralExtensions.currentRule.lng === lng) {
  16485. ext = pluralExtensions.currentRule.rule;
  16486. } else {
  16487. ext = pluralExtensions.rules[parts[f.getCountyIndexOfLng(lng)]];
  16488. }
  16489. if (ext && ext.numbers.length <= 1) {
  16490. return false;
  16491. } else {
  16492. return this.get(lng, count) !== 1;
  16493. }
  16494. },
  16495. get: function(lng, count) {
  16496. var parts = lng.split('-');
  16497. function getResult(l, c) {
  16498. var ext;
  16499. if (pluralExtensions.currentRule && pluralExtensions.currentRule.lng === lng) {
  16500. ext = pluralExtensions.currentRule.rule;
  16501. } else {
  16502. ext = pluralExtensions.rules[l];
  16503. }
  16504. if (ext) {
  16505. var i;
  16506. if (ext.noAbs) {
  16507. i = ext.plurals(c);
  16508. } else {
  16509. i = ext.plurals(Math.abs(c));
  16510. }
  16511. var number = ext.numbers[i];
  16512. if (ext.numbers.length === 2 && ext.numbers[0] === 1) {
  16513. if (number === 2) {
  16514. number = -1; // regular plural
  16515. } else if (number === 1) {
  16516. number = 1; // singular
  16517. }
  16518. }//console.log(count + '-' + number);
  16519. return number;
  16520. } else {
  16521. return c === 1 ? '1' : '-1';
  16522. }
  16523. }
  16524. return getResult(parts[f.getCountyIndexOfLng(lng)], count);
  16525. }
  16526. };
  16527. var postProcessors = {};
  16528. var addPostProcessor = function(name, fc) {
  16529. postProcessors[name] = fc;
  16530. };
  16531. // sprintf support
  16532. var sprintf = (function() {
  16533. function get_type(variable) {
  16534. return Object.prototype.toString.call(variable).slice(8, -1).toLowerCase();
  16535. }
  16536. function str_repeat(input, multiplier) {
  16537. for (var output = []; multiplier > 0; output[--multiplier] = input) {/* do nothing */}
  16538. return output.join('');
  16539. }
  16540. var str_format = function() {
  16541. if (!str_format.cache.hasOwnProperty(arguments[0])) {
  16542. str_format.cache[arguments[0]] = str_format.parse(arguments[0]);
  16543. }
  16544. return str_format.format.call(null, str_format.cache[arguments[0]], arguments);
  16545. };
  16546. str_format.format = function(parse_tree, argv) {
  16547. var cursor = 1, tree_length = parse_tree.length, node_type = '', arg, output = [], i, k, match, pad, pad_character, pad_length;
  16548. for (i = 0; i < tree_length; i++) {
  16549. node_type = get_type(parse_tree[i]);
  16550. if (node_type === 'string') {
  16551. output.push(parse_tree[i]);
  16552. }
  16553. else if (node_type === 'array') {
  16554. match = parse_tree[i]; // convenience purposes only
  16555. if (match[2]) { // keyword argument
  16556. arg = argv[cursor];
  16557. for (k = 0; k < match[2].length; k++) {
  16558. if (!arg.hasOwnProperty(match[2][k])) {
  16559. throw(sprintf('[sprintf] property "%s" does not exist', match[2][k]));
  16560. }
  16561. arg = arg[match[2][k]];
  16562. }
  16563. }
  16564. else if (match[1]) { // positional argument (explicit)
  16565. arg = argv[match[1]];
  16566. }
  16567. else { // positional argument (implicit)
  16568. arg = argv[cursor++];
  16569. }
  16570. if (/[^s]/.test(match[8]) && (get_type(arg) != 'number')) {
  16571. throw(sprintf('[sprintf] expecting number but found %s', get_type(arg)));
  16572. }
  16573. switch (match[8]) {
  16574. case 'b': arg = arg.toString(2); break;
  16575. case 'c': arg = String.fromCharCode(arg); break;
  16576. case 'd': arg = parseInt(arg, 10); break;
  16577. case 'e': arg = match[7] ? arg.toExponential(match[7]) : arg.toExponential(); break;
  16578. case 'f': arg = match[7] ? parseFloat(arg).toFixed(match[7]) : parseFloat(arg); break;
  16579. case 'o': arg = arg.toString(8); break;
  16580. case 's': arg = ((arg = String(arg)) && match[7] ? arg.substring(0, match[7]) : arg); break;
  16581. case 'u': arg = Math.abs(arg); break;
  16582. case 'x': arg = arg.toString(16); break;
  16583. case 'X': arg = arg.toString(16).toUpperCase(); break;
  16584. }
  16585. arg = (/[def]/.test(match[8]) && match[3] && arg >= 0 ? '+'+ arg : arg);
  16586. pad_character = match[4] ? match[4] == '0' ? '0' : match[4].charAt(1) : ' ';
  16587. pad_length = match[6] - String(arg).length;
  16588. pad = match[6] ? str_repeat(pad_character, pad_length) : '';
  16589. output.push(match[5] ? arg + pad : pad + arg);
  16590. }
  16591. }
  16592. return output.join('');
  16593. };
  16594. str_format.cache = {};
  16595. str_format.parse = function(fmt) {
  16596. var _fmt = fmt, match = [], parse_tree = [], arg_names = 0;
  16597. while (_fmt) {
  16598. if ((match = /^[^\x25]+/.exec(_fmt)) !== null) {
  16599. parse_tree.push(match[0]);
  16600. }
  16601. else if ((match = /^\x25{2}/.exec(_fmt)) !== null) {
  16602. parse_tree.push('%');
  16603. }
  16604. else if ((match = /^\x25(?:([1-9]\d*)\$|\(([^\)]+)\))?(\+)?(0|'[^$])?(-)?(\d+)?(?:\.(\d+))?([b-fosuxX])/.exec(_fmt)) !== null) {
  16605. if (match[2]) {
  16606. arg_names |= 1;
  16607. var field_list = [], replacement_field = match[2], field_match = [];
  16608. if ((field_match = /^([a-z_][a-z_\d]*)/i.exec(replacement_field)) !== null) {
  16609. field_list.push(field_match[1]);
  16610. while ((replacement_field = replacement_field.substring(field_match[0].length)) !== '') {
  16611. if ((field_match = /^\.([a-z_][a-z_\d]*)/i.exec(replacement_field)) !== null) {
  16612. field_list.push(field_match[1]);
  16613. }
  16614. else if ((field_match = /^\[(\d+)\]/.exec(replacement_field)) !== null) {
  16615. field_list.push(field_match[1]);
  16616. }
  16617. else {
  16618. throw('[sprintf] huh?');
  16619. }
  16620. }
  16621. }
  16622. else {
  16623. throw('[sprintf] huh?');
  16624. }
  16625. match[2] = field_list;
  16626. }
  16627. else {
  16628. arg_names |= 2;
  16629. }
  16630. if (arg_names === 3) {
  16631. throw('[sprintf] mixing positional and named placeholders is not (yet) supported');
  16632. }
  16633. parse_tree.push(match);
  16634. }
  16635. else {
  16636. throw('[sprintf] huh?');
  16637. }
  16638. _fmt = _fmt.substring(match[0].length);
  16639. }
  16640. return parse_tree;
  16641. };
  16642. return str_format;
  16643. })();
  16644. var vsprintf = function(fmt, argv) {
  16645. argv.unshift(fmt);
  16646. return sprintf.apply(null, argv);
  16647. };
  16648. addPostProcessor("sprintf", function(val, key, opts) {
  16649. if (!opts.sprintf) return val;
  16650. if (Object.prototype.toString.apply(opts.sprintf) === '[object Array]') {
  16651. return vsprintf(val, opts.sprintf);
  16652. } else if (typeof opts.sprintf === 'object') {
  16653. return sprintf(val, opts.sprintf);
  16654. }
  16655. return val;
  16656. });
  16657. // public api interface
  16658. i18n.init = init;
  16659. i18n.setLng = setLng;
  16660. i18n.preload = preload;
  16661. i18n.addResourceBundle = addResourceBundle;
  16662. i18n.hasResourceBundle = hasResourceBundle;
  16663. i18n.addResource = addResource;
  16664. i18n.addResources = addResources;
  16665. i18n.removeResourceBundle = removeResourceBundle;
  16666. i18n.loadNamespace = loadNamespace;
  16667. i18n.loadNamespaces = loadNamespaces;
  16668. i18n.setDefaultNamespace = setDefaultNamespace;
  16669. i18n.t = translate;
  16670. i18n.translate = translate;
  16671. i18n.exists = exists;
  16672. i18n.detectLanguage = f.detectLanguage;
  16673. i18n.pluralExtensions = pluralExtensions;
  16674. i18n.sync = sync;
  16675. i18n.functions = f;
  16676. i18n.lng = lng;
  16677. i18n.addPostProcessor = addPostProcessor;
  16678. i18n.options = o;
  16679. })();
  16680. },{"jquery":"jquery"}],62:[function(require,module,exports){
  16681. // Top level file is just a mixin of submodules & constants
  16682. 'use strict';
  16683. var assign = require('./lib/utils/common').assign;
  16684. var deflate = require('./lib/deflate');
  16685. var inflate = require('./lib/inflate');
  16686. var constants = require('./lib/zlib/constants');
  16687. var pako = {};
  16688. assign(pako, deflate, inflate, constants);
  16689. module.exports = pako;
  16690. },{"./lib/deflate":63,"./lib/inflate":64,"./lib/utils/common":65,"./lib/zlib/constants":68}],63:[function(require,module,exports){
  16691. 'use strict';
  16692. var zlib_deflate = require('./zlib/deflate.js');
  16693. var utils = require('./utils/common');
  16694. var strings = require('./utils/strings');
  16695. var msg = require('./zlib/messages');
  16696. var zstream = require('./zlib/zstream');
  16697. /* Public constants ==========================================================*/
  16698. /* ===========================================================================*/
  16699. var Z_NO_FLUSH = 0;
  16700. var Z_FINISH = 4;
  16701. var Z_OK = 0;
  16702. var Z_STREAM_END = 1;
  16703. var Z_DEFAULT_COMPRESSION = -1;
  16704. var Z_DEFAULT_STRATEGY = 0;
  16705. var Z_DEFLATED = 8;
  16706. /* ===========================================================================*/
  16707. /**
  16708. * class Deflate
  16709. *
  16710. * Generic JS-style wrapper for zlib calls. If you don't need
  16711. * streaming behaviour - use more simple functions: [[deflate]],
  16712. * [[deflateRaw]] and [[gzip]].
  16713. **/
  16714. /* internal
  16715. * Deflate.chunks -> Array
  16716. *
  16717. * Chunks of output data, if [[Deflate#onData]] not overriden.
  16718. **/
  16719. /**
  16720. * Deflate.result -> Uint8Array|Array
  16721. *
  16722. * Compressed result, generated by default [[Deflate#onData]]
  16723. * and [[Deflate#onEnd]] handlers. Filled after you push last chunk
  16724. * (call [[Deflate#push]] with `Z_FINISH` / `true` param).
  16725. **/
  16726. /**
  16727. * Deflate.err -> Number
  16728. *
  16729. * Error code after deflate finished. 0 (Z_OK) on success.
  16730. * You will not need it in real life, because deflate errors
  16731. * are possible only on wrong options or bad `onData` / `onEnd`
  16732. * custom handlers.
  16733. **/
  16734. /**
  16735. * Deflate.msg -> String
  16736. *
  16737. * Error message, if [[Deflate.err]] != 0
  16738. **/
  16739. /**
  16740. * new Deflate(options)
  16741. * - options (Object): zlib deflate options.
  16742. *
  16743. * Creates new deflator instance with specified params. Throws exception
  16744. * on bad params. Supported options:
  16745. *
  16746. * - `level`
  16747. * - `windowBits`
  16748. * - `memLevel`
  16749. * - `strategy`
  16750. *
  16751. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  16752. * for more information on these.
  16753. *
  16754. * Additional options, for internal needs:
  16755. *
  16756. * - `chunkSize` - size of generated data chunks (16K by default)
  16757. * - `raw` (Boolean) - do raw deflate
  16758. * - `gzip` (Boolean) - create gzip wrapper
  16759. * - `to` (String) - if equal to 'string', then result will be "binary string"
  16760. * (each char code [0..255])
  16761. * - `header` (Object) - custom header for gzip
  16762. * - `text` (Boolean) - true if compressed data believed to be text
  16763. * - `time` (Number) - modification time, unix timestamp
  16764. * - `os` (Number) - operation system code
  16765. * - `extra` (Array) - array of bytes with extra data (max 65536)
  16766. * - `name` (String) - file name (binary string)
  16767. * - `comment` (String) - comment (binary string)
  16768. * - `hcrc` (Boolean) - true if header crc should be added
  16769. *
  16770. * ##### Example:
  16771. *
  16772. * ```javascript
  16773. * var pako = require('pako')
  16774. * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
  16775. * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
  16776. *
  16777. * var deflate = new pako.Deflate({ level: 3});
  16778. *
  16779. * deflate.push(chunk1, false);
  16780. * deflate.push(chunk2, true); // true -> last chunk
  16781. *
  16782. * if (deflate.err) { throw new Error(deflate.err); }
  16783. *
  16784. * console.log(deflate.result);
  16785. * ```
  16786. **/
  16787. var Deflate = function(options) {
  16788. this.options = utils.assign({
  16789. level: Z_DEFAULT_COMPRESSION,
  16790. method: Z_DEFLATED,
  16791. chunkSize: 16384,
  16792. windowBits: 15,
  16793. memLevel: 8,
  16794. strategy: Z_DEFAULT_STRATEGY,
  16795. to: ''
  16796. }, options || {});
  16797. var opt = this.options;
  16798. if (opt.raw && (opt.windowBits > 0)) {
  16799. opt.windowBits = -opt.windowBits;
  16800. }
  16801. else if (opt.gzip && (opt.windowBits > 0) && (opt.windowBits < 16)) {
  16802. opt.windowBits += 16;
  16803. }
  16804. this.err = 0; // error code, if happens (0 = Z_OK)
  16805. this.msg = ''; // error message
  16806. this.ended = false; // used to avoid multiple onEnd() calls
  16807. this.chunks = []; // chunks of compressed data
  16808. this.strm = new zstream();
  16809. this.strm.avail_out = 0;
  16810. var status = zlib_deflate.deflateInit2(
  16811. this.strm,
  16812. opt.level,
  16813. opt.method,
  16814. opt.windowBits,
  16815. opt.memLevel,
  16816. opt.strategy
  16817. );
  16818. if (status !== Z_OK) {
  16819. throw new Error(msg[status]);
  16820. }
  16821. if (opt.header) {
  16822. zlib_deflate.deflateSetHeader(this.strm, opt.header);
  16823. }
  16824. };
  16825. /**
  16826. * Deflate#push(data[, mode]) -> Boolean
  16827. * - data (Uint8Array|Array|String): input data. Strings will be converted to
  16828. * utf8 byte sequence.
  16829. * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
  16830. * See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH.
  16831. *
  16832. * Sends input data to deflate pipe, generating [[Deflate#onData]] calls with
  16833. * new compressed chunks. Returns `true` on success. The last data block must have
  16834. * mode Z_FINISH (or `true`). That flush internal pending buffers and call
  16835. * [[Deflate#onEnd]].
  16836. *
  16837. * On fail call [[Deflate#onEnd]] with error code and return false.
  16838. *
  16839. * We strongly recommend to use `Uint8Array` on input for best speed (output
  16840. * array format is detected automatically). Also, don't skip last param and always
  16841. * use the same type in your code (boolean or number). That will improve JS speed.
  16842. *
  16843. * For regular `Array`-s make sure all elements are [0..255].
  16844. *
  16845. * ##### Example
  16846. *
  16847. * ```javascript
  16848. * push(chunk, false); // push one of data chunks
  16849. * ...
  16850. * push(chunk, true); // push last chunk
  16851. * ```
  16852. **/
  16853. Deflate.prototype.push = function(data, mode) {
  16854. var strm = this.strm;
  16855. var chunkSize = this.options.chunkSize;
  16856. var status, _mode;
  16857. if (this.ended) { return false; }
  16858. _mode = (mode === ~~mode) ? mode : ((mode === true) ? Z_FINISH : Z_NO_FLUSH);
  16859. // Convert data if needed
  16860. if (typeof data === 'string') {
  16861. // If we need to compress text, change encoding to utf8.
  16862. strm.input = strings.string2buf(data);
  16863. } else {
  16864. strm.input = data;
  16865. }
  16866. strm.next_in = 0;
  16867. strm.avail_in = strm.input.length;
  16868. do {
  16869. if (strm.avail_out === 0) {
  16870. strm.output = new utils.Buf8(chunkSize);
  16871. strm.next_out = 0;
  16872. strm.avail_out = chunkSize;
  16873. }
  16874. status = zlib_deflate.deflate(strm, _mode); /* no bad return value */
  16875. if (status !== Z_STREAM_END && status !== Z_OK) {
  16876. this.onEnd(status);
  16877. this.ended = true;
  16878. return false;
  16879. }
  16880. if (strm.avail_out === 0 || (strm.avail_in === 0 && _mode === Z_FINISH)) {
  16881. if (this.options.to === 'string') {
  16882. this.onData(strings.buf2binstring(utils.shrinkBuf(strm.output, strm.next_out)));
  16883. } else {
  16884. this.onData(utils.shrinkBuf(strm.output, strm.next_out));
  16885. }
  16886. }
  16887. } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== Z_STREAM_END);
  16888. // Finalize on the last chunk.
  16889. if (_mode === Z_FINISH) {
  16890. status = zlib_deflate.deflateEnd(this.strm);
  16891. this.onEnd(status);
  16892. this.ended = true;
  16893. return status === Z_OK;
  16894. }
  16895. return true;
  16896. };
  16897. /**
  16898. * Deflate#onData(chunk) -> Void
  16899. * - chunk (Uint8Array|Array|String): ouput data. Type of array depends
  16900. * on js engine support. When string output requested, each chunk
  16901. * will be string.
  16902. *
  16903. * By default, stores data blocks in `chunks[]` property and glue
  16904. * those in `onEnd`. Override this handler, if you need another behaviour.
  16905. **/
  16906. Deflate.prototype.onData = function(chunk) {
  16907. this.chunks.push(chunk);
  16908. };
  16909. /**
  16910. * Deflate#onEnd(status) -> Void
  16911. * - status (Number): deflate status. 0 (Z_OK) on success,
  16912. * other if not.
  16913. *
  16914. * Called once after you tell deflate that input stream complete
  16915. * or error happenned. By default - join collected chunks,
  16916. * free memory and fill `results` / `err` properties.
  16917. **/
  16918. Deflate.prototype.onEnd = function(status) {
  16919. // On success - join
  16920. if (status === Z_OK) {
  16921. if (this.options.to === 'string') {
  16922. this.result = this.chunks.join('');
  16923. } else {
  16924. this.result = utils.flattenChunks(this.chunks);
  16925. }
  16926. }
  16927. this.chunks = [];
  16928. this.err = status;
  16929. this.msg = this.strm.msg;
  16930. };
  16931. /**
  16932. * deflate(data[, options]) -> Uint8Array|Array|String
  16933. * - data (Uint8Array|Array|String): input data to compress.
  16934. * - options (Object): zlib deflate options.
  16935. *
  16936. * Compress `data` with deflate alrorythm and `options`.
  16937. *
  16938. * Supported options are:
  16939. *
  16940. * - level
  16941. * - windowBits
  16942. * - memLevel
  16943. * - strategy
  16944. *
  16945. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  16946. * for more information on these.
  16947. *
  16948. * Sugar (options):
  16949. *
  16950. * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
  16951. * negative windowBits implicitly.
  16952. * - `to` (String) - if equal to 'string', then result will be "binary string"
  16953. * (each char code [0..255])
  16954. *
  16955. * ##### Example:
  16956. *
  16957. * ```javascript
  16958. * var pako = require('pako')
  16959. * , data = Uint8Array([1,2,3,4,5,6,7,8,9]);
  16960. *
  16961. * console.log(pako.deflate(data));
  16962. * ```
  16963. **/
  16964. function deflate(input, options) {
  16965. var deflator = new Deflate(options);
  16966. deflator.push(input, true);
  16967. // That will never happens, if you don't cheat with options :)
  16968. if (deflator.err) { throw deflator.msg; }
  16969. return deflator.result;
  16970. }
  16971. /**
  16972. * deflateRaw(data[, options]) -> Uint8Array|Array|String
  16973. * - data (Uint8Array|Array|String): input data to compress.
  16974. * - options (Object): zlib deflate options.
  16975. *
  16976. * The same as [[deflate]], but creates raw data, without wrapper
  16977. * (header and adler32 crc).
  16978. **/
  16979. function deflateRaw(input, options) {
  16980. options = options || {};
  16981. options.raw = true;
  16982. return deflate(input, options);
  16983. }
  16984. /**
  16985. * gzip(data[, options]) -> Uint8Array|Array|String
  16986. * - data (Uint8Array|Array|String): input data to compress.
  16987. * - options (Object): zlib deflate options.
  16988. *
  16989. * The same as [[deflate]], but create gzip wrapper instead of
  16990. * deflate one.
  16991. **/
  16992. function gzip(input, options) {
  16993. options = options || {};
  16994. options.gzip = true;
  16995. return deflate(input, options);
  16996. }
  16997. exports.Deflate = Deflate;
  16998. exports.deflate = deflate;
  16999. exports.deflateRaw = deflateRaw;
  17000. exports.gzip = gzip;
  17001. },{"./utils/common":65,"./utils/strings":66,"./zlib/deflate.js":70,"./zlib/messages":75,"./zlib/zstream":77}],64:[function(require,module,exports){
  17002. 'use strict';
  17003. var zlib_inflate = require('./zlib/inflate.js');
  17004. var utils = require('./utils/common');
  17005. var strings = require('./utils/strings');
  17006. var c = require('./zlib/constants');
  17007. var msg = require('./zlib/messages');
  17008. var zstream = require('./zlib/zstream');
  17009. var gzheader = require('./zlib/gzheader');
  17010. /**
  17011. * class Inflate
  17012. *
  17013. * Generic JS-style wrapper for zlib calls. If you don't need
  17014. * streaming behaviour - use more simple functions: [[inflate]]
  17015. * and [[inflateRaw]].
  17016. **/
  17017. /* internal
  17018. * inflate.chunks -> Array
  17019. *
  17020. * Chunks of output data, if [[Inflate#onData]] not overriden.
  17021. **/
  17022. /**
  17023. * Inflate.result -> Uint8Array|Array|String
  17024. *
  17025. * Uncompressed result, generated by default [[Inflate#onData]]
  17026. * and [[Inflate#onEnd]] handlers. Filled after you push last chunk
  17027. * (call [[Inflate#push]] with `Z_FINISH` / `true` param).
  17028. **/
  17029. /**
  17030. * Inflate.err -> Number
  17031. *
  17032. * Error code after inflate finished. 0 (Z_OK) on success.
  17033. * Should be checked if broken data possible.
  17034. **/
  17035. /**
  17036. * Inflate.msg -> String
  17037. *
  17038. * Error message, if [[Inflate.err]] != 0
  17039. **/
  17040. /**
  17041. * new Inflate(options)
  17042. * - options (Object): zlib inflate options.
  17043. *
  17044. * Creates new inflator instance with specified params. Throws exception
  17045. * on bad params. Supported options:
  17046. *
  17047. * - `windowBits`
  17048. *
  17049. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  17050. * for more information on these.
  17051. *
  17052. * Additional options, for internal needs:
  17053. *
  17054. * - `chunkSize` - size of generated data chunks (16K by default)
  17055. * - `raw` (Boolean) - do raw inflate
  17056. * - `to` (String) - if equal to 'string', then result will be converted
  17057. * from utf8 to utf16 (javascript) string. When string output requested,
  17058. * chunk length can differ from `chunkSize`, depending on content.
  17059. *
  17060. * By default, when no options set, autodetect deflate/gzip data format via
  17061. * wrapper header.
  17062. *
  17063. * ##### Example:
  17064. *
  17065. * ```javascript
  17066. * var pako = require('pako')
  17067. * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
  17068. * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
  17069. *
  17070. * var inflate = new pako.Inflate({ level: 3});
  17071. *
  17072. * inflate.push(chunk1, false);
  17073. * inflate.push(chunk2, true); // true -> last chunk
  17074. *
  17075. * if (inflate.err) { throw new Error(inflate.err); }
  17076. *
  17077. * console.log(inflate.result);
  17078. * ```
  17079. **/
  17080. var Inflate = function(options) {
  17081. this.options = utils.assign({
  17082. chunkSize: 16384,
  17083. windowBits: 0,
  17084. to: ''
  17085. }, options || {});
  17086. var opt = this.options;
  17087. // Force window size for `raw` data, if not set directly,
  17088. // because we have no header for autodetect.
  17089. if (opt.raw && (opt.windowBits >= 0) && (opt.windowBits < 16)) {
  17090. opt.windowBits = -opt.windowBits;
  17091. if (opt.windowBits === 0) { opt.windowBits = -15; }
  17092. }
  17093. // If `windowBits` not defined (and mode not raw) - set autodetect flag for gzip/deflate
  17094. if ((opt.windowBits >= 0) && (opt.windowBits < 16) &&
  17095. !(options && options.windowBits)) {
  17096. opt.windowBits += 32;
  17097. }
  17098. // Gzip header has no info about windows size, we can do autodetect only
  17099. // for deflate. So, if window size not set, force it to max when gzip possible
  17100. if ((opt.windowBits > 15) && (opt.windowBits < 48)) {
  17101. // bit 3 (16) -> gzipped data
  17102. // bit 4 (32) -> autodetect gzip/deflate
  17103. if ((opt.windowBits & 15) === 0) {
  17104. opt.windowBits |= 15;
  17105. }
  17106. }
  17107. this.err = 0; // error code, if happens (0 = Z_OK)
  17108. this.msg = ''; // error message
  17109. this.ended = false; // used to avoid multiple onEnd() calls
  17110. this.chunks = []; // chunks of compressed data
  17111. this.strm = new zstream();
  17112. this.strm.avail_out = 0;
  17113. var status = zlib_inflate.inflateInit2(
  17114. this.strm,
  17115. opt.windowBits
  17116. );
  17117. if (status !== c.Z_OK) {
  17118. throw new Error(msg[status]);
  17119. }
  17120. this.header = new gzheader();
  17121. zlib_inflate.inflateGetHeader(this.strm, this.header);
  17122. };
  17123. /**
  17124. * Inflate#push(data[, mode]) -> Boolean
  17125. * - data (Uint8Array|Array|String): input data
  17126. * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
  17127. * See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH.
  17128. *
  17129. * Sends input data to inflate pipe, generating [[Inflate#onData]] calls with
  17130. * new output chunks. Returns `true` on success. The last data block must have
  17131. * mode Z_FINISH (or `true`). That flush internal pending buffers and call
  17132. * [[Inflate#onEnd]].
  17133. *
  17134. * On fail call [[Inflate#onEnd]] with error code and return false.
  17135. *
  17136. * We strongly recommend to use `Uint8Array` on input for best speed (output
  17137. * format is detected automatically). Also, don't skip last param and always
  17138. * use the same type in your code (boolean or number). That will improve JS speed.
  17139. *
  17140. * For regular `Array`-s make sure all elements are [0..255].
  17141. *
  17142. * ##### Example
  17143. *
  17144. * ```javascript
  17145. * push(chunk, false); // push one of data chunks
  17146. * ...
  17147. * push(chunk, true); // push last chunk
  17148. * ```
  17149. **/
  17150. Inflate.prototype.push = function(data, mode) {
  17151. var strm = this.strm;
  17152. var chunkSize = this.options.chunkSize;
  17153. var status, _mode;
  17154. var next_out_utf8, tail, utf8str;
  17155. if (this.ended) { return false; }
  17156. _mode = (mode === ~~mode) ? mode : ((mode === true) ? c.Z_FINISH : c.Z_NO_FLUSH);
  17157. // Convert data if needed
  17158. if (typeof data === 'string') {
  17159. // Only binary strings can be decompressed on practice
  17160. strm.input = strings.binstring2buf(data);
  17161. } else {
  17162. strm.input = data;
  17163. }
  17164. strm.next_in = 0;
  17165. strm.avail_in = strm.input.length;
  17166. do {
  17167. if (strm.avail_out === 0) {
  17168. strm.output = new utils.Buf8(chunkSize);
  17169. strm.next_out = 0;
  17170. strm.avail_out = chunkSize;
  17171. }
  17172. status = zlib_inflate.inflate(strm, c.Z_NO_FLUSH); /* no bad return value */
  17173. if (status !== c.Z_STREAM_END && status !== c.Z_OK) {
  17174. this.onEnd(status);
  17175. this.ended = true;
  17176. return false;
  17177. }
  17178. if (strm.next_out) {
  17179. if (strm.avail_out === 0 || status === c.Z_STREAM_END || (strm.avail_in === 0 && _mode === c.Z_FINISH)) {
  17180. if (this.options.to === 'string') {
  17181. next_out_utf8 = strings.utf8border(strm.output, strm.next_out);
  17182. tail = strm.next_out - next_out_utf8;
  17183. utf8str = strings.buf2string(strm.output, next_out_utf8);
  17184. // move tail
  17185. strm.next_out = tail;
  17186. strm.avail_out = chunkSize - tail;
  17187. if (tail) { utils.arraySet(strm.output, strm.output, next_out_utf8, tail, 0); }
  17188. this.onData(utf8str);
  17189. } else {
  17190. this.onData(utils.shrinkBuf(strm.output, strm.next_out));
  17191. }
  17192. }
  17193. }
  17194. } while ((strm.avail_in > 0) && status !== c.Z_STREAM_END);
  17195. if (status === c.Z_STREAM_END) {
  17196. _mode = c.Z_FINISH;
  17197. }
  17198. // Finalize on the last chunk.
  17199. if (_mode === c.Z_FINISH) {
  17200. status = zlib_inflate.inflateEnd(this.strm);
  17201. this.onEnd(status);
  17202. this.ended = true;
  17203. return status === c.Z_OK;
  17204. }
  17205. return true;
  17206. };
  17207. /**
  17208. * Inflate#onData(chunk) -> Void
  17209. * - chunk (Uint8Array|Array|String): ouput data. Type of array depends
  17210. * on js engine support. When string output requested, each chunk
  17211. * will be string.
  17212. *
  17213. * By default, stores data blocks in `chunks[]` property and glue
  17214. * those in `onEnd`. Override this handler, if you need another behaviour.
  17215. **/
  17216. Inflate.prototype.onData = function(chunk) {
  17217. this.chunks.push(chunk);
  17218. };
  17219. /**
  17220. * Inflate#onEnd(status) -> Void
  17221. * - status (Number): inflate status. 0 (Z_OK) on success,
  17222. * other if not.
  17223. *
  17224. * Called once after you tell inflate that input stream complete
  17225. * or error happenned. By default - join collected chunks,
  17226. * free memory and fill `results` / `err` properties.
  17227. **/
  17228. Inflate.prototype.onEnd = function(status) {
  17229. // On success - join
  17230. if (status === c.Z_OK) {
  17231. if (this.options.to === 'string') {
  17232. // Glue & convert here, until we teach pako to send
  17233. // utf8 alligned strings to onData
  17234. this.result = this.chunks.join('');
  17235. } else {
  17236. this.result = utils.flattenChunks(this.chunks);
  17237. }
  17238. }
  17239. this.chunks = [];
  17240. this.err = status;
  17241. this.msg = this.strm.msg;
  17242. };
  17243. /**
  17244. * inflate(data[, options]) -> Uint8Array|Array|String
  17245. * - data (Uint8Array|Array|String): input data to decompress.
  17246. * - options (Object): zlib inflate options.
  17247. *
  17248. * Decompress `data` with inflate/ungzip and `options`. Autodetect
  17249. * format via wrapper header by default. That's why we don't provide
  17250. * separate `ungzip` method.
  17251. *
  17252. * Supported options are:
  17253. *
  17254. * - windowBits
  17255. *
  17256. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  17257. * for more information.
  17258. *
  17259. * Sugar (options):
  17260. *
  17261. * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
  17262. * negative windowBits implicitly.
  17263. * - `to` (String) - if equal to 'string', then result will be converted
  17264. * from utf8 to utf16 (javascript) string. When string output requested,
  17265. * chunk length can differ from `chunkSize`, depending on content.
  17266. *
  17267. *
  17268. * ##### Example:
  17269. *
  17270. * ```javascript
  17271. * var pako = require('pako')
  17272. * , input = pako.deflate([1,2,3,4,5,6,7,8,9])
  17273. * , output;
  17274. *
  17275. * try {
  17276. * output = pako.inflate(input);
  17277. * } catch (err)
  17278. * console.log(err);
  17279. * }
  17280. * ```
  17281. **/
  17282. function inflate(input, options) {
  17283. var inflator = new Inflate(options);
  17284. inflator.push(input, true);
  17285. // That will never happens, if you don't cheat with options :)
  17286. if (inflator.err) { throw inflator.msg; }
  17287. return inflator.result;
  17288. }
  17289. /**
  17290. * inflateRaw(data[, options]) -> Uint8Array|Array|String
  17291. * - data (Uint8Array|Array|String): input data to decompress.
  17292. * - options (Object): zlib inflate options.
  17293. *
  17294. * The same as [[inflate]], but creates raw data, without wrapper
  17295. * (header and adler32 crc).
  17296. **/
  17297. function inflateRaw(input, options) {
  17298. options = options || {};
  17299. options.raw = true;
  17300. return inflate(input, options);
  17301. }
  17302. /**
  17303. * ungzip(data[, options]) -> Uint8Array|Array|String
  17304. * - data (Uint8Array|Array|String): input data to decompress.
  17305. * - options (Object): zlib inflate options.
  17306. *
  17307. * Just shortcut to [[inflate]], because it autodetects format
  17308. * by header.content. Done for convenience.
  17309. **/
  17310. exports.Inflate = Inflate;
  17311. exports.inflate = inflate;
  17312. exports.inflateRaw = inflateRaw;
  17313. exports.ungzip = inflate;
  17314. },{"./utils/common":65,"./utils/strings":66,"./zlib/constants":68,"./zlib/gzheader":71,"./zlib/inflate.js":73,"./zlib/messages":75,"./zlib/zstream":77}],65:[function(require,module,exports){
  17315. 'use strict';
  17316. var TYPED_OK = (typeof Uint8Array !== 'undefined') &&
  17317. (typeof Uint16Array !== 'undefined') &&
  17318. (typeof Int32Array !== 'undefined');
  17319. exports.assign = function (obj /*from1, from2, from3, ...*/) {
  17320. var sources = Array.prototype.slice.call(arguments, 1);
  17321. while (sources.length) {
  17322. var source = sources.shift();
  17323. if (!source) { continue; }
  17324. if (typeof(source) !== 'object') {
  17325. throw new TypeError(source + 'must be non-object');
  17326. }
  17327. for (var p in source) {
  17328. if (source.hasOwnProperty(p)) {
  17329. obj[p] = source[p];
  17330. }
  17331. }
  17332. }
  17333. return obj;
  17334. };
  17335. // reduce buffer size, avoiding mem copy
  17336. exports.shrinkBuf = function (buf, size) {
  17337. if (buf.length === size) { return buf; }
  17338. if (buf.subarray) { return buf.subarray(0, size); }
  17339. buf.length = size;
  17340. return buf;
  17341. };
  17342. var fnTyped = {
  17343. arraySet: function (dest, src, src_offs, len, dest_offs) {
  17344. if (src.subarray && dest.subarray) {
  17345. dest.set(src.subarray(src_offs, src_offs+len), dest_offs);
  17346. return;
  17347. }
  17348. // Fallback to ordinary array
  17349. for(var i=0; i<len; i++) {
  17350. dest[dest_offs + i] = src[src_offs + i];
  17351. }
  17352. },
  17353. // Join array of chunks to single array.
  17354. flattenChunks: function(chunks) {
  17355. var i, l, len, pos, chunk, result;
  17356. // calculate data length
  17357. len = 0;
  17358. for (i=0, l=chunks.length; i<l; i++) {
  17359. len += chunks[i].length;
  17360. }
  17361. // join chunks
  17362. result = new Uint8Array(len);
  17363. pos = 0;
  17364. for (i=0, l=chunks.length; i<l; i++) {
  17365. chunk = chunks[i];
  17366. result.set(chunk, pos);
  17367. pos += chunk.length;
  17368. }
  17369. return result;
  17370. }
  17371. };
  17372. var fnUntyped = {
  17373. arraySet: function (dest, src, src_offs, len, dest_offs) {
  17374. for(var i=0; i<len; i++) {
  17375. dest[dest_offs + i] = src[src_offs + i];
  17376. }
  17377. },
  17378. // Join array of chunks to single array.
  17379. flattenChunks: function(chunks) {
  17380. return [].concat.apply([], chunks);
  17381. }
  17382. };
  17383. // Enable/Disable typed arrays use, for testing
  17384. //
  17385. exports.setTyped = function (on) {
  17386. if (on) {
  17387. exports.Buf8 = Uint8Array;
  17388. exports.Buf16 = Uint16Array;
  17389. exports.Buf32 = Int32Array;
  17390. exports.assign(exports, fnTyped);
  17391. } else {
  17392. exports.Buf8 = Array;
  17393. exports.Buf16 = Array;
  17394. exports.Buf32 = Array;
  17395. exports.assign(exports, fnUntyped);
  17396. }
  17397. };
  17398. exports.setTyped(TYPED_OK);
  17399. },{}],66:[function(require,module,exports){
  17400. // String encode/decode helpers
  17401. 'use strict';
  17402. var utils = require('./common');
  17403. // Quick check if we can use fast array to bin string conversion
  17404. //
  17405. // - apply(Array) can fail on Android 2.2
  17406. // - apply(Uint8Array) can fail on iOS 5.1 Safary
  17407. //
  17408. var STR_APPLY_OK = true;
  17409. var STR_APPLY_UIA_OK = true;
  17410. try { String.fromCharCode.apply(null, [0]); } catch(__) { STR_APPLY_OK = false; }
  17411. try { String.fromCharCode.apply(null, new Uint8Array(1)); } catch(__) { STR_APPLY_UIA_OK = false; }
  17412. // Table with utf8 lengths (calculated by first byte of sequence)
  17413. // Note, that 5 & 6-byte values and some 4-byte values can not be represented in JS,
  17414. // because max possible codepoint is 0x10ffff
  17415. var _utf8len = new utils.Buf8(256);
  17416. for (var i=0; i<256; i++) {
  17417. _utf8len[i] = (i >= 252 ? 6 : i >= 248 ? 5 : i >= 240 ? 4 : i >= 224 ? 3 : i >= 192 ? 2 : 1);
  17418. }
  17419. _utf8len[254]=_utf8len[254]=1; // Invalid sequence start
  17420. // convert string to array (typed, when possible)
  17421. exports.string2buf = function (str) {
  17422. var buf, c, c2, m_pos, i, str_len = str.length, buf_len = 0;
  17423. // count binary size
  17424. for (m_pos = 0; m_pos < str_len; m_pos++) {
  17425. c = str.charCodeAt(m_pos);
  17426. if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) {
  17427. c2 = str.charCodeAt(m_pos+1);
  17428. if ((c2 & 0xfc00) === 0xdc00) {
  17429. c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
  17430. m_pos++;
  17431. }
  17432. }
  17433. buf_len += c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4;
  17434. }
  17435. // allocate buffer
  17436. buf = new utils.Buf8(buf_len);
  17437. // convert
  17438. for (i=0, m_pos = 0; i < buf_len; m_pos++) {
  17439. c = str.charCodeAt(m_pos);
  17440. if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) {
  17441. c2 = str.charCodeAt(m_pos+1);
  17442. if ((c2 & 0xfc00) === 0xdc00) {
  17443. c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
  17444. m_pos++;
  17445. }
  17446. }
  17447. if (c < 0x80) {
  17448. /* one byte */
  17449. buf[i++] = c;
  17450. } else if (c < 0x800) {
  17451. /* two bytes */
  17452. buf[i++] = 0xC0 | (c >>> 6);
  17453. buf[i++] = 0x80 | (c & 0x3f);
  17454. } else if (c < 0x10000) {
  17455. /* three bytes */
  17456. buf[i++] = 0xE0 | (c >>> 12);
  17457. buf[i++] = 0x80 | (c >>> 6 & 0x3f);
  17458. buf[i++] = 0x80 | (c & 0x3f);
  17459. } else {
  17460. /* four bytes */
  17461. buf[i++] = 0xf0 | (c >>> 18);
  17462. buf[i++] = 0x80 | (c >>> 12 & 0x3f);
  17463. buf[i++] = 0x80 | (c >>> 6 & 0x3f);
  17464. buf[i++] = 0x80 | (c & 0x3f);
  17465. }
  17466. }
  17467. return buf;
  17468. };
  17469. // Helper (used in 2 places)
  17470. function buf2binstring(buf, len) {
  17471. // use fallback for big arrays to avoid stack overflow
  17472. if (len < 65537) {
  17473. if ((buf.subarray && STR_APPLY_UIA_OK) || (!buf.subarray && STR_APPLY_OK)) {
  17474. return String.fromCharCode.apply(null, utils.shrinkBuf(buf, len));
  17475. }
  17476. }
  17477. var result = '';
  17478. for(var i=0; i < len; i++) {
  17479. result += String.fromCharCode(buf[i]);
  17480. }
  17481. return result;
  17482. }
  17483. // Convert byte array to binary string
  17484. exports.buf2binstring = function(buf) {
  17485. return buf2binstring(buf, buf.length);
  17486. };
  17487. // Convert binary string (typed, when possible)
  17488. exports.binstring2buf = function(str) {
  17489. var buf = new utils.Buf8(str.length);
  17490. for(var i=0, len=buf.length; i < len; i++) {
  17491. buf[i] = str.charCodeAt(i);
  17492. }
  17493. return buf;
  17494. };
  17495. // convert array to string
  17496. exports.buf2string = function (buf, max) {
  17497. var i, out, c, c_len;
  17498. var len = max || buf.length;
  17499. // Reserve max possible length (2 words per char)
  17500. // NB: by unknown reasons, Array is significantly faster for
  17501. // String.fromCharCode.apply than Uint16Array.
  17502. var utf16buf = new Array(len*2);
  17503. for (out=0, i=0; i<len;) {
  17504. c = buf[i++];
  17505. // quick process ascii
  17506. if (c < 0x80) { utf16buf[out++] = c; continue; }
  17507. c_len = _utf8len[c];
  17508. // skip 5 & 6 byte codes
  17509. if (c_len > 4) { utf16buf[out++] = 0xfffd; i += c_len-1; continue; }
  17510. // apply mask on first byte
  17511. c &= c_len === 2 ? 0x1f : c_len === 3 ? 0x0f : 0x07;
  17512. // join the rest
  17513. while (c_len > 1 && i < len) {
  17514. c = (c << 6) | (buf[i++] & 0x3f);
  17515. c_len--;
  17516. }
  17517. // terminated by end of string?
  17518. if (c_len > 1) { utf16buf[out++] = 0xfffd; continue; }
  17519. if (c < 0x10000) {
  17520. utf16buf[out++] = c;
  17521. } else {
  17522. c -= 0x10000;
  17523. utf16buf[out++] = 0xd800 | ((c >> 10) & 0x3ff);
  17524. utf16buf[out++] = 0xdc00 | (c & 0x3ff);
  17525. }
  17526. }
  17527. return buf2binstring(utf16buf, out);
  17528. };
  17529. // Calculate max possible position in utf8 buffer,
  17530. // that will not break sequence. If that's not possible
  17531. // - (very small limits) return max size as is.
  17532. //
  17533. // buf[] - utf8 bytes array
  17534. // max - length limit (mandatory);
  17535. exports.utf8border = function(buf, max) {
  17536. var pos;
  17537. max = max || buf.length;
  17538. if (max > buf.length) { max = buf.length; }
  17539. // go back from last position, until start of sequence found
  17540. pos = max-1;
  17541. while (pos >= 0 && (buf[pos] & 0xC0) === 0x80) { pos--; }
  17542. // Fuckup - very small and broken sequence,
  17543. // return max, because we should return something anyway.
  17544. if (pos < 0) { return max; }
  17545. // If we came to start of buffer - that means vuffer is too small,
  17546. // return max too.
  17547. if (pos === 0) { return max; }
  17548. return (pos + _utf8len[buf[pos]] > max) ? pos : max;
  17549. };
  17550. },{"./common":65}],67:[function(require,module,exports){
  17551. 'use strict';
  17552. // Note: adler32 takes 12% for level 0 and 2% for level 6.
  17553. // It doesn't worth to make additional optimizationa as in original.
  17554. // Small size is preferable.
  17555. function adler32(adler, buf, len, pos) {
  17556. var s1 = (adler & 0xffff) |0
  17557. , s2 = ((adler >>> 16) & 0xffff) |0
  17558. , n = 0;
  17559. while (len !== 0) {
  17560. // Set limit ~ twice less than 5552, to keep
  17561. // s2 in 31-bits, because we force signed ints.
  17562. // in other case %= will fail.
  17563. n = len > 2000 ? 2000 : len;
  17564. len -= n;
  17565. do {
  17566. s1 = (s1 + buf[pos++]) |0;
  17567. s2 = (s2 + s1) |0;
  17568. } while (--n);
  17569. s1 %= 65521;
  17570. s2 %= 65521;
  17571. }
  17572. return (s1 | (s2 << 16)) |0;
  17573. }
  17574. module.exports = adler32;
  17575. },{}],68:[function(require,module,exports){
  17576. module.exports = {
  17577. /* Allowed flush values; see deflate() and inflate() below for details */
  17578. Z_NO_FLUSH: 0,
  17579. Z_PARTIAL_FLUSH: 1,
  17580. Z_SYNC_FLUSH: 2,
  17581. Z_FULL_FLUSH: 3,
  17582. Z_FINISH: 4,
  17583. Z_BLOCK: 5,
  17584. Z_TREES: 6,
  17585. /* Return codes for the compression/decompression functions. Negative values
  17586. * are errors, positive values are used for special but normal events.
  17587. */
  17588. Z_OK: 0,
  17589. Z_STREAM_END: 1,
  17590. Z_NEED_DICT: 2,
  17591. Z_ERRNO: -1,
  17592. Z_STREAM_ERROR: -2,
  17593. Z_DATA_ERROR: -3,
  17594. //Z_MEM_ERROR: -4,
  17595. Z_BUF_ERROR: -5,
  17596. //Z_VERSION_ERROR: -6,
  17597. /* compression levels */
  17598. Z_NO_COMPRESSION: 0,
  17599. Z_BEST_SPEED: 1,
  17600. Z_BEST_COMPRESSION: 9,
  17601. Z_DEFAULT_COMPRESSION: -1,
  17602. Z_FILTERED: 1,
  17603. Z_HUFFMAN_ONLY: 2,
  17604. Z_RLE: 3,
  17605. Z_FIXED: 4,
  17606. Z_DEFAULT_STRATEGY: 0,
  17607. /* Possible values of the data_type field (though see inflate()) */
  17608. Z_BINARY: 0,
  17609. Z_TEXT: 1,
  17610. //Z_ASCII: 1, // = Z_TEXT (deprecated)
  17611. Z_UNKNOWN: 2,
  17612. /* The deflate compression method */
  17613. Z_DEFLATED: 8
  17614. //Z_NULL: null // Use -1 or null inline, depending on var type
  17615. };
  17616. },{}],69:[function(require,module,exports){
  17617. 'use strict';
  17618. // Note: we can't get significant speed boost here.
  17619. // So write code to minimize size - no pregenerated tables
  17620. // and array tools dependencies.
  17621. // Use ordinary array, since untyped makes no boost here
  17622. function makeTable() {
  17623. var c, table = [];
  17624. for(var n =0; n < 256; n++){
  17625. c = n;
  17626. for(var k =0; k < 8; k++){
  17627. c = ((c&1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1));
  17628. }
  17629. table[n] = c;
  17630. }
  17631. return table;
  17632. }
  17633. // Create table on load. Just 255 signed longs. Not a problem.
  17634. var crcTable = makeTable();
  17635. function crc32(crc, buf, len, pos) {
  17636. var t = crcTable
  17637. , end = pos + len;
  17638. crc = crc ^ (-1);
  17639. for (var i = pos; i < end; i++ ) {
  17640. crc = (crc >>> 8) ^ t[(crc ^ buf[i]) & 0xFF];
  17641. }
  17642. return (crc ^ (-1)); // >>> 0;
  17643. }
  17644. module.exports = crc32;
  17645. },{}],70:[function(require,module,exports){
  17646. 'use strict';
  17647. var utils = require('../utils/common');
  17648. var trees = require('./trees');
  17649. var adler32 = require('./adler32');
  17650. var crc32 = require('./crc32');
  17651. var msg = require('./messages');
  17652. /* Public constants ==========================================================*/
  17653. /* ===========================================================================*/
  17654. /* Allowed flush values; see deflate() and inflate() below for details */
  17655. var Z_NO_FLUSH = 0;
  17656. var Z_PARTIAL_FLUSH = 1;
  17657. //var Z_SYNC_FLUSH = 2;
  17658. var Z_FULL_FLUSH = 3;
  17659. var Z_FINISH = 4;
  17660. var Z_BLOCK = 5;
  17661. //var Z_TREES = 6;
  17662. /* Return codes for the compression/decompression functions. Negative values
  17663. * are errors, positive values are used for special but normal events.
  17664. */
  17665. var Z_OK = 0;
  17666. var Z_STREAM_END = 1;
  17667. //var Z_NEED_DICT = 2;
  17668. //var Z_ERRNO = -1;
  17669. var Z_STREAM_ERROR = -2;
  17670. var Z_DATA_ERROR = -3;
  17671. //var Z_MEM_ERROR = -4;
  17672. var Z_BUF_ERROR = -5;
  17673. //var Z_VERSION_ERROR = -6;
  17674. /* compression levels */
  17675. //var Z_NO_COMPRESSION = 0;
  17676. //var Z_BEST_SPEED = 1;
  17677. //var Z_BEST_COMPRESSION = 9;
  17678. var Z_DEFAULT_COMPRESSION = -1;
  17679. var Z_FILTERED = 1;
  17680. var Z_HUFFMAN_ONLY = 2;
  17681. var Z_RLE = 3;
  17682. var Z_FIXED = 4;
  17683. var Z_DEFAULT_STRATEGY = 0;
  17684. /* Possible values of the data_type field (though see inflate()) */
  17685. //var Z_BINARY = 0;
  17686. //var Z_TEXT = 1;
  17687. //var Z_ASCII = 1; // = Z_TEXT
  17688. var Z_UNKNOWN = 2;
  17689. /* The deflate compression method */
  17690. var Z_DEFLATED = 8;
  17691. /*============================================================================*/
  17692. var MAX_MEM_LEVEL = 9;
  17693. /* Maximum value for memLevel in deflateInit2 */
  17694. var MAX_WBITS = 15;
  17695. /* 32K LZ77 window */
  17696. var DEF_MEM_LEVEL = 8;
  17697. var LENGTH_CODES = 29;
  17698. /* number of length codes, not counting the special END_BLOCK code */
  17699. var LITERALS = 256;
  17700. /* number of literal bytes 0..255 */
  17701. var L_CODES = LITERALS + 1 + LENGTH_CODES;
  17702. /* number of Literal or Length codes, including the END_BLOCK code */
  17703. var D_CODES = 30;
  17704. /* number of distance codes */
  17705. var BL_CODES = 19;
  17706. /* number of codes used to transfer the bit lengths */
  17707. var HEAP_SIZE = 2*L_CODES + 1;
  17708. /* maximum heap size */
  17709. var MAX_BITS = 15;
  17710. /* All codes must not exceed MAX_BITS bits */
  17711. var MIN_MATCH = 3;
  17712. var MAX_MATCH = 258;
  17713. var MIN_LOOKAHEAD = (MAX_MATCH + MIN_MATCH + 1);
  17714. var PRESET_DICT = 0x20;
  17715. var INIT_STATE = 42;
  17716. var EXTRA_STATE = 69;
  17717. var NAME_STATE = 73;
  17718. var COMMENT_STATE = 91;
  17719. var HCRC_STATE = 103;
  17720. var BUSY_STATE = 113;
  17721. var FINISH_STATE = 666;
  17722. var BS_NEED_MORE = 1; /* block not completed, need more input or more output */
  17723. var BS_BLOCK_DONE = 2; /* block flush performed */
  17724. var BS_FINISH_STARTED = 3; /* finish started, need only more output at next deflate */
  17725. var BS_FINISH_DONE = 4; /* finish done, accept no more input or output */
  17726. var OS_CODE = 0x03; // Unix :) . Don't detect, use this default.
  17727. function err(strm, errorCode) {
  17728. strm.msg = msg[errorCode];
  17729. return errorCode;
  17730. }
  17731. function rank(f) {
  17732. return ((f) << 1) - ((f) > 4 ? 9 : 0);
  17733. }
  17734. function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
  17735. /* =========================================================================
  17736. * Flush as much pending output as possible. All deflate() output goes
  17737. * through this function so some applications may wish to modify it
  17738. * to avoid allocating a large strm->output buffer and copying into it.
  17739. * (See also read_buf()).
  17740. */
  17741. function flush_pending(strm) {
  17742. var s = strm.state;
  17743. //_tr_flush_bits(s);
  17744. var len = s.pending;
  17745. if (len > strm.avail_out) {
  17746. len = strm.avail_out;
  17747. }
  17748. if (len === 0) { return; }
  17749. utils.arraySet(strm.output, s.pending_buf, s.pending_out, len, strm.next_out);
  17750. strm.next_out += len;
  17751. s.pending_out += len;
  17752. strm.total_out += len;
  17753. strm.avail_out -= len;
  17754. s.pending -= len;
  17755. if (s.pending === 0) {
  17756. s.pending_out = 0;
  17757. }
  17758. }
  17759. function flush_block_only (s, last) {
  17760. trees._tr_flush_block(s, (s.block_start >= 0 ? s.block_start : -1), s.strstart - s.block_start, last);
  17761. s.block_start = s.strstart;
  17762. flush_pending(s.strm);
  17763. }
  17764. function put_byte(s, b) {
  17765. s.pending_buf[s.pending++] = b;
  17766. }
  17767. /* =========================================================================
  17768. * Put a short in the pending buffer. The 16-bit value is put in MSB order.
  17769. * IN assertion: the stream state is correct and there is enough room in
  17770. * pending_buf.
  17771. */
  17772. function putShortMSB(s, b) {
  17773. // put_byte(s, (Byte)(b >> 8));
  17774. // put_byte(s, (Byte)(b & 0xff));
  17775. s.pending_buf[s.pending++] = (b >>> 8) & 0xff;
  17776. s.pending_buf[s.pending++] = b & 0xff;
  17777. }
  17778. /* ===========================================================================
  17779. * Read a new buffer from the current input stream, update the adler32
  17780. * and total number of bytes read. All deflate() input goes through
  17781. * this function so some applications may wish to modify it to avoid
  17782. * allocating a large strm->input buffer and copying from it.
  17783. * (See also flush_pending()).
  17784. */
  17785. function read_buf(strm, buf, start, size) {
  17786. var len = strm.avail_in;
  17787. if (len > size) { len = size; }
  17788. if (len === 0) { return 0; }
  17789. strm.avail_in -= len;
  17790. utils.arraySet(buf, strm.input, strm.next_in, len, start);
  17791. if (strm.state.wrap === 1) {
  17792. strm.adler = adler32(strm.adler, buf, len, start);
  17793. }
  17794. else if (strm.state.wrap === 2) {
  17795. strm.adler = crc32(strm.adler, buf, len, start);
  17796. }
  17797. strm.next_in += len;
  17798. strm.total_in += len;
  17799. return len;
  17800. }
  17801. /* ===========================================================================
  17802. * Set match_start to the longest match starting at the given string and
  17803. * return its length. Matches shorter or equal to prev_length are discarded,
  17804. * in which case the result is equal to prev_length and match_start is
  17805. * garbage.
  17806. * IN assertions: cur_match is the head of the hash chain for the current
  17807. * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
  17808. * OUT assertion: the match length is not greater than s->lookahead.
  17809. */
  17810. function longest_match(s, cur_match) {
  17811. var chain_length = s.max_chain_length; /* max hash chain length */
  17812. var scan = s.strstart; /* current string */
  17813. var match; /* matched string */
  17814. var len; /* length of current match */
  17815. var best_len = s.prev_length; /* best match length so far */
  17816. var nice_match = s.nice_match; /* stop if match long enough */
  17817. var limit = (s.strstart > (s.w_size - MIN_LOOKAHEAD)) ?
  17818. s.strstart - (s.w_size - MIN_LOOKAHEAD) : 0/*NIL*/;
  17819. var _win = s.window; // shortcut
  17820. var wmask = s.w_mask;
  17821. var prev = s.prev;
  17822. /* Stop when cur_match becomes <= limit. To simplify the code,
  17823. * we prevent matches with the string of window index 0.
  17824. */
  17825. var strend = s.strstart + MAX_MATCH;
  17826. var scan_end1 = _win[scan + best_len - 1];
  17827. var scan_end = _win[scan + best_len];
  17828. /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
  17829. * It is easy to get rid of this optimization if necessary.
  17830. */
  17831. // Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
  17832. /* Do not waste too much time if we already have a good match: */
  17833. if (s.prev_length >= s.good_match) {
  17834. chain_length >>= 2;
  17835. }
  17836. /* Do not look for matches beyond the end of the input. This is necessary
  17837. * to make deflate deterministic.
  17838. */
  17839. if (nice_match > s.lookahead) { nice_match = s.lookahead; }
  17840. // Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
  17841. do {
  17842. // Assert(cur_match < s->strstart, "no future");
  17843. match = cur_match;
  17844. /* Skip to next match if the match length cannot increase
  17845. * or if the match length is less than 2. Note that the checks below
  17846. * for insufficient lookahead only occur occasionally for performance
  17847. * reasons. Therefore uninitialized memory will be accessed, and
  17848. * conditional jumps will be made that depend on those values.
  17849. * However the length of the match is limited to the lookahead, so
  17850. * the output of deflate is not affected by the uninitialized values.
  17851. */
  17852. if (_win[match + best_len] !== scan_end ||
  17853. _win[match + best_len - 1] !== scan_end1 ||
  17854. _win[match] !== _win[scan] ||
  17855. _win[++match] !== _win[scan + 1]) {
  17856. continue;
  17857. }
  17858. /* The check at best_len-1 can be removed because it will be made
  17859. * again later. (This heuristic is not always a win.)
  17860. * It is not necessary to compare scan[2] and match[2] since they
  17861. * are always equal when the other bytes match, given that
  17862. * the hash keys are equal and that HASH_BITS >= 8.
  17863. */
  17864. scan += 2;
  17865. match++;
  17866. // Assert(*scan == *match, "match[2]?");
  17867. /* We check for insufficient lookahead only every 8th comparison;
  17868. * the 256th check will be made at strstart+258.
  17869. */
  17870. do {
  17871. /*jshint noempty:false*/
  17872. } while (_win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  17873. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  17874. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  17875. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  17876. scan < strend);
  17877. // Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  17878. len = MAX_MATCH - (strend - scan);
  17879. scan = strend - MAX_MATCH;
  17880. if (len > best_len) {
  17881. s.match_start = cur_match;
  17882. best_len = len;
  17883. if (len >= nice_match) {
  17884. break;
  17885. }
  17886. scan_end1 = _win[scan + best_len - 1];
  17887. scan_end = _win[scan + best_len];
  17888. }
  17889. } while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length !== 0);
  17890. if (best_len <= s.lookahead) {
  17891. return best_len;
  17892. }
  17893. return s.lookahead;
  17894. }
  17895. /* ===========================================================================
  17896. * Fill the window when the lookahead becomes insufficient.
  17897. * Updates strstart and lookahead.
  17898. *
  17899. * IN assertion: lookahead < MIN_LOOKAHEAD
  17900. * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
  17901. * At least one byte has been read, or avail_in == 0; reads are
  17902. * performed for at least two bytes (required for the zip translate_eol
  17903. * option -- not supported here).
  17904. */
  17905. function fill_window(s) {
  17906. var _w_size = s.w_size;
  17907. var p, n, m, more, str;
  17908. //Assert(s->lookahead < MIN_LOOKAHEAD, "already enough lookahead");
  17909. do {
  17910. more = s.window_size - s.lookahead - s.strstart;
  17911. // JS ints have 32 bit, block below not needed
  17912. /* Deal with !@#$% 64K limit: */
  17913. //if (sizeof(int) <= 2) {
  17914. // if (more == 0 && s->strstart == 0 && s->lookahead == 0) {
  17915. // more = wsize;
  17916. //
  17917. // } else if (more == (unsigned)(-1)) {
  17918. // /* Very unlikely, but possible on 16 bit machine if
  17919. // * strstart == 0 && lookahead == 1 (input done a byte at time)
  17920. // */
  17921. // more--;
  17922. // }
  17923. //}
  17924. /* If the window is almost full and there is insufficient lookahead,
  17925. * move the upper half to the lower one to make room in the upper half.
  17926. */
  17927. if (s.strstart >= _w_size + (_w_size - MIN_LOOKAHEAD)) {
  17928. utils.arraySet(s.window, s.window, _w_size, _w_size, 0);
  17929. s.match_start -= _w_size;
  17930. s.strstart -= _w_size;
  17931. /* we now have strstart >= MAX_DIST */
  17932. s.block_start -= _w_size;
  17933. /* Slide the hash table (could be avoided with 32 bit values
  17934. at the expense of memory usage). We slide even when level == 0
  17935. to keep the hash table consistent if we switch back to level > 0
  17936. later. (Using level 0 permanently is not an optimal usage of
  17937. zlib, so we don't care about this pathological case.)
  17938. */
  17939. n = s.hash_size;
  17940. p = n;
  17941. do {
  17942. m = s.head[--p];
  17943. s.head[p] = (m >= _w_size ? m - _w_size : 0);
  17944. } while (--n);
  17945. n = _w_size;
  17946. p = n;
  17947. do {
  17948. m = s.prev[--p];
  17949. s.prev[p] = (m >= _w_size ? m - _w_size : 0);
  17950. /* If n is not on any hash chain, prev[n] is garbage but
  17951. * its value will never be used.
  17952. */
  17953. } while (--n);
  17954. more += _w_size;
  17955. }
  17956. if (s.strm.avail_in === 0) {
  17957. break;
  17958. }
  17959. /* If there was no sliding:
  17960. * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
  17961. * more == window_size - lookahead - strstart
  17962. * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
  17963. * => more >= window_size - 2*WSIZE + 2
  17964. * In the BIG_MEM or MMAP case (not yet supported),
  17965. * window_size == input_size + MIN_LOOKAHEAD &&
  17966. * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
  17967. * Otherwise, window_size == 2*WSIZE so more >= 2.
  17968. * If there was sliding, more >= WSIZE. So in all cases, more >= 2.
  17969. */
  17970. //Assert(more >= 2, "more < 2");
  17971. n = read_buf(s.strm, s.window, s.strstart + s.lookahead, more);
  17972. s.lookahead += n;
  17973. /* Initialize the hash value now that we have some input: */
  17974. if (s.lookahead + s.insert >= MIN_MATCH) {
  17975. str = s.strstart - s.insert;
  17976. s.ins_h = s.window[str];
  17977. /* UPDATE_HASH(s, s->ins_h, s->window[str + 1]); */
  17978. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + 1]) & s.hash_mask;
  17979. //#if MIN_MATCH != 3
  17980. // Call update_hash() MIN_MATCH-3 more times
  17981. //#endif
  17982. while (s.insert) {
  17983. /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */
  17984. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH-1]) & s.hash_mask;
  17985. s.prev[str & s.w_mask] = s.head[s.ins_h];
  17986. s.head[s.ins_h] = str;
  17987. str++;
  17988. s.insert--;
  17989. if (s.lookahead + s.insert < MIN_MATCH) {
  17990. break;
  17991. }
  17992. }
  17993. }
  17994. /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,
  17995. * but this is not important since only literal bytes will be emitted.
  17996. */
  17997. } while (s.lookahead < MIN_LOOKAHEAD && s.strm.avail_in !== 0);
  17998. /* If the WIN_INIT bytes after the end of the current data have never been
  17999. * written, then zero those bytes in order to avoid memory check reports of
  18000. * the use of uninitialized (or uninitialised as Julian writes) bytes by
  18001. * the longest match routines. Update the high water mark for the next
  18002. * time through here. WIN_INIT is set to MAX_MATCH since the longest match
  18003. * routines allow scanning to strstart + MAX_MATCH, ignoring lookahead.
  18004. */
  18005. // if (s.high_water < s.window_size) {
  18006. // var curr = s.strstart + s.lookahead;
  18007. // var init = 0;
  18008. //
  18009. // if (s.high_water < curr) {
  18010. // /* Previous high water mark below current data -- zero WIN_INIT
  18011. // * bytes or up to end of window, whichever is less.
  18012. // */
  18013. // init = s.window_size - curr;
  18014. // if (init > WIN_INIT)
  18015. // init = WIN_INIT;
  18016. // zmemzero(s->window + curr, (unsigned)init);
  18017. // s->high_water = curr + init;
  18018. // }
  18019. // else if (s->high_water < (ulg)curr + WIN_INIT) {
  18020. // /* High water mark at or above current data, but below current data
  18021. // * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up
  18022. // * to end of window, whichever is less.
  18023. // */
  18024. // init = (ulg)curr + WIN_INIT - s->high_water;
  18025. // if (init > s->window_size - s->high_water)
  18026. // init = s->window_size - s->high_water;
  18027. // zmemzero(s->window + s->high_water, (unsigned)init);
  18028. // s->high_water += init;
  18029. // }
  18030. // }
  18031. //
  18032. // Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD,
  18033. // "not enough room for search");
  18034. }
  18035. /* ===========================================================================
  18036. * Copy without compression as much as possible from the input stream, return
  18037. * the current block state.
  18038. * This function does not insert new strings in the dictionary since
  18039. * uncompressible data is probably not useful. This function is used
  18040. * only for the level=0 compression option.
  18041. * NOTE: this function should be optimized to avoid extra copying from
  18042. * window to pending_buf.
  18043. */
  18044. function deflate_stored(s, flush) {
  18045. /* Stored blocks are limited to 0xffff bytes, pending_buf is limited
  18046. * to pending_buf_size, and each stored block has a 5 byte header:
  18047. */
  18048. var max_block_size = 0xffff;
  18049. if (max_block_size > s.pending_buf_size - 5) {
  18050. max_block_size = s.pending_buf_size - 5;
  18051. }
  18052. /* Copy as much as possible from input to output: */
  18053. for (;;) {
  18054. /* Fill the window as much as possible: */
  18055. if (s.lookahead <= 1) {
  18056. //Assert(s->strstart < s->w_size+MAX_DIST(s) ||
  18057. // s->block_start >= (long)s->w_size, "slide too late");
  18058. // if (!(s.strstart < s.w_size + (s.w_size - MIN_LOOKAHEAD) ||
  18059. // s.block_start >= s.w_size)) {
  18060. // throw new Error("slide too late");
  18061. // }
  18062. fill_window(s);
  18063. if (s.lookahead === 0 && flush === Z_NO_FLUSH) {
  18064. return BS_NEED_MORE;
  18065. }
  18066. if (s.lookahead === 0) {
  18067. break;
  18068. }
  18069. /* flush the current block */
  18070. }
  18071. //Assert(s->block_start >= 0L, "block gone");
  18072. // if (s.block_start < 0) throw new Error("block gone");
  18073. s.strstart += s.lookahead;
  18074. s.lookahead = 0;
  18075. /* Emit a stored block if pending_buf will be full: */
  18076. var max_start = s.block_start + max_block_size;
  18077. if (s.strstart === 0 || s.strstart >= max_start) {
  18078. /* strstart == 0 is possible when wraparound on 16-bit machine */
  18079. s.lookahead = s.strstart - max_start;
  18080. s.strstart = max_start;
  18081. /*** FLUSH_BLOCK(s, 0); ***/
  18082. flush_block_only(s, false);
  18083. if (s.strm.avail_out === 0) {
  18084. return BS_NEED_MORE;
  18085. }
  18086. /***/
  18087. }
  18088. /* Flush if we may have to slide, otherwise block_start may become
  18089. * negative and the data will be gone:
  18090. */
  18091. if (s.strstart - s.block_start >= (s.w_size - MIN_LOOKAHEAD)) {
  18092. /*** FLUSH_BLOCK(s, 0); ***/
  18093. flush_block_only(s, false);
  18094. if (s.strm.avail_out === 0) {
  18095. return BS_NEED_MORE;
  18096. }
  18097. /***/
  18098. }
  18099. }
  18100. s.insert = 0;
  18101. if (flush === Z_FINISH) {
  18102. /*** FLUSH_BLOCK(s, 1); ***/
  18103. flush_block_only(s, true);
  18104. if (s.strm.avail_out === 0) {
  18105. return BS_FINISH_STARTED;
  18106. }
  18107. /***/
  18108. return BS_FINISH_DONE;
  18109. }
  18110. if (s.strstart > s.block_start) {
  18111. /*** FLUSH_BLOCK(s, 0); ***/
  18112. flush_block_only(s, false);
  18113. if (s.strm.avail_out === 0) {
  18114. return BS_NEED_MORE;
  18115. }
  18116. /***/
  18117. }
  18118. return BS_NEED_MORE;
  18119. }
  18120. /* ===========================================================================
  18121. * Compress as much as possible from the input stream, return the current
  18122. * block state.
  18123. * This function does not perform lazy evaluation of matches and inserts
  18124. * new strings in the dictionary only for unmatched strings or for short
  18125. * matches. It is used only for the fast compression options.
  18126. */
  18127. function deflate_fast(s, flush) {
  18128. var hash_head; /* head of the hash chain */
  18129. var bflush; /* set if current block must be flushed */
  18130. for (;;) {
  18131. /* Make sure that we always have enough lookahead, except
  18132. * at the end of the input file. We need MAX_MATCH bytes
  18133. * for the next match, plus MIN_MATCH bytes to insert the
  18134. * string following the next match.
  18135. */
  18136. if (s.lookahead < MIN_LOOKAHEAD) {
  18137. fill_window(s);
  18138. if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
  18139. return BS_NEED_MORE;
  18140. }
  18141. if (s.lookahead === 0) {
  18142. break; /* flush the current block */
  18143. }
  18144. }
  18145. /* Insert the string window[strstart .. strstart+2] in the
  18146. * dictionary, and set hash_head to the head of the hash chain:
  18147. */
  18148. hash_head = 0/*NIL*/;
  18149. if (s.lookahead >= MIN_MATCH) {
  18150. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  18151. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  18152. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  18153. s.head[s.ins_h] = s.strstart;
  18154. /***/
  18155. }
  18156. /* Find the longest match, discarding those <= prev_length.
  18157. * At this point we have always match_length < MIN_MATCH
  18158. */
  18159. if (hash_head !== 0/*NIL*/ && ((s.strstart - hash_head) <= (s.w_size - MIN_LOOKAHEAD))) {
  18160. /* To simplify the code, we prevent matches with the string
  18161. * of window index 0 (in particular we have to avoid a match
  18162. * of the string with itself at the start of the input file).
  18163. */
  18164. s.match_length = longest_match(s, hash_head);
  18165. /* longest_match() sets match_start */
  18166. }
  18167. if (s.match_length >= MIN_MATCH) {
  18168. // check_match(s, s.strstart, s.match_start, s.match_length); // for debug only
  18169. /*** _tr_tally_dist(s, s.strstart - s.match_start,
  18170. s.match_length - MIN_MATCH, bflush); ***/
  18171. bflush = trees._tr_tally(s, s.strstart - s.match_start, s.match_length - MIN_MATCH);
  18172. s.lookahead -= s.match_length;
  18173. /* Insert new strings in the hash table only if the match length
  18174. * is not too large. This saves time but degrades compression.
  18175. */
  18176. if (s.match_length <= s.max_lazy_match/*max_insert_length*/ && s.lookahead >= MIN_MATCH) {
  18177. s.match_length--; /* string at strstart already in table */
  18178. do {
  18179. s.strstart++;
  18180. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  18181. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  18182. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  18183. s.head[s.ins_h] = s.strstart;
  18184. /***/
  18185. /* strstart never exceeds WSIZE-MAX_MATCH, so there are
  18186. * always MIN_MATCH bytes ahead.
  18187. */
  18188. } while (--s.match_length !== 0);
  18189. s.strstart++;
  18190. } else
  18191. {
  18192. s.strstart += s.match_length;
  18193. s.match_length = 0;
  18194. s.ins_h = s.window[s.strstart];
  18195. /* UPDATE_HASH(s, s.ins_h, s.window[s.strstart+1]); */
  18196. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + 1]) & s.hash_mask;
  18197. //#if MIN_MATCH != 3
  18198. // Call UPDATE_HASH() MIN_MATCH-3 more times
  18199. //#endif
  18200. /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not
  18201. * matter since it will be recomputed at next deflate call.
  18202. */
  18203. }
  18204. } else {
  18205. /* No match, output a literal byte */
  18206. //Tracevv((stderr,"%c", s.window[s.strstart]));
  18207. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  18208. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  18209. s.lookahead--;
  18210. s.strstart++;
  18211. }
  18212. if (bflush) {
  18213. /*** FLUSH_BLOCK(s, 0); ***/
  18214. flush_block_only(s, false);
  18215. if (s.strm.avail_out === 0) {
  18216. return BS_NEED_MORE;
  18217. }
  18218. /***/
  18219. }
  18220. }
  18221. s.insert = ((s.strstart < (MIN_MATCH-1)) ? s.strstart : MIN_MATCH-1);
  18222. if (flush === Z_FINISH) {
  18223. /*** FLUSH_BLOCK(s, 1); ***/
  18224. flush_block_only(s, true);
  18225. if (s.strm.avail_out === 0) {
  18226. return BS_FINISH_STARTED;
  18227. }
  18228. /***/
  18229. return BS_FINISH_DONE;
  18230. }
  18231. if (s.last_lit) {
  18232. /*** FLUSH_BLOCK(s, 0); ***/
  18233. flush_block_only(s, false);
  18234. if (s.strm.avail_out === 0) {
  18235. return BS_NEED_MORE;
  18236. }
  18237. /***/
  18238. }
  18239. return BS_BLOCK_DONE;
  18240. }
  18241. /* ===========================================================================
  18242. * Same as above, but achieves better compression. We use a lazy
  18243. * evaluation for matches: a match is finally adopted only if there is
  18244. * no better match at the next window position.
  18245. */
  18246. function deflate_slow(s, flush) {
  18247. var hash_head; /* head of hash chain */
  18248. var bflush; /* set if current block must be flushed */
  18249. var max_insert;
  18250. /* Process the input block. */
  18251. for (;;) {
  18252. /* Make sure that we always have enough lookahead, except
  18253. * at the end of the input file. We need MAX_MATCH bytes
  18254. * for the next match, plus MIN_MATCH bytes to insert the
  18255. * string following the next match.
  18256. */
  18257. if (s.lookahead < MIN_LOOKAHEAD) {
  18258. fill_window(s);
  18259. if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
  18260. return BS_NEED_MORE;
  18261. }
  18262. if (s.lookahead === 0) { break; } /* flush the current block */
  18263. }
  18264. /* Insert the string window[strstart .. strstart+2] in the
  18265. * dictionary, and set hash_head to the head of the hash chain:
  18266. */
  18267. hash_head = 0/*NIL*/;
  18268. if (s.lookahead >= MIN_MATCH) {
  18269. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  18270. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  18271. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  18272. s.head[s.ins_h] = s.strstart;
  18273. /***/
  18274. }
  18275. /* Find the longest match, discarding those <= prev_length.
  18276. */
  18277. s.prev_length = s.match_length;
  18278. s.prev_match = s.match_start;
  18279. s.match_length = MIN_MATCH-1;
  18280. if (hash_head !== 0/*NIL*/ && s.prev_length < s.max_lazy_match &&
  18281. s.strstart - hash_head <= (s.w_size-MIN_LOOKAHEAD)/*MAX_DIST(s)*/) {
  18282. /* To simplify the code, we prevent matches with the string
  18283. * of window index 0 (in particular we have to avoid a match
  18284. * of the string with itself at the start of the input file).
  18285. */
  18286. s.match_length = longest_match(s, hash_head);
  18287. /* longest_match() sets match_start */
  18288. if (s.match_length <= 5 &&
  18289. (s.strategy === Z_FILTERED || (s.match_length === MIN_MATCH && s.strstart - s.match_start > 4096/*TOO_FAR*/))) {
  18290. /* If prev_match is also MIN_MATCH, match_start is garbage
  18291. * but we will ignore the current match anyway.
  18292. */
  18293. s.match_length = MIN_MATCH-1;
  18294. }
  18295. }
  18296. /* If there was a match at the previous step and the current
  18297. * match is not better, output the previous match:
  18298. */
  18299. if (s.prev_length >= MIN_MATCH && s.match_length <= s.prev_length) {
  18300. max_insert = s.strstart + s.lookahead - MIN_MATCH;
  18301. /* Do not insert strings in hash table beyond this. */
  18302. //check_match(s, s.strstart-1, s.prev_match, s.prev_length);
  18303. /***_tr_tally_dist(s, s.strstart - 1 - s.prev_match,
  18304. s.prev_length - MIN_MATCH, bflush);***/
  18305. bflush = trees._tr_tally(s, s.strstart - 1- s.prev_match, s.prev_length - MIN_MATCH);
  18306. /* Insert in hash table all strings up to the end of the match.
  18307. * strstart-1 and strstart are already inserted. If there is not
  18308. * enough lookahead, the last two strings are not inserted in
  18309. * the hash table.
  18310. */
  18311. s.lookahead -= s.prev_length-1;
  18312. s.prev_length -= 2;
  18313. do {
  18314. if (++s.strstart <= max_insert) {
  18315. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  18316. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  18317. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  18318. s.head[s.ins_h] = s.strstart;
  18319. /***/
  18320. }
  18321. } while (--s.prev_length !== 0);
  18322. s.match_available = 0;
  18323. s.match_length = MIN_MATCH-1;
  18324. s.strstart++;
  18325. if (bflush) {
  18326. /*** FLUSH_BLOCK(s, 0); ***/
  18327. flush_block_only(s, false);
  18328. if (s.strm.avail_out === 0) {
  18329. return BS_NEED_MORE;
  18330. }
  18331. /***/
  18332. }
  18333. } else if (s.match_available) {
  18334. /* If there was no match at the previous position, output a
  18335. * single literal. If there was a match but the current match
  18336. * is longer, truncate the previous match to a single literal.
  18337. */
  18338. //Tracevv((stderr,"%c", s->window[s->strstart-1]));
  18339. /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
  18340. bflush = trees._tr_tally(s, 0, s.window[s.strstart-1]);
  18341. if (bflush) {
  18342. /*** FLUSH_BLOCK_ONLY(s, 0) ***/
  18343. flush_block_only(s, false);
  18344. /***/
  18345. }
  18346. s.strstart++;
  18347. s.lookahead--;
  18348. if (s.strm.avail_out === 0) {
  18349. return BS_NEED_MORE;
  18350. }
  18351. } else {
  18352. /* There is no previous match to compare with, wait for
  18353. * the next step to decide.
  18354. */
  18355. s.match_available = 1;
  18356. s.strstart++;
  18357. s.lookahead--;
  18358. }
  18359. }
  18360. //Assert (flush != Z_NO_FLUSH, "no flush?");
  18361. if (s.match_available) {
  18362. //Tracevv((stderr,"%c", s->window[s->strstart-1]));
  18363. /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
  18364. bflush = trees._tr_tally(s, 0, s.window[s.strstart-1]);
  18365. s.match_available = 0;
  18366. }
  18367. s.insert = s.strstart < MIN_MATCH-1 ? s.strstart : MIN_MATCH-1;
  18368. if (flush === Z_FINISH) {
  18369. /*** FLUSH_BLOCK(s, 1); ***/
  18370. flush_block_only(s, true);
  18371. if (s.strm.avail_out === 0) {
  18372. return BS_FINISH_STARTED;
  18373. }
  18374. /***/
  18375. return BS_FINISH_DONE;
  18376. }
  18377. if (s.last_lit) {
  18378. /*** FLUSH_BLOCK(s, 0); ***/
  18379. flush_block_only(s, false);
  18380. if (s.strm.avail_out === 0) {
  18381. return BS_NEED_MORE;
  18382. }
  18383. /***/
  18384. }
  18385. return BS_BLOCK_DONE;
  18386. }
  18387. /* ===========================================================================
  18388. * For Z_RLE, simply look for runs of bytes, generate matches only of distance
  18389. * one. Do not maintain a hash table. (It will be regenerated if this run of
  18390. * deflate switches away from Z_RLE.)
  18391. */
  18392. function deflate_rle(s, flush) {
  18393. var bflush; /* set if current block must be flushed */
  18394. var prev; /* byte at distance one to match */
  18395. var scan, strend; /* scan goes up to strend for length of run */
  18396. var _win = s.window;
  18397. for (;;) {
  18398. /* Make sure that we always have enough lookahead, except
  18399. * at the end of the input file. We need MAX_MATCH bytes
  18400. * for the longest run, plus one for the unrolled loop.
  18401. */
  18402. if (s.lookahead <= MAX_MATCH) {
  18403. fill_window(s);
  18404. if (s.lookahead <= MAX_MATCH && flush === Z_NO_FLUSH) {
  18405. return BS_NEED_MORE;
  18406. }
  18407. if (s.lookahead === 0) { break; } /* flush the current block */
  18408. }
  18409. /* See how many times the previous byte repeats */
  18410. s.match_length = 0;
  18411. if (s.lookahead >= MIN_MATCH && s.strstart > 0) {
  18412. scan = s.strstart - 1;
  18413. prev = _win[scan];
  18414. if (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan]) {
  18415. strend = s.strstart + MAX_MATCH;
  18416. do {
  18417. /*jshint noempty:false*/
  18418. } while (prev === _win[++scan] && prev === _win[++scan] &&
  18419. prev === _win[++scan] && prev === _win[++scan] &&
  18420. prev === _win[++scan] && prev === _win[++scan] &&
  18421. prev === _win[++scan] && prev === _win[++scan] &&
  18422. scan < strend);
  18423. s.match_length = MAX_MATCH - (strend - scan);
  18424. if (s.match_length > s.lookahead) {
  18425. s.match_length = s.lookahead;
  18426. }
  18427. }
  18428. //Assert(scan <= s->window+(uInt)(s->window_size-1), "wild scan");
  18429. }
  18430. /* Emit match if have run of MIN_MATCH or longer, else emit literal */
  18431. if (s.match_length >= MIN_MATCH) {
  18432. //check_match(s, s.strstart, s.strstart - 1, s.match_length);
  18433. /*** _tr_tally_dist(s, 1, s.match_length - MIN_MATCH, bflush); ***/
  18434. bflush = trees._tr_tally(s, 1, s.match_length - MIN_MATCH);
  18435. s.lookahead -= s.match_length;
  18436. s.strstart += s.match_length;
  18437. s.match_length = 0;
  18438. } else {
  18439. /* No match, output a literal byte */
  18440. //Tracevv((stderr,"%c", s->window[s->strstart]));
  18441. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  18442. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  18443. s.lookahead--;
  18444. s.strstart++;
  18445. }
  18446. if (bflush) {
  18447. /*** FLUSH_BLOCK(s, 0); ***/
  18448. flush_block_only(s, false);
  18449. if (s.strm.avail_out === 0) {
  18450. return BS_NEED_MORE;
  18451. }
  18452. /***/
  18453. }
  18454. }
  18455. s.insert = 0;
  18456. if (flush === Z_FINISH) {
  18457. /*** FLUSH_BLOCK(s, 1); ***/
  18458. flush_block_only(s, true);
  18459. if (s.strm.avail_out === 0) {
  18460. return BS_FINISH_STARTED;
  18461. }
  18462. /***/
  18463. return BS_FINISH_DONE;
  18464. }
  18465. if (s.last_lit) {
  18466. /*** FLUSH_BLOCK(s, 0); ***/
  18467. flush_block_only(s, false);
  18468. if (s.strm.avail_out === 0) {
  18469. return BS_NEED_MORE;
  18470. }
  18471. /***/
  18472. }
  18473. return BS_BLOCK_DONE;
  18474. }
  18475. /* ===========================================================================
  18476. * For Z_HUFFMAN_ONLY, do not look for matches. Do not maintain a hash table.
  18477. * (It will be regenerated if this run of deflate switches away from Huffman.)
  18478. */
  18479. function deflate_huff(s, flush) {
  18480. var bflush; /* set if current block must be flushed */
  18481. for (;;) {
  18482. /* Make sure that we have a literal to write. */
  18483. if (s.lookahead === 0) {
  18484. fill_window(s);
  18485. if (s.lookahead === 0) {
  18486. if (flush === Z_NO_FLUSH) {
  18487. return BS_NEED_MORE;
  18488. }
  18489. break; /* flush the current block */
  18490. }
  18491. }
  18492. /* Output a literal byte */
  18493. s.match_length = 0;
  18494. //Tracevv((stderr,"%c", s->window[s->strstart]));
  18495. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  18496. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  18497. s.lookahead--;
  18498. s.strstart++;
  18499. if (bflush) {
  18500. /*** FLUSH_BLOCK(s, 0); ***/
  18501. flush_block_only(s, false);
  18502. if (s.strm.avail_out === 0) {
  18503. return BS_NEED_MORE;
  18504. }
  18505. /***/
  18506. }
  18507. }
  18508. s.insert = 0;
  18509. if (flush === Z_FINISH) {
  18510. /*** FLUSH_BLOCK(s, 1); ***/
  18511. flush_block_only(s, true);
  18512. if (s.strm.avail_out === 0) {
  18513. return BS_FINISH_STARTED;
  18514. }
  18515. /***/
  18516. return BS_FINISH_DONE;
  18517. }
  18518. if (s.last_lit) {
  18519. /*** FLUSH_BLOCK(s, 0); ***/
  18520. flush_block_only(s, false);
  18521. if (s.strm.avail_out === 0) {
  18522. return BS_NEED_MORE;
  18523. }
  18524. /***/
  18525. }
  18526. return BS_BLOCK_DONE;
  18527. }
  18528. /* Values for max_lazy_match, good_match and max_chain_length, depending on
  18529. * the desired pack level (0..9). The values given below have been tuned to
  18530. * exclude worst case performance for pathological files. Better values may be
  18531. * found for specific files.
  18532. */
  18533. var Config = function (good_length, max_lazy, nice_length, max_chain, func) {
  18534. this.good_length = good_length;
  18535. this.max_lazy = max_lazy;
  18536. this.nice_length = nice_length;
  18537. this.max_chain = max_chain;
  18538. this.func = func;
  18539. };
  18540. var configuration_table;
  18541. configuration_table = [
  18542. /* good lazy nice chain */
  18543. new Config(0, 0, 0, 0, deflate_stored), /* 0 store only */
  18544. new Config(4, 4, 8, 4, deflate_fast), /* 1 max speed, no lazy matches */
  18545. new Config(4, 5, 16, 8, deflate_fast), /* 2 */
  18546. new Config(4, 6, 32, 32, deflate_fast), /* 3 */
  18547. new Config(4, 4, 16, 16, deflate_slow), /* 4 lazy matches */
  18548. new Config(8, 16, 32, 32, deflate_slow), /* 5 */
  18549. new Config(8, 16, 128, 128, deflate_slow), /* 6 */
  18550. new Config(8, 32, 128, 256, deflate_slow), /* 7 */
  18551. new Config(32, 128, 258, 1024, deflate_slow), /* 8 */
  18552. new Config(32, 258, 258, 4096, deflate_slow) /* 9 max compression */
  18553. ];
  18554. /* ===========================================================================
  18555. * Initialize the "longest match" routines for a new zlib stream
  18556. */
  18557. function lm_init(s) {
  18558. s.window_size = 2 * s.w_size;
  18559. /*** CLEAR_HASH(s); ***/
  18560. zero(s.head); // Fill with NIL (= 0);
  18561. /* Set the default configuration parameters:
  18562. */
  18563. s.max_lazy_match = configuration_table[s.level].max_lazy;
  18564. s.good_match = configuration_table[s.level].good_length;
  18565. s.nice_match = configuration_table[s.level].nice_length;
  18566. s.max_chain_length = configuration_table[s.level].max_chain;
  18567. s.strstart = 0;
  18568. s.block_start = 0;
  18569. s.lookahead = 0;
  18570. s.insert = 0;
  18571. s.match_length = s.prev_length = MIN_MATCH - 1;
  18572. s.match_available = 0;
  18573. s.ins_h = 0;
  18574. }
  18575. function DeflateState() {
  18576. this.strm = null; /* pointer back to this zlib stream */
  18577. this.status = 0; /* as the name implies */
  18578. this.pending_buf = null; /* output still pending */
  18579. this.pending_buf_size = 0; /* size of pending_buf */
  18580. this.pending_out = 0; /* next pending byte to output to the stream */
  18581. this.pending = 0; /* nb of bytes in the pending buffer */
  18582. this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
  18583. this.gzhead = null; /* gzip header information to write */
  18584. this.gzindex = 0; /* where in extra, name, or comment */
  18585. this.method = Z_DEFLATED; /* can only be DEFLATED */
  18586. this.last_flush = -1; /* value of flush param for previous deflate call */
  18587. this.w_size = 0; /* LZ77 window size (32K by default) */
  18588. this.w_bits = 0; /* log2(w_size) (8..16) */
  18589. this.w_mask = 0; /* w_size - 1 */
  18590. this.window = null;
  18591. /* Sliding window. Input bytes are read into the second half of the window,
  18592. * and move to the first half later to keep a dictionary of at least wSize
  18593. * bytes. With this organization, matches are limited to a distance of
  18594. * wSize-MAX_MATCH bytes, but this ensures that IO is always
  18595. * performed with a length multiple of the block size.
  18596. */
  18597. this.window_size = 0;
  18598. /* Actual size of window: 2*wSize, except when the user input buffer
  18599. * is directly used as sliding window.
  18600. */
  18601. this.prev = null;
  18602. /* Link to older string with same hash index. To limit the size of this
  18603. * array to 64K, this link is maintained only for the last 32K strings.
  18604. * An index in this array is thus a window index modulo 32K.
  18605. */
  18606. this.head = null; /* Heads of the hash chains or NIL. */
  18607. this.ins_h = 0; /* hash index of string to be inserted */
  18608. this.hash_size = 0; /* number of elements in hash table */
  18609. this.hash_bits = 0; /* log2(hash_size) */
  18610. this.hash_mask = 0; /* hash_size-1 */
  18611. this.hash_shift = 0;
  18612. /* Number of bits by which ins_h must be shifted at each input
  18613. * step. It must be such that after MIN_MATCH steps, the oldest
  18614. * byte no longer takes part in the hash key, that is:
  18615. * hash_shift * MIN_MATCH >= hash_bits
  18616. */
  18617. this.block_start = 0;
  18618. /* Window position at the beginning of the current output block. Gets
  18619. * negative when the window is moved backwards.
  18620. */
  18621. this.match_length = 0; /* length of best match */
  18622. this.prev_match = 0; /* previous match */
  18623. this.match_available = 0; /* set if previous match exists */
  18624. this.strstart = 0; /* start of string to insert */
  18625. this.match_start = 0; /* start of matching string */
  18626. this.lookahead = 0; /* number of valid bytes ahead in window */
  18627. this.prev_length = 0;
  18628. /* Length of the best match at previous step. Matches not greater than this
  18629. * are discarded. This is used in the lazy match evaluation.
  18630. */
  18631. this.max_chain_length = 0;
  18632. /* To speed up deflation, hash chains are never searched beyond this
  18633. * length. A higher limit improves compression ratio but degrades the
  18634. * speed.
  18635. */
  18636. this.max_lazy_match = 0;
  18637. /* Attempt to find a better match only when the current match is strictly
  18638. * smaller than this value. This mechanism is used only for compression
  18639. * levels >= 4.
  18640. */
  18641. // That's alias to max_lazy_match, don't use directly
  18642. //this.max_insert_length = 0;
  18643. /* Insert new strings in the hash table only if the match length is not
  18644. * greater than this length. This saves time but degrades compression.
  18645. * max_insert_length is used only for compression levels <= 3.
  18646. */
  18647. this.level = 0; /* compression level (1..9) */
  18648. this.strategy = 0; /* favor or force Huffman coding*/
  18649. this.good_match = 0;
  18650. /* Use a faster search when the previous match is longer than this */
  18651. this.nice_match = 0; /* Stop searching when current match exceeds this */
  18652. /* used by trees.c: */
  18653. /* Didn't use ct_data typedef below to suppress compiler warning */
  18654. // struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */
  18655. // struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */
  18656. // struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */
  18657. // Use flat array of DOUBLE size, with interleaved fata,
  18658. // because JS does not support effective
  18659. this.dyn_ltree = new utils.Buf16(HEAP_SIZE * 2);
  18660. this.dyn_dtree = new utils.Buf16((2*D_CODES+1) * 2);
  18661. this.bl_tree = new utils.Buf16((2*BL_CODES+1) * 2);
  18662. zero(this.dyn_ltree);
  18663. zero(this.dyn_dtree);
  18664. zero(this.bl_tree);
  18665. this.l_desc = null; /* desc. for literal tree */
  18666. this.d_desc = null; /* desc. for distance tree */
  18667. this.bl_desc = null; /* desc. for bit length tree */
  18668. //ush bl_count[MAX_BITS+1];
  18669. this.bl_count = new utils.Buf16(MAX_BITS+1);
  18670. /* number of codes at each bit length for an optimal tree */
  18671. //int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */
  18672. this.heap = new utils.Buf16(2*L_CODES+1); /* heap used to build the Huffman trees */
  18673. zero(this.heap);
  18674. this.heap_len = 0; /* number of elements in the heap */
  18675. this.heap_max = 0; /* element of largest frequency */
  18676. /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.
  18677. * The same heap array is used to build all trees.
  18678. */
  18679. this.depth = new utils.Buf16(2*L_CODES+1); //uch depth[2*L_CODES+1];
  18680. zero(this.depth);
  18681. /* Depth of each subtree used as tie breaker for trees of equal frequency
  18682. */
  18683. this.l_buf = 0; /* buffer index for literals or lengths */
  18684. this.lit_bufsize = 0;
  18685. /* Size of match buffer for literals/lengths. There are 4 reasons for
  18686. * limiting lit_bufsize to 64K:
  18687. * - frequencies can be kept in 16 bit counters
  18688. * - if compression is not successful for the first block, all input
  18689. * data is still in the window so we can still emit a stored block even
  18690. * when input comes from standard input. (This can also be done for
  18691. * all blocks if lit_bufsize is not greater than 32K.)
  18692. * - if compression is not successful for a file smaller than 64K, we can
  18693. * even emit a stored file instead of a stored block (saving 5 bytes).
  18694. * This is applicable only for zip (not gzip or zlib).
  18695. * - creating new Huffman trees less frequently may not provide fast
  18696. * adaptation to changes in the input data statistics. (Take for
  18697. * example a binary file with poorly compressible code followed by
  18698. * a highly compressible string table.) Smaller buffer sizes give
  18699. * fast adaptation but have of course the overhead of transmitting
  18700. * trees more frequently.
  18701. * - I can't count above 4
  18702. */
  18703. this.last_lit = 0; /* running index in l_buf */
  18704. this.d_buf = 0;
  18705. /* Buffer index for distances. To simplify the code, d_buf and l_buf have
  18706. * the same number of elements. To use different lengths, an extra flag
  18707. * array would be necessary.
  18708. */
  18709. this.opt_len = 0; /* bit length of current block with optimal trees */
  18710. this.static_len = 0; /* bit length of current block with static trees */
  18711. this.matches = 0; /* number of string matches in current block */
  18712. this.insert = 0; /* bytes at end of window left to insert */
  18713. this.bi_buf = 0;
  18714. /* Output buffer. bits are inserted starting at the bottom (least
  18715. * significant bits).
  18716. */
  18717. this.bi_valid = 0;
  18718. /* Number of valid bits in bi_buf. All bits above the last valid bit
  18719. * are always zero.
  18720. */
  18721. // Used for window memory init. We safely ignore it for JS. That makes
  18722. // sense only for pointers and memory check tools.
  18723. //this.high_water = 0;
  18724. /* High water mark offset in window for initialized bytes -- bytes above
  18725. * this are set to zero in order to avoid memory check warnings when
  18726. * longest match routines access bytes past the input. This is then
  18727. * updated to the new high water mark.
  18728. */
  18729. }
  18730. function deflateResetKeep(strm) {
  18731. var s;
  18732. if (!strm || !strm.state) {
  18733. return err(strm, Z_STREAM_ERROR);
  18734. }
  18735. strm.total_in = strm.total_out = 0;
  18736. strm.data_type = Z_UNKNOWN;
  18737. s = strm.state;
  18738. s.pending = 0;
  18739. s.pending_out = 0;
  18740. if (s.wrap < 0) {
  18741. s.wrap = -s.wrap;
  18742. /* was made negative by deflate(..., Z_FINISH); */
  18743. }
  18744. s.status = (s.wrap ? INIT_STATE : BUSY_STATE);
  18745. strm.adler = (s.wrap === 2) ?
  18746. 0 // crc32(0, Z_NULL, 0)
  18747. :
  18748. 1; // adler32(0, Z_NULL, 0)
  18749. s.last_flush = Z_NO_FLUSH;
  18750. trees._tr_init(s);
  18751. return Z_OK;
  18752. }
  18753. function deflateReset(strm) {
  18754. var ret = deflateResetKeep(strm);
  18755. if (ret === Z_OK) {
  18756. lm_init(strm.state);
  18757. }
  18758. return ret;
  18759. }
  18760. function deflateSetHeader(strm, head) {
  18761. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  18762. if (strm.state.wrap !== 2) { return Z_STREAM_ERROR; }
  18763. strm.state.gzhead = head;
  18764. return Z_OK;
  18765. }
  18766. function deflateInit2(strm, level, method, windowBits, memLevel, strategy) {
  18767. if (!strm) { // === Z_NULL
  18768. return Z_STREAM_ERROR;
  18769. }
  18770. var wrap = 1;
  18771. if (level === Z_DEFAULT_COMPRESSION) {
  18772. level = 6;
  18773. }
  18774. if (windowBits < 0) { /* suppress zlib wrapper */
  18775. wrap = 0;
  18776. windowBits = -windowBits;
  18777. }
  18778. else if (windowBits > 15) {
  18779. wrap = 2; /* write gzip wrapper instead */
  18780. windowBits -= 16;
  18781. }
  18782. if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method !== Z_DEFLATED ||
  18783. windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||
  18784. strategy < 0 || strategy > Z_FIXED) {
  18785. return err(strm, Z_STREAM_ERROR);
  18786. }
  18787. if (windowBits === 8) {
  18788. windowBits = 9;
  18789. }
  18790. /* until 256-byte window bug fixed */
  18791. var s = new DeflateState();
  18792. strm.state = s;
  18793. s.strm = strm;
  18794. s.wrap = wrap;
  18795. s.gzhead = null;
  18796. s.w_bits = windowBits;
  18797. s.w_size = 1 << s.w_bits;
  18798. s.w_mask = s.w_size - 1;
  18799. s.hash_bits = memLevel + 7;
  18800. s.hash_size = 1 << s.hash_bits;
  18801. s.hash_mask = s.hash_size - 1;
  18802. s.hash_shift = ~~((s.hash_bits + MIN_MATCH - 1) / MIN_MATCH);
  18803. s.window = new utils.Buf8(s.w_size * 2);
  18804. s.head = new utils.Buf16(s.hash_size);
  18805. s.prev = new utils.Buf16(s.w_size);
  18806. // Don't need mem init magic for JS.
  18807. //s.high_water = 0; /* nothing written to s->window yet */
  18808. s.lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */
  18809. s.pending_buf_size = s.lit_bufsize * 4;
  18810. s.pending_buf = new utils.Buf8(s.pending_buf_size);
  18811. s.d_buf = s.lit_bufsize >> 1;
  18812. s.l_buf = (1 + 2) * s.lit_bufsize;
  18813. s.level = level;
  18814. s.strategy = strategy;
  18815. s.method = method;
  18816. return deflateReset(strm);
  18817. }
  18818. function deflateInit(strm, level) {
  18819. return deflateInit2(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY);
  18820. }
  18821. function deflate(strm, flush) {
  18822. var old_flush, s;
  18823. var beg, val; // for gzip header write only
  18824. if (!strm || !strm.state ||
  18825. flush > Z_BLOCK || flush < 0) {
  18826. return strm ? err(strm, Z_STREAM_ERROR) : Z_STREAM_ERROR;
  18827. }
  18828. s = strm.state;
  18829. if (!strm.output ||
  18830. (!strm.input && strm.avail_in !== 0) ||
  18831. (s.status === FINISH_STATE && flush !== Z_FINISH)) {
  18832. return err(strm, (strm.avail_out === 0) ? Z_BUF_ERROR : Z_STREAM_ERROR);
  18833. }
  18834. s.strm = strm; /* just in case */
  18835. old_flush = s.last_flush;
  18836. s.last_flush = flush;
  18837. /* Write the header */
  18838. if (s.status === INIT_STATE) {
  18839. if (s.wrap === 2) { // GZIP header
  18840. strm.adler = 0; //crc32(0L, Z_NULL, 0);
  18841. put_byte(s, 31);
  18842. put_byte(s, 139);
  18843. put_byte(s, 8);
  18844. if (!s.gzhead) { // s->gzhead == Z_NULL
  18845. put_byte(s, 0);
  18846. put_byte(s, 0);
  18847. put_byte(s, 0);
  18848. put_byte(s, 0);
  18849. put_byte(s, 0);
  18850. put_byte(s, s.level === 9 ? 2 :
  18851. (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
  18852. 4 : 0));
  18853. put_byte(s, OS_CODE);
  18854. s.status = BUSY_STATE;
  18855. }
  18856. else {
  18857. put_byte(s, (s.gzhead.text ? 1 : 0) +
  18858. (s.gzhead.hcrc ? 2 : 0) +
  18859. (!s.gzhead.extra ? 0 : 4) +
  18860. (!s.gzhead.name ? 0 : 8) +
  18861. (!s.gzhead.comment ? 0 : 16)
  18862. );
  18863. put_byte(s, s.gzhead.time & 0xff);
  18864. put_byte(s, (s.gzhead.time >> 8) & 0xff);
  18865. put_byte(s, (s.gzhead.time >> 16) & 0xff);
  18866. put_byte(s, (s.gzhead.time >> 24) & 0xff);
  18867. put_byte(s, s.level === 9 ? 2 :
  18868. (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
  18869. 4 : 0));
  18870. put_byte(s, s.gzhead.os & 0xff);
  18871. if (s.gzhead.extra && s.gzhead.extra.length) {
  18872. put_byte(s, s.gzhead.extra.length & 0xff);
  18873. put_byte(s, (s.gzhead.extra.length >> 8) & 0xff);
  18874. }
  18875. if (s.gzhead.hcrc) {
  18876. strm.adler = crc32(strm.adler, s.pending_buf, s.pending, 0);
  18877. }
  18878. s.gzindex = 0;
  18879. s.status = EXTRA_STATE;
  18880. }
  18881. }
  18882. else // DEFLATE header
  18883. {
  18884. var header = (Z_DEFLATED + ((s.w_bits - 8) << 4)) << 8;
  18885. var level_flags = -1;
  18886. if (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2) {
  18887. level_flags = 0;
  18888. } else if (s.level < 6) {
  18889. level_flags = 1;
  18890. } else if (s.level === 6) {
  18891. level_flags = 2;
  18892. } else {
  18893. level_flags = 3;
  18894. }
  18895. header |= (level_flags << 6);
  18896. if (s.strstart !== 0) { header |= PRESET_DICT; }
  18897. header += 31 - (header % 31);
  18898. s.status = BUSY_STATE;
  18899. putShortMSB(s, header);
  18900. /* Save the adler32 of the preset dictionary: */
  18901. if (s.strstart !== 0) {
  18902. putShortMSB(s, strm.adler >>> 16);
  18903. putShortMSB(s, strm.adler & 0xffff);
  18904. }
  18905. strm.adler = 1; // adler32(0L, Z_NULL, 0);
  18906. }
  18907. }
  18908. //#ifdef GZIP
  18909. if (s.status === EXTRA_STATE) {
  18910. if (s.gzhead.extra/* != Z_NULL*/) {
  18911. beg = s.pending; /* start of bytes to update crc */
  18912. while (s.gzindex < (s.gzhead.extra.length & 0xffff)) {
  18913. if (s.pending === s.pending_buf_size) {
  18914. if (s.gzhead.hcrc && s.pending > beg) {
  18915. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  18916. }
  18917. flush_pending(strm);
  18918. beg = s.pending;
  18919. if (s.pending === s.pending_buf_size) {
  18920. break;
  18921. }
  18922. }
  18923. put_byte(s, s.gzhead.extra[s.gzindex] & 0xff);
  18924. s.gzindex++;
  18925. }
  18926. if (s.gzhead.hcrc && s.pending > beg) {
  18927. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  18928. }
  18929. if (s.gzindex === s.gzhead.extra.length) {
  18930. s.gzindex = 0;
  18931. s.status = NAME_STATE;
  18932. }
  18933. }
  18934. else {
  18935. s.status = NAME_STATE;
  18936. }
  18937. }
  18938. if (s.status === NAME_STATE) {
  18939. if (s.gzhead.name/* != Z_NULL*/) {
  18940. beg = s.pending; /* start of bytes to update crc */
  18941. //int val;
  18942. do {
  18943. if (s.pending === s.pending_buf_size) {
  18944. if (s.gzhead.hcrc && s.pending > beg) {
  18945. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  18946. }
  18947. flush_pending(strm);
  18948. beg = s.pending;
  18949. if (s.pending === s.pending_buf_size) {
  18950. val = 1;
  18951. break;
  18952. }
  18953. }
  18954. // JS specific: little magic to add zero terminator to end of string
  18955. if (s.gzindex < s.gzhead.name.length) {
  18956. val = s.gzhead.name.charCodeAt(s.gzindex++) & 0xff;
  18957. } else {
  18958. val = 0;
  18959. }
  18960. put_byte(s, val);
  18961. } while (val !== 0);
  18962. if (s.gzhead.hcrc && s.pending > beg){
  18963. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  18964. }
  18965. if (val === 0) {
  18966. s.gzindex = 0;
  18967. s.status = COMMENT_STATE;
  18968. }
  18969. }
  18970. else {
  18971. s.status = COMMENT_STATE;
  18972. }
  18973. }
  18974. if (s.status === COMMENT_STATE) {
  18975. if (s.gzhead.comment/* != Z_NULL*/) {
  18976. beg = s.pending; /* start of bytes to update crc */
  18977. //int val;
  18978. do {
  18979. if (s.pending === s.pending_buf_size) {
  18980. if (s.gzhead.hcrc && s.pending > beg) {
  18981. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  18982. }
  18983. flush_pending(strm);
  18984. beg = s.pending;
  18985. if (s.pending === s.pending_buf_size) {
  18986. val = 1;
  18987. break;
  18988. }
  18989. }
  18990. // JS specific: little magic to add zero terminator to end of string
  18991. if (s.gzindex < s.gzhead.comment.length) {
  18992. val = s.gzhead.comment.charCodeAt(s.gzindex++) & 0xff;
  18993. } else {
  18994. val = 0;
  18995. }
  18996. put_byte(s, val);
  18997. } while (val !== 0);
  18998. if (s.gzhead.hcrc && s.pending > beg) {
  18999. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  19000. }
  19001. if (val === 0) {
  19002. s.status = HCRC_STATE;
  19003. }
  19004. }
  19005. else {
  19006. s.status = HCRC_STATE;
  19007. }
  19008. }
  19009. if (s.status === HCRC_STATE) {
  19010. if (s.gzhead.hcrc) {
  19011. if (s.pending + 2 > s.pending_buf_size) {
  19012. flush_pending(strm);
  19013. }
  19014. if (s.pending + 2 <= s.pending_buf_size) {
  19015. put_byte(s, strm.adler & 0xff);
  19016. put_byte(s, (strm.adler >> 8) & 0xff);
  19017. strm.adler = 0; //crc32(0L, Z_NULL, 0);
  19018. s.status = BUSY_STATE;
  19019. }
  19020. }
  19021. else {
  19022. s.status = BUSY_STATE;
  19023. }
  19024. }
  19025. //#endif
  19026. /* Flush as much pending output as possible */
  19027. if (s.pending !== 0) {
  19028. flush_pending(strm);
  19029. if (strm.avail_out === 0) {
  19030. /* Since avail_out is 0, deflate will be called again with
  19031. * more output space, but possibly with both pending and
  19032. * avail_in equal to zero. There won't be anything to do,
  19033. * but this is not an error situation so make sure we
  19034. * return OK instead of BUF_ERROR at next call of deflate:
  19035. */
  19036. s.last_flush = -1;
  19037. return Z_OK;
  19038. }
  19039. /* Make sure there is something to do and avoid duplicate consecutive
  19040. * flushes. For repeated and useless calls with Z_FINISH, we keep
  19041. * returning Z_STREAM_END instead of Z_BUF_ERROR.
  19042. */
  19043. } else if (strm.avail_in === 0 && rank(flush) <= rank(old_flush) &&
  19044. flush !== Z_FINISH) {
  19045. return err(strm, Z_BUF_ERROR);
  19046. }
  19047. /* User must not provide more input after the first FINISH: */
  19048. if (s.status === FINISH_STATE && strm.avail_in !== 0) {
  19049. return err(strm, Z_BUF_ERROR);
  19050. }
  19051. /* Start a new block or continue the current one.
  19052. */
  19053. if (strm.avail_in !== 0 || s.lookahead !== 0 ||
  19054. (flush !== Z_NO_FLUSH && s.status !== FINISH_STATE)) {
  19055. var bstate = (s.strategy === Z_HUFFMAN_ONLY) ? deflate_huff(s, flush) :
  19056. (s.strategy === Z_RLE ? deflate_rle(s, flush) :
  19057. configuration_table[s.level].func(s, flush));
  19058. if (bstate === BS_FINISH_STARTED || bstate === BS_FINISH_DONE) {
  19059. s.status = FINISH_STATE;
  19060. }
  19061. if (bstate === BS_NEED_MORE || bstate === BS_FINISH_STARTED) {
  19062. if (strm.avail_out === 0) {
  19063. s.last_flush = -1;
  19064. /* avoid BUF_ERROR next call, see above */
  19065. }
  19066. return Z_OK;
  19067. /* If flush != Z_NO_FLUSH && avail_out == 0, the next call
  19068. * of deflate should use the same flush parameter to make sure
  19069. * that the flush is complete. So we don't have to output an
  19070. * empty block here, this will be done at next call. This also
  19071. * ensures that for a very small output buffer, we emit at most
  19072. * one empty block.
  19073. */
  19074. }
  19075. if (bstate === BS_BLOCK_DONE) {
  19076. if (flush === Z_PARTIAL_FLUSH) {
  19077. trees._tr_align(s);
  19078. }
  19079. else if (flush !== Z_BLOCK) { /* FULL_FLUSH or SYNC_FLUSH */
  19080. trees._tr_stored_block(s, 0, 0, false);
  19081. /* For a full flush, this empty block will be recognized
  19082. * as a special marker by inflate_sync().
  19083. */
  19084. if (flush === Z_FULL_FLUSH) {
  19085. /*** CLEAR_HASH(s); ***/ /* forget history */
  19086. zero(s.head); // Fill with NIL (= 0);
  19087. if (s.lookahead === 0) {
  19088. s.strstart = 0;
  19089. s.block_start = 0;
  19090. s.insert = 0;
  19091. }
  19092. }
  19093. }
  19094. flush_pending(strm);
  19095. if (strm.avail_out === 0) {
  19096. s.last_flush = -1; /* avoid BUF_ERROR at next call, see above */
  19097. return Z_OK;
  19098. }
  19099. }
  19100. }
  19101. //Assert(strm->avail_out > 0, "bug2");
  19102. //if (strm.avail_out <= 0) { throw new Error("bug2");}
  19103. if (flush !== Z_FINISH) { return Z_OK; }
  19104. if (s.wrap <= 0) { return Z_STREAM_END; }
  19105. /* Write the trailer */
  19106. if (s.wrap === 2) {
  19107. put_byte(s, strm.adler & 0xff);
  19108. put_byte(s, (strm.adler >> 8) & 0xff);
  19109. put_byte(s, (strm.adler >> 16) & 0xff);
  19110. put_byte(s, (strm.adler >> 24) & 0xff);
  19111. put_byte(s, strm.total_in & 0xff);
  19112. put_byte(s, (strm.total_in >> 8) & 0xff);
  19113. put_byte(s, (strm.total_in >> 16) & 0xff);
  19114. put_byte(s, (strm.total_in >> 24) & 0xff);
  19115. }
  19116. else
  19117. {
  19118. putShortMSB(s, strm.adler >>> 16);
  19119. putShortMSB(s, strm.adler & 0xffff);
  19120. }
  19121. flush_pending(strm);
  19122. /* If avail_out is zero, the application will call deflate again
  19123. * to flush the rest.
  19124. */
  19125. if (s.wrap > 0) { s.wrap = -s.wrap; }
  19126. /* write the trailer only once! */
  19127. return s.pending !== 0 ? Z_OK : Z_STREAM_END;
  19128. }
  19129. function deflateEnd(strm) {
  19130. var status;
  19131. if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) {
  19132. return Z_STREAM_ERROR;
  19133. }
  19134. status = strm.state.status;
  19135. if (status !== INIT_STATE &&
  19136. status !== EXTRA_STATE &&
  19137. status !== NAME_STATE &&
  19138. status !== COMMENT_STATE &&
  19139. status !== HCRC_STATE &&
  19140. status !== BUSY_STATE &&
  19141. status !== FINISH_STATE
  19142. ) {
  19143. return err(strm, Z_STREAM_ERROR);
  19144. }
  19145. strm.state = null;
  19146. return status === BUSY_STATE ? err(strm, Z_DATA_ERROR) : Z_OK;
  19147. }
  19148. /* =========================================================================
  19149. * Copy the source state to the destination state
  19150. */
  19151. //function deflateCopy(dest, source) {
  19152. //
  19153. //}
  19154. exports.deflateInit = deflateInit;
  19155. exports.deflateInit2 = deflateInit2;
  19156. exports.deflateReset = deflateReset;
  19157. exports.deflateResetKeep = deflateResetKeep;
  19158. exports.deflateSetHeader = deflateSetHeader;
  19159. exports.deflate = deflate;
  19160. exports.deflateEnd = deflateEnd;
  19161. exports.deflateInfo = 'pako deflate (from Nodeca project)';
  19162. /* Not implemented
  19163. exports.deflateBound = deflateBound;
  19164. exports.deflateCopy = deflateCopy;
  19165. exports.deflateSetDictionary = deflateSetDictionary;
  19166. exports.deflateParams = deflateParams;
  19167. exports.deflatePending = deflatePending;
  19168. exports.deflatePrime = deflatePrime;
  19169. exports.deflateTune = deflateTune;
  19170. */
  19171. },{"../utils/common":65,"./adler32":67,"./crc32":69,"./messages":75,"./trees":76}],71:[function(require,module,exports){
  19172. 'use strict';
  19173. function GZheader() {
  19174. /* true if compressed data believed to be text */
  19175. this.text = 0;
  19176. /* modification time */
  19177. this.time = 0;
  19178. /* extra flags (not used when writing a gzip file) */
  19179. this.xflags = 0;
  19180. /* operating system */
  19181. this.os = 0;
  19182. /* pointer to extra field or Z_NULL if none */
  19183. this.extra = null;
  19184. /* extra field length (valid if extra != Z_NULL) */
  19185. this.extra_len = 0; // Actually, we don't need it in JS,
  19186. // but leave for few code modifications
  19187. //
  19188. // Setup limits is not necessary because in js we should not preallocate memory
  19189. // for inflate use constant limit in 65536 bytes
  19190. //
  19191. /* space at extra (only when reading header) */
  19192. // this.extra_max = 0;
  19193. /* pointer to zero-terminated file name or Z_NULL */
  19194. this.name = '';
  19195. /* space at name (only when reading header) */
  19196. // this.name_max = 0;
  19197. /* pointer to zero-terminated comment or Z_NULL */
  19198. this.comment = '';
  19199. /* space at comment (only when reading header) */
  19200. // this.comm_max = 0;
  19201. /* true if there was or will be a header crc */
  19202. this.hcrc = 0;
  19203. /* true when done reading gzip header (not used when writing a gzip file) */
  19204. this.done = false;
  19205. }
  19206. module.exports = GZheader;
  19207. },{}],72:[function(require,module,exports){
  19208. 'use strict';
  19209. // See state defs from inflate.js
  19210. var BAD = 30; /* got a data error -- remain here until reset */
  19211. var TYPE = 12; /* i: waiting for type bits, including last-flag bit */
  19212. /*
  19213. Decode literal, length, and distance codes and write out the resulting
  19214. literal and match bytes until either not enough input or output is
  19215. available, an end-of-block is encountered, or a data error is encountered.
  19216. When large enough input and output buffers are supplied to inflate(), for
  19217. example, a 16K input buffer and a 64K output buffer, more than 95% of the
  19218. inflate execution time is spent in this routine.
  19219. Entry assumptions:
  19220. state.mode === LEN
  19221. strm.avail_in >= 6
  19222. strm.avail_out >= 258
  19223. start >= strm.avail_out
  19224. state.bits < 8
  19225. On return, state.mode is one of:
  19226. LEN -- ran out of enough output space or enough available input
  19227. TYPE -- reached end of block code, inflate() to interpret next block
  19228. BAD -- error in block data
  19229. Notes:
  19230. - The maximum input bits used by a length/distance pair is 15 bits for the
  19231. length code, 5 bits for the length extra, 15 bits for the distance code,
  19232. and 13 bits for the distance extra. This totals 48 bits, or six bytes.
  19233. Therefore if strm.avail_in >= 6, then there is enough input to avoid
  19234. checking for available input while decoding.
  19235. - The maximum bytes that a single length/distance pair can output is 258
  19236. bytes, which is the maximum length that can be coded. inflate_fast()
  19237. requires strm.avail_out >= 258 for each loop to avoid checking for
  19238. output space.
  19239. */
  19240. module.exports = function inflate_fast(strm, start) {
  19241. var state;
  19242. var _in; /* local strm.input */
  19243. var last; /* have enough input while in < last */
  19244. var _out; /* local strm.output */
  19245. var beg; /* inflate()'s initial strm.output */
  19246. var end; /* while out < end, enough space available */
  19247. //#ifdef INFLATE_STRICT
  19248. var dmax; /* maximum distance from zlib header */
  19249. //#endif
  19250. var wsize; /* window size or zero if not using window */
  19251. var whave; /* valid bytes in the window */
  19252. var wnext; /* window write index */
  19253. var window; /* allocated sliding window, if wsize != 0 */
  19254. var hold; /* local strm.hold */
  19255. var bits; /* local strm.bits */
  19256. var lcode; /* local strm.lencode */
  19257. var dcode; /* local strm.distcode */
  19258. var lmask; /* mask for first level of length codes */
  19259. var dmask; /* mask for first level of distance codes */
  19260. var here; /* retrieved table entry */
  19261. var op; /* code bits, operation, extra bits, or */
  19262. /* window position, window bytes to copy */
  19263. var len; /* match length, unused bytes */
  19264. var dist; /* match distance */
  19265. var from; /* where to copy match from */
  19266. var from_source;
  19267. var input, output; // JS specific, because we have no pointers
  19268. /* copy state to local variables */
  19269. state = strm.state;
  19270. //here = state.here;
  19271. _in = strm.next_in;
  19272. input = strm.input;
  19273. last = _in + (strm.avail_in - 5);
  19274. _out = strm.next_out;
  19275. output = strm.output;
  19276. beg = _out - (start - strm.avail_out);
  19277. end = _out + (strm.avail_out - 257);
  19278. //#ifdef INFLATE_STRICT
  19279. dmax = state.dmax;
  19280. //#endif
  19281. wsize = state.wsize;
  19282. whave = state.whave;
  19283. wnext = state.wnext;
  19284. window = state.window;
  19285. hold = state.hold;
  19286. bits = state.bits;
  19287. lcode = state.lencode;
  19288. dcode = state.distcode;
  19289. lmask = (1 << state.lenbits) - 1;
  19290. dmask = (1 << state.distbits) - 1;
  19291. /* decode literals and length/distances until end-of-block or not enough
  19292. input data or output space */
  19293. top:
  19294. do {
  19295. if (bits < 15) {
  19296. hold += input[_in++] << bits;
  19297. bits += 8;
  19298. hold += input[_in++] << bits;
  19299. bits += 8;
  19300. }
  19301. here = lcode[hold & lmask];
  19302. dolen:
  19303. for (;;) { // Goto emulation
  19304. op = here >>> 24/*here.bits*/;
  19305. hold >>>= op;
  19306. bits -= op;
  19307. op = (here >>> 16) & 0xff/*here.op*/;
  19308. if (op === 0) { /* literal */
  19309. //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
  19310. // "inflate: literal '%c'\n" :
  19311. // "inflate: literal 0x%02x\n", here.val));
  19312. output[_out++] = here & 0xffff/*here.val*/;
  19313. }
  19314. else if (op & 16) { /* length base */
  19315. len = here & 0xffff/*here.val*/;
  19316. op &= 15; /* number of extra bits */
  19317. if (op) {
  19318. if (bits < op) {
  19319. hold += input[_in++] << bits;
  19320. bits += 8;
  19321. }
  19322. len += hold & ((1 << op) - 1);
  19323. hold >>>= op;
  19324. bits -= op;
  19325. }
  19326. //Tracevv((stderr, "inflate: length %u\n", len));
  19327. if (bits < 15) {
  19328. hold += input[_in++] << bits;
  19329. bits += 8;
  19330. hold += input[_in++] << bits;
  19331. bits += 8;
  19332. }
  19333. here = dcode[hold & dmask];
  19334. dodist:
  19335. for (;;) { // goto emulation
  19336. op = here >>> 24/*here.bits*/;
  19337. hold >>>= op;
  19338. bits -= op;
  19339. op = (here >>> 16) & 0xff/*here.op*/;
  19340. if (op & 16) { /* distance base */
  19341. dist = here & 0xffff/*here.val*/;
  19342. op &= 15; /* number of extra bits */
  19343. if (bits < op) {
  19344. hold += input[_in++] << bits;
  19345. bits += 8;
  19346. if (bits < op) {
  19347. hold += input[_in++] << bits;
  19348. bits += 8;
  19349. }
  19350. }
  19351. dist += hold & ((1 << op) - 1);
  19352. //#ifdef INFLATE_STRICT
  19353. if (dist > dmax) {
  19354. strm.msg = 'invalid distance too far back';
  19355. state.mode = BAD;
  19356. break top;
  19357. }
  19358. //#endif
  19359. hold >>>= op;
  19360. bits -= op;
  19361. //Tracevv((stderr, "inflate: distance %u\n", dist));
  19362. op = _out - beg; /* max distance in output */
  19363. if (dist > op) { /* see if copy from window */
  19364. op = dist - op; /* distance back in window */
  19365. if (op > whave) {
  19366. if (state.sane) {
  19367. strm.msg = 'invalid distance too far back';
  19368. state.mode = BAD;
  19369. break top;
  19370. }
  19371. // (!) This block is disabled in zlib defailts,
  19372. // don't enable it for binary compatibility
  19373. //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
  19374. // if (len <= op - whave) {
  19375. // do {
  19376. // output[_out++] = 0;
  19377. // } while (--len);
  19378. // continue top;
  19379. // }
  19380. // len -= op - whave;
  19381. // do {
  19382. // output[_out++] = 0;
  19383. // } while (--op > whave);
  19384. // if (op === 0) {
  19385. // from = _out - dist;
  19386. // do {
  19387. // output[_out++] = output[from++];
  19388. // } while (--len);
  19389. // continue top;
  19390. // }
  19391. //#endif
  19392. }
  19393. from = 0; // window index
  19394. from_source = window;
  19395. if (wnext === 0) { /* very common case */
  19396. from += wsize - op;
  19397. if (op < len) { /* some from window */
  19398. len -= op;
  19399. do {
  19400. output[_out++] = window[from++];
  19401. } while (--op);
  19402. from = _out - dist; /* rest from output */
  19403. from_source = output;
  19404. }
  19405. }
  19406. else if (wnext < op) { /* wrap around window */
  19407. from += wsize + wnext - op;
  19408. op -= wnext;
  19409. if (op < len) { /* some from end of window */
  19410. len -= op;
  19411. do {
  19412. output[_out++] = window[from++];
  19413. } while (--op);
  19414. from = 0;
  19415. if (wnext < len) { /* some from start of window */
  19416. op = wnext;
  19417. len -= op;
  19418. do {
  19419. output[_out++] = window[from++];
  19420. } while (--op);
  19421. from = _out - dist; /* rest from output */
  19422. from_source = output;
  19423. }
  19424. }
  19425. }
  19426. else { /* contiguous in window */
  19427. from += wnext - op;
  19428. if (op < len) { /* some from window */
  19429. len -= op;
  19430. do {
  19431. output[_out++] = window[from++];
  19432. } while (--op);
  19433. from = _out - dist; /* rest from output */
  19434. from_source = output;
  19435. }
  19436. }
  19437. while (len > 2) {
  19438. output[_out++] = from_source[from++];
  19439. output[_out++] = from_source[from++];
  19440. output[_out++] = from_source[from++];
  19441. len -= 3;
  19442. }
  19443. if (len) {
  19444. output[_out++] = from_source[from++];
  19445. if (len > 1) {
  19446. output[_out++] = from_source[from++];
  19447. }
  19448. }
  19449. }
  19450. else {
  19451. from = _out - dist; /* copy direct from output */
  19452. do { /* minimum length is three */
  19453. output[_out++] = output[from++];
  19454. output[_out++] = output[from++];
  19455. output[_out++] = output[from++];
  19456. len -= 3;
  19457. } while (len > 2);
  19458. if (len) {
  19459. output[_out++] = output[from++];
  19460. if (len > 1) {
  19461. output[_out++] = output[from++];
  19462. }
  19463. }
  19464. }
  19465. }
  19466. else if ((op & 64) === 0) { /* 2nd level distance code */
  19467. here = dcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
  19468. continue dodist;
  19469. }
  19470. else {
  19471. strm.msg = 'invalid distance code';
  19472. state.mode = BAD;
  19473. break top;
  19474. }
  19475. break; // need to emulate goto via "continue"
  19476. }
  19477. }
  19478. else if ((op & 64) === 0) { /* 2nd level length code */
  19479. here = lcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
  19480. continue dolen;
  19481. }
  19482. else if (op & 32) { /* end-of-block */
  19483. //Tracevv((stderr, "inflate: end of block\n"));
  19484. state.mode = TYPE;
  19485. break top;
  19486. }
  19487. else {
  19488. strm.msg = 'invalid literal/length code';
  19489. state.mode = BAD;
  19490. break top;
  19491. }
  19492. break; // need to emulate goto via "continue"
  19493. }
  19494. } while (_in < last && _out < end);
  19495. /* return unused bytes (on entry, bits < 8, so in won't go too far back) */
  19496. len = bits >> 3;
  19497. _in -= len;
  19498. bits -= len << 3;
  19499. hold &= (1 << bits) - 1;
  19500. /* update state and return */
  19501. strm.next_in = _in;
  19502. strm.next_out = _out;
  19503. strm.avail_in = (_in < last ? 5 + (last - _in) : 5 - (_in - last));
  19504. strm.avail_out = (_out < end ? 257 + (end - _out) : 257 - (_out - end));
  19505. state.hold = hold;
  19506. state.bits = bits;
  19507. return;
  19508. };
  19509. },{}],73:[function(require,module,exports){
  19510. 'use strict';
  19511. var utils = require('../utils/common');
  19512. var adler32 = require('./adler32');
  19513. var crc32 = require('./crc32');
  19514. var inflate_fast = require('./inffast');
  19515. var inflate_table = require('./inftrees');
  19516. var CODES = 0;
  19517. var LENS = 1;
  19518. var DISTS = 2;
  19519. /* Public constants ==========================================================*/
  19520. /* ===========================================================================*/
  19521. /* Allowed flush values; see deflate() and inflate() below for details */
  19522. //var Z_NO_FLUSH = 0;
  19523. //var Z_PARTIAL_FLUSH = 1;
  19524. //var Z_SYNC_FLUSH = 2;
  19525. //var Z_FULL_FLUSH = 3;
  19526. var Z_FINISH = 4;
  19527. var Z_BLOCK = 5;
  19528. var Z_TREES = 6;
  19529. /* Return codes for the compression/decompression functions. Negative values
  19530. * are errors, positive values are used for special but normal events.
  19531. */
  19532. var Z_OK = 0;
  19533. var Z_STREAM_END = 1;
  19534. var Z_NEED_DICT = 2;
  19535. //var Z_ERRNO = -1;
  19536. var Z_STREAM_ERROR = -2;
  19537. var Z_DATA_ERROR = -3;
  19538. var Z_MEM_ERROR = -4;
  19539. var Z_BUF_ERROR = -5;
  19540. //var Z_VERSION_ERROR = -6;
  19541. /* The deflate compression method */
  19542. var Z_DEFLATED = 8;
  19543. /* STATES ====================================================================*/
  19544. /* ===========================================================================*/
  19545. var HEAD = 1; /* i: waiting for magic header */
  19546. var FLAGS = 2; /* i: waiting for method and flags (gzip) */
  19547. var TIME = 3; /* i: waiting for modification time (gzip) */
  19548. var OS = 4; /* i: waiting for extra flags and operating system (gzip) */
  19549. var EXLEN = 5; /* i: waiting for extra length (gzip) */
  19550. var EXTRA = 6; /* i: waiting for extra bytes (gzip) */
  19551. var NAME = 7; /* i: waiting for end of file name (gzip) */
  19552. var COMMENT = 8; /* i: waiting for end of comment (gzip) */
  19553. var HCRC = 9; /* i: waiting for header crc (gzip) */
  19554. var DICTID = 10; /* i: waiting for dictionary check value */
  19555. var DICT = 11; /* waiting for inflateSetDictionary() call */
  19556. var TYPE = 12; /* i: waiting for type bits, including last-flag bit */
  19557. var TYPEDO = 13; /* i: same, but skip check to exit inflate on new block */
  19558. var STORED = 14; /* i: waiting for stored size (length and complement) */
  19559. var COPY_ = 15; /* i/o: same as COPY below, but only first time in */
  19560. var COPY = 16; /* i/o: waiting for input or output to copy stored block */
  19561. var TABLE = 17; /* i: waiting for dynamic block table lengths */
  19562. var LENLENS = 18; /* i: waiting for code length code lengths */
  19563. var CODELENS = 19; /* i: waiting for length/lit and distance code lengths */
  19564. var LEN_ = 20; /* i: same as LEN below, but only first time in */
  19565. var LEN = 21; /* i: waiting for length/lit/eob code */
  19566. var LENEXT = 22; /* i: waiting for length extra bits */
  19567. var DIST = 23; /* i: waiting for distance code */
  19568. var DISTEXT = 24; /* i: waiting for distance extra bits */
  19569. var MATCH = 25; /* o: waiting for output space to copy string */
  19570. var LIT = 26; /* o: waiting for output space to write literal */
  19571. var CHECK = 27; /* i: waiting for 32-bit check value */
  19572. var LENGTH = 28; /* i: waiting for 32-bit length (gzip) */
  19573. var DONE = 29; /* finished check, done -- remain here until reset */
  19574. var BAD = 30; /* got a data error -- remain here until reset */
  19575. var MEM = 31; /* got an inflate() memory error -- remain here until reset */
  19576. var SYNC = 32; /* looking for synchronization bytes to restart inflate() */
  19577. /* ===========================================================================*/
  19578. var ENOUGH_LENS = 852;
  19579. var ENOUGH_DISTS = 592;
  19580. //var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
  19581. var MAX_WBITS = 15;
  19582. /* 32K LZ77 window */
  19583. var DEF_WBITS = MAX_WBITS;
  19584. function ZSWAP32(q) {
  19585. return (((q >>> 24) & 0xff) +
  19586. ((q >>> 8) & 0xff00) +
  19587. ((q & 0xff00) << 8) +
  19588. ((q & 0xff) << 24));
  19589. }
  19590. function InflateState() {
  19591. this.mode = 0; /* current inflate mode */
  19592. this.last = false; /* true if processing last block */
  19593. this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
  19594. this.havedict = false; /* true if dictionary provided */
  19595. this.flags = 0; /* gzip header method and flags (0 if zlib) */
  19596. this.dmax = 0; /* zlib header max distance (INFLATE_STRICT) */
  19597. this.check = 0; /* protected copy of check value */
  19598. this.total = 0; /* protected copy of output count */
  19599. // TODO: may be {}
  19600. this.head = null; /* where to save gzip header information */
  19601. /* sliding window */
  19602. this.wbits = 0; /* log base 2 of requested window size */
  19603. this.wsize = 0; /* window size or zero if not using window */
  19604. this.whave = 0; /* valid bytes in the window */
  19605. this.wnext = 0; /* window write index */
  19606. this.window = null; /* allocated sliding window, if needed */
  19607. /* bit accumulator */
  19608. this.hold = 0; /* input bit accumulator */
  19609. this.bits = 0; /* number of bits in "in" */
  19610. /* for string and stored block copying */
  19611. this.length = 0; /* literal or length of data to copy */
  19612. this.offset = 0; /* distance back to copy string from */
  19613. /* for table and code decoding */
  19614. this.extra = 0; /* extra bits needed */
  19615. /* fixed and dynamic code tables */
  19616. this.lencode = null; /* starting table for length/literal codes */
  19617. this.distcode = null; /* starting table for distance codes */
  19618. this.lenbits = 0; /* index bits for lencode */
  19619. this.distbits = 0; /* index bits for distcode */
  19620. /* dynamic table building */
  19621. this.ncode = 0; /* number of code length code lengths */
  19622. this.nlen = 0; /* number of length code lengths */
  19623. this.ndist = 0; /* number of distance code lengths */
  19624. this.have = 0; /* number of code lengths in lens[] */
  19625. this.next = null; /* next available space in codes[] */
  19626. this.lens = new utils.Buf16(320); /* temporary storage for code lengths */
  19627. this.work = new utils.Buf16(288); /* work area for code table building */
  19628. /*
  19629. because we don't have pointers in js, we use lencode and distcode directly
  19630. as buffers so we don't need codes
  19631. */
  19632. //this.codes = new utils.Buf32(ENOUGH); /* space for code tables */
  19633. this.lendyn = null; /* dynamic table for length/literal codes (JS specific) */
  19634. this.distdyn = null; /* dynamic table for distance codes (JS specific) */
  19635. this.sane = 0; /* if false, allow invalid distance too far */
  19636. this.back = 0; /* bits back of last unprocessed length/lit */
  19637. this.was = 0; /* initial length of match */
  19638. }
  19639. function inflateResetKeep(strm) {
  19640. var state;
  19641. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  19642. state = strm.state;
  19643. strm.total_in = strm.total_out = state.total = 0;
  19644. strm.msg = ''; /*Z_NULL*/
  19645. if (state.wrap) { /* to support ill-conceived Java test suite */
  19646. strm.adler = state.wrap & 1;
  19647. }
  19648. state.mode = HEAD;
  19649. state.last = 0;
  19650. state.havedict = 0;
  19651. state.dmax = 32768;
  19652. state.head = null/*Z_NULL*/;
  19653. state.hold = 0;
  19654. state.bits = 0;
  19655. //state.lencode = state.distcode = state.next = state.codes;
  19656. state.lencode = state.lendyn = new utils.Buf32(ENOUGH_LENS);
  19657. state.distcode = state.distdyn = new utils.Buf32(ENOUGH_DISTS);
  19658. state.sane = 1;
  19659. state.back = -1;
  19660. //Tracev((stderr, "inflate: reset\n"));
  19661. return Z_OK;
  19662. }
  19663. function inflateReset(strm) {
  19664. var state;
  19665. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  19666. state = strm.state;
  19667. state.wsize = 0;
  19668. state.whave = 0;
  19669. state.wnext = 0;
  19670. return inflateResetKeep(strm);
  19671. }
  19672. function inflateReset2(strm, windowBits) {
  19673. var wrap;
  19674. var state;
  19675. /* get the state */
  19676. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  19677. state = strm.state;
  19678. /* extract wrap request from windowBits parameter */
  19679. if (windowBits < 0) {
  19680. wrap = 0;
  19681. windowBits = -windowBits;
  19682. }
  19683. else {
  19684. wrap = (windowBits >> 4) + 1;
  19685. if (windowBits < 48) {
  19686. windowBits &= 15;
  19687. }
  19688. }
  19689. /* set number of window bits, free window if different */
  19690. if (windowBits && (windowBits < 8 || windowBits > 15)) {
  19691. return Z_STREAM_ERROR;
  19692. }
  19693. if (state.window !== null && state.wbits !== windowBits) {
  19694. state.window = null;
  19695. }
  19696. /* update state and reset the rest of it */
  19697. state.wrap = wrap;
  19698. state.wbits = windowBits;
  19699. return inflateReset(strm);
  19700. }
  19701. function inflateInit2(strm, windowBits) {
  19702. var ret;
  19703. var state;
  19704. if (!strm) { return Z_STREAM_ERROR; }
  19705. //strm.msg = Z_NULL; /* in case we return an error */
  19706. state = new InflateState();
  19707. //if (state === Z_NULL) return Z_MEM_ERROR;
  19708. //Tracev((stderr, "inflate: allocated\n"));
  19709. strm.state = state;
  19710. state.window = null/*Z_NULL*/;
  19711. ret = inflateReset2(strm, windowBits);
  19712. if (ret !== Z_OK) {
  19713. strm.state = null/*Z_NULL*/;
  19714. }
  19715. return ret;
  19716. }
  19717. function inflateInit(strm) {
  19718. return inflateInit2(strm, DEF_WBITS);
  19719. }
  19720. /*
  19721. Return state with length and distance decoding tables and index sizes set to
  19722. fixed code decoding. Normally this returns fixed tables from inffixed.h.
  19723. If BUILDFIXED is defined, then instead this routine builds the tables the
  19724. first time it's called, and returns those tables the first time and
  19725. thereafter. This reduces the size of the code by about 2K bytes, in
  19726. exchange for a little execution time. However, BUILDFIXED should not be
  19727. used for threaded applications, since the rewriting of the tables and virgin
  19728. may not be thread-safe.
  19729. */
  19730. var virgin = true;
  19731. var lenfix, distfix; // We have no pointers in JS, so keep tables separate
  19732. function fixedtables(state) {
  19733. /* build fixed huffman tables if first call (may not be thread safe) */
  19734. if (virgin) {
  19735. var sym;
  19736. lenfix = new utils.Buf32(512);
  19737. distfix = new utils.Buf32(32);
  19738. /* literal/length table */
  19739. sym = 0;
  19740. while (sym < 144) { state.lens[sym++] = 8; }
  19741. while (sym < 256) { state.lens[sym++] = 9; }
  19742. while (sym < 280) { state.lens[sym++] = 7; }
  19743. while (sym < 288) { state.lens[sym++] = 8; }
  19744. inflate_table(LENS, state.lens, 0, 288, lenfix, 0, state.work, {bits: 9});
  19745. /* distance table */
  19746. sym = 0;
  19747. while (sym < 32) { state.lens[sym++] = 5; }
  19748. inflate_table(DISTS, state.lens, 0, 32, distfix, 0, state.work, {bits: 5});
  19749. /* do this just once */
  19750. virgin = false;
  19751. }
  19752. state.lencode = lenfix;
  19753. state.lenbits = 9;
  19754. state.distcode = distfix;
  19755. state.distbits = 5;
  19756. }
  19757. /*
  19758. Update the window with the last wsize (normally 32K) bytes written before
  19759. returning. If window does not exist yet, create it. This is only called
  19760. when a window is already in use, or when output has been written during this
  19761. inflate call, but the end of the deflate stream has not been reached yet.
  19762. It is also called to create a window for dictionary data when a dictionary
  19763. is loaded.
  19764. Providing output buffers larger than 32K to inflate() should provide a speed
  19765. advantage, since only the last 32K of output is copied to the sliding window
  19766. upon return from inflate(), and since all distances after the first 32K of
  19767. output will fall in the output data, making match copies simpler and faster.
  19768. The advantage may be dependent on the size of the processor's data caches.
  19769. */
  19770. function updatewindow(strm, src, end, copy) {
  19771. var dist;
  19772. var state = strm.state;
  19773. /* if it hasn't been done already, allocate space for the window */
  19774. if (state.window === null) {
  19775. state.wsize = 1 << state.wbits;
  19776. state.wnext = 0;
  19777. state.whave = 0;
  19778. state.window = new utils.Buf8(state.wsize);
  19779. }
  19780. /* copy state->wsize or less output bytes into the circular window */
  19781. if (copy >= state.wsize) {
  19782. utils.arraySet(state.window,src, end - state.wsize, state.wsize, 0);
  19783. state.wnext = 0;
  19784. state.whave = state.wsize;
  19785. }
  19786. else {
  19787. dist = state.wsize - state.wnext;
  19788. if (dist > copy) {
  19789. dist = copy;
  19790. }
  19791. //zmemcpy(state->window + state->wnext, end - copy, dist);
  19792. utils.arraySet(state.window,src, end - copy, dist, state.wnext);
  19793. copy -= dist;
  19794. if (copy) {
  19795. //zmemcpy(state->window, end - copy, copy);
  19796. utils.arraySet(state.window,src, end - copy, copy, 0);
  19797. state.wnext = copy;
  19798. state.whave = state.wsize;
  19799. }
  19800. else {
  19801. state.wnext += dist;
  19802. if (state.wnext === state.wsize) { state.wnext = 0; }
  19803. if (state.whave < state.wsize) { state.whave += dist; }
  19804. }
  19805. }
  19806. return 0;
  19807. }
  19808. function inflate(strm, flush) {
  19809. var state;
  19810. var input, output; // input/output buffers
  19811. var next; /* next input INDEX */
  19812. var put; /* next output INDEX */
  19813. var have, left; /* available input and output */
  19814. var hold; /* bit buffer */
  19815. var bits; /* bits in bit buffer */
  19816. var _in, _out; /* save starting available input and output */
  19817. var copy; /* number of stored or match bytes to copy */
  19818. var from; /* where to copy match bytes from */
  19819. var from_source;
  19820. var here = 0; /* current decoding table entry */
  19821. var here_bits, here_op, here_val; // paked "here" denormalized (JS specific)
  19822. //var last; /* parent table entry */
  19823. var last_bits, last_op, last_val; // paked "last" denormalized (JS specific)
  19824. var len; /* length to copy for repeats, bits to drop */
  19825. var ret; /* return code */
  19826. var hbuf = new utils.Buf8(4); /* buffer for gzip header crc calculation */
  19827. var opts;
  19828. var n; // temporary var for NEED_BITS
  19829. var order = /* permutation of code lengths */
  19830. [16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15];
  19831. if (!strm || !strm.state || !strm.output ||
  19832. (!strm.input && strm.avail_in !== 0)) {
  19833. return Z_STREAM_ERROR;
  19834. }
  19835. state = strm.state;
  19836. if (state.mode === TYPE) { state.mode = TYPEDO; } /* skip check */
  19837. //--- LOAD() ---
  19838. put = strm.next_out;
  19839. output = strm.output;
  19840. left = strm.avail_out;
  19841. next = strm.next_in;
  19842. input = strm.input;
  19843. have = strm.avail_in;
  19844. hold = state.hold;
  19845. bits = state.bits;
  19846. //---
  19847. _in = have;
  19848. _out = left;
  19849. ret = Z_OK;
  19850. inf_leave: // goto emulation
  19851. for (;;) {
  19852. switch (state.mode) {
  19853. case HEAD:
  19854. if (state.wrap === 0) {
  19855. state.mode = TYPEDO;
  19856. break;
  19857. }
  19858. //=== NEEDBITS(16);
  19859. while (bits < 16) {
  19860. if (have === 0) { break inf_leave; }
  19861. have--;
  19862. hold += input[next++] << bits;
  19863. bits += 8;
  19864. }
  19865. //===//
  19866. if ((state.wrap & 2) && hold === 0x8b1f) { /* gzip header */
  19867. state.check = 0/*crc32(0L, Z_NULL, 0)*/;
  19868. //=== CRC2(state.check, hold);
  19869. hbuf[0] = hold & 0xff;
  19870. hbuf[1] = (hold >>> 8) & 0xff;
  19871. state.check = crc32(state.check, hbuf, 2, 0);
  19872. //===//
  19873. //=== INITBITS();
  19874. hold = 0;
  19875. bits = 0;
  19876. //===//
  19877. state.mode = FLAGS;
  19878. break;
  19879. }
  19880. state.flags = 0; /* expect zlib header */
  19881. if (state.head) {
  19882. state.head.done = false;
  19883. }
  19884. if (!(state.wrap & 1) || /* check if zlib header allowed */
  19885. (((hold & 0xff)/*BITS(8)*/ << 8) + (hold >> 8)) % 31) {
  19886. strm.msg = 'incorrect header check';
  19887. state.mode = BAD;
  19888. break;
  19889. }
  19890. if ((hold & 0x0f)/*BITS(4)*/ !== Z_DEFLATED) {
  19891. strm.msg = 'unknown compression method';
  19892. state.mode = BAD;
  19893. break;
  19894. }
  19895. //--- DROPBITS(4) ---//
  19896. hold >>>= 4;
  19897. bits -= 4;
  19898. //---//
  19899. len = (hold & 0x0f)/*BITS(4)*/ + 8;
  19900. if (state.wbits === 0) {
  19901. state.wbits = len;
  19902. }
  19903. else if (len > state.wbits) {
  19904. strm.msg = 'invalid window size';
  19905. state.mode = BAD;
  19906. break;
  19907. }
  19908. state.dmax = 1 << len;
  19909. //Tracev((stderr, "inflate: zlib header ok\n"));
  19910. strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
  19911. state.mode = hold & 0x200 ? DICTID : TYPE;
  19912. //=== INITBITS();
  19913. hold = 0;
  19914. bits = 0;
  19915. //===//
  19916. break;
  19917. case FLAGS:
  19918. //=== NEEDBITS(16); */
  19919. while (bits < 16) {
  19920. if (have === 0) { break inf_leave; }
  19921. have--;
  19922. hold += input[next++] << bits;
  19923. bits += 8;
  19924. }
  19925. //===//
  19926. state.flags = hold;
  19927. if ((state.flags & 0xff) !== Z_DEFLATED) {
  19928. strm.msg = 'unknown compression method';
  19929. state.mode = BAD;
  19930. break;
  19931. }
  19932. if (state.flags & 0xe000) {
  19933. strm.msg = 'unknown header flags set';
  19934. state.mode = BAD;
  19935. break;
  19936. }
  19937. if (state.head) {
  19938. state.head.text = ((hold >> 8) & 1);
  19939. }
  19940. if (state.flags & 0x0200) {
  19941. //=== CRC2(state.check, hold);
  19942. hbuf[0] = hold & 0xff;
  19943. hbuf[1] = (hold >>> 8) & 0xff;
  19944. state.check = crc32(state.check, hbuf, 2, 0);
  19945. //===//
  19946. }
  19947. //=== INITBITS();
  19948. hold = 0;
  19949. bits = 0;
  19950. //===//
  19951. state.mode = TIME;
  19952. /* falls through */
  19953. case TIME:
  19954. //=== NEEDBITS(32); */
  19955. while (bits < 32) {
  19956. if (have === 0) { break inf_leave; }
  19957. have--;
  19958. hold += input[next++] << bits;
  19959. bits += 8;
  19960. }
  19961. //===//
  19962. if (state.head) {
  19963. state.head.time = hold;
  19964. }
  19965. if (state.flags & 0x0200) {
  19966. //=== CRC4(state.check, hold)
  19967. hbuf[0] = hold & 0xff;
  19968. hbuf[1] = (hold >>> 8) & 0xff;
  19969. hbuf[2] = (hold >>> 16) & 0xff;
  19970. hbuf[3] = (hold >>> 24) & 0xff;
  19971. state.check = crc32(state.check, hbuf, 4, 0);
  19972. //===
  19973. }
  19974. //=== INITBITS();
  19975. hold = 0;
  19976. bits = 0;
  19977. //===//
  19978. state.mode = OS;
  19979. /* falls through */
  19980. case OS:
  19981. //=== NEEDBITS(16); */
  19982. while (bits < 16) {
  19983. if (have === 0) { break inf_leave; }
  19984. have--;
  19985. hold += input[next++] << bits;
  19986. bits += 8;
  19987. }
  19988. //===//
  19989. if (state.head) {
  19990. state.head.xflags = (hold & 0xff);
  19991. state.head.os = (hold >> 8);
  19992. }
  19993. if (state.flags & 0x0200) {
  19994. //=== CRC2(state.check, hold);
  19995. hbuf[0] = hold & 0xff;
  19996. hbuf[1] = (hold >>> 8) & 0xff;
  19997. state.check = crc32(state.check, hbuf, 2, 0);
  19998. //===//
  19999. }
  20000. //=== INITBITS();
  20001. hold = 0;
  20002. bits = 0;
  20003. //===//
  20004. state.mode = EXLEN;
  20005. /* falls through */
  20006. case EXLEN:
  20007. if (state.flags & 0x0400) {
  20008. //=== NEEDBITS(16); */
  20009. while (bits < 16) {
  20010. if (have === 0) { break inf_leave; }
  20011. have--;
  20012. hold += input[next++] << bits;
  20013. bits += 8;
  20014. }
  20015. //===//
  20016. state.length = hold;
  20017. if (state.head) {
  20018. state.head.extra_len = hold;
  20019. }
  20020. if (state.flags & 0x0200) {
  20021. //=== CRC2(state.check, hold);
  20022. hbuf[0] = hold & 0xff;
  20023. hbuf[1] = (hold >>> 8) & 0xff;
  20024. state.check = crc32(state.check, hbuf, 2, 0);
  20025. //===//
  20026. }
  20027. //=== INITBITS();
  20028. hold = 0;
  20029. bits = 0;
  20030. //===//
  20031. }
  20032. else if (state.head) {
  20033. state.head.extra = null/*Z_NULL*/;
  20034. }
  20035. state.mode = EXTRA;
  20036. /* falls through */
  20037. case EXTRA:
  20038. if (state.flags & 0x0400) {
  20039. copy = state.length;
  20040. if (copy > have) { copy = have; }
  20041. if (copy) {
  20042. if (state.head) {
  20043. len = state.head.extra_len - state.length;
  20044. if (!state.head.extra) {
  20045. // Use untyped array for more conveniend processing later
  20046. state.head.extra = new Array(state.head.extra_len);
  20047. }
  20048. utils.arraySet(
  20049. state.head.extra,
  20050. input,
  20051. next,
  20052. // extra field is limited to 65536 bytes
  20053. // - no need for additional size check
  20054. copy,
  20055. /*len + copy > state.head.extra_max - len ? state.head.extra_max : copy,*/
  20056. len
  20057. );
  20058. //zmemcpy(state.head.extra + len, next,
  20059. // len + copy > state.head.extra_max ?
  20060. // state.head.extra_max - len : copy);
  20061. }
  20062. if (state.flags & 0x0200) {
  20063. state.check = crc32(state.check, input, copy, next);
  20064. }
  20065. have -= copy;
  20066. next += copy;
  20067. state.length -= copy;
  20068. }
  20069. if (state.length) { break inf_leave; }
  20070. }
  20071. state.length = 0;
  20072. state.mode = NAME;
  20073. /* falls through */
  20074. case NAME:
  20075. if (state.flags & 0x0800) {
  20076. if (have === 0) { break inf_leave; }
  20077. copy = 0;
  20078. do {
  20079. // TODO: 2 or 1 bytes?
  20080. len = input[next + copy++];
  20081. /* use constant limit because in js we should not preallocate memory */
  20082. if (state.head && len &&
  20083. (state.length < 65536 /*state.head.name_max*/)) {
  20084. state.head.name += String.fromCharCode(len);
  20085. }
  20086. } while (len && copy < have);
  20087. if (state.flags & 0x0200) {
  20088. state.check = crc32(state.check, input, copy, next);
  20089. }
  20090. have -= copy;
  20091. next += copy;
  20092. if (len) { break inf_leave; }
  20093. }
  20094. else if (state.head) {
  20095. state.head.name = null;
  20096. }
  20097. state.length = 0;
  20098. state.mode = COMMENT;
  20099. /* falls through */
  20100. case COMMENT:
  20101. if (state.flags & 0x1000) {
  20102. if (have === 0) { break inf_leave; }
  20103. copy = 0;
  20104. do {
  20105. len = input[next + copy++];
  20106. /* use constant limit because in js we should not preallocate memory */
  20107. if (state.head && len &&
  20108. (state.length < 65536 /*state.head.comm_max*/)) {
  20109. state.head.comment += String.fromCharCode(len);
  20110. }
  20111. } while (len && copy < have);
  20112. if (state.flags & 0x0200) {
  20113. state.check = crc32(state.check, input, copy, next);
  20114. }
  20115. have -= copy;
  20116. next += copy;
  20117. if (len) { break inf_leave; }
  20118. }
  20119. else if (state.head) {
  20120. state.head.comment = null;
  20121. }
  20122. state.mode = HCRC;
  20123. /* falls through */
  20124. case HCRC:
  20125. if (state.flags & 0x0200) {
  20126. //=== NEEDBITS(16); */
  20127. while (bits < 16) {
  20128. if (have === 0) { break inf_leave; }
  20129. have--;
  20130. hold += input[next++] << bits;
  20131. bits += 8;
  20132. }
  20133. //===//
  20134. if (hold !== (state.check & 0xffff)) {
  20135. strm.msg = 'header crc mismatch';
  20136. state.mode = BAD;
  20137. break;
  20138. }
  20139. //=== INITBITS();
  20140. hold = 0;
  20141. bits = 0;
  20142. //===//
  20143. }
  20144. if (state.head) {
  20145. state.head.hcrc = ((state.flags >> 9) & 1);
  20146. state.head.done = true;
  20147. }
  20148. strm.adler = state.check = 0 /*crc32(0L, Z_NULL, 0)*/;
  20149. state.mode = TYPE;
  20150. break;
  20151. case DICTID:
  20152. //=== NEEDBITS(32); */
  20153. while (bits < 32) {
  20154. if (have === 0) { break inf_leave; }
  20155. have--;
  20156. hold += input[next++] << bits;
  20157. bits += 8;
  20158. }
  20159. //===//
  20160. strm.adler = state.check = ZSWAP32(hold);
  20161. //=== INITBITS();
  20162. hold = 0;
  20163. bits = 0;
  20164. //===//
  20165. state.mode = DICT;
  20166. /* falls through */
  20167. case DICT:
  20168. if (state.havedict === 0) {
  20169. //--- RESTORE() ---
  20170. strm.next_out = put;
  20171. strm.avail_out = left;
  20172. strm.next_in = next;
  20173. strm.avail_in = have;
  20174. state.hold = hold;
  20175. state.bits = bits;
  20176. //---
  20177. return Z_NEED_DICT;
  20178. }
  20179. strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
  20180. state.mode = TYPE;
  20181. /* falls through */
  20182. case TYPE:
  20183. if (flush === Z_BLOCK || flush === Z_TREES) { break inf_leave; }
  20184. /* falls through */
  20185. case TYPEDO:
  20186. if (state.last) {
  20187. //--- BYTEBITS() ---//
  20188. hold >>>= bits & 7;
  20189. bits -= bits & 7;
  20190. //---//
  20191. state.mode = CHECK;
  20192. break;
  20193. }
  20194. //=== NEEDBITS(3); */
  20195. while (bits < 3) {
  20196. if (have === 0) { break inf_leave; }
  20197. have--;
  20198. hold += input[next++] << bits;
  20199. bits += 8;
  20200. }
  20201. //===//
  20202. state.last = (hold & 0x01)/*BITS(1)*/;
  20203. //--- DROPBITS(1) ---//
  20204. hold >>>= 1;
  20205. bits -= 1;
  20206. //---//
  20207. switch ((hold & 0x03)/*BITS(2)*/) {
  20208. case 0: /* stored block */
  20209. //Tracev((stderr, "inflate: stored block%s\n",
  20210. // state.last ? " (last)" : ""));
  20211. state.mode = STORED;
  20212. break;
  20213. case 1: /* fixed block */
  20214. fixedtables(state);
  20215. //Tracev((stderr, "inflate: fixed codes block%s\n",
  20216. // state.last ? " (last)" : ""));
  20217. state.mode = LEN_; /* decode codes */
  20218. if (flush === Z_TREES) {
  20219. //--- DROPBITS(2) ---//
  20220. hold >>>= 2;
  20221. bits -= 2;
  20222. //---//
  20223. break inf_leave;
  20224. }
  20225. break;
  20226. case 2: /* dynamic block */
  20227. //Tracev((stderr, "inflate: dynamic codes block%s\n",
  20228. // state.last ? " (last)" : ""));
  20229. state.mode = TABLE;
  20230. break;
  20231. case 3:
  20232. strm.msg = 'invalid block type';
  20233. state.mode = BAD;
  20234. }
  20235. //--- DROPBITS(2) ---//
  20236. hold >>>= 2;
  20237. bits -= 2;
  20238. //---//
  20239. break;
  20240. case STORED:
  20241. //--- BYTEBITS() ---// /* go to byte boundary */
  20242. hold >>>= bits & 7;
  20243. bits -= bits & 7;
  20244. //---//
  20245. //=== NEEDBITS(32); */
  20246. while (bits < 32) {
  20247. if (have === 0) { break inf_leave; }
  20248. have--;
  20249. hold += input[next++] << bits;
  20250. bits += 8;
  20251. }
  20252. //===//
  20253. if ((hold & 0xffff) !== ((hold >>> 16) ^ 0xffff)) {
  20254. strm.msg = 'invalid stored block lengths';
  20255. state.mode = BAD;
  20256. break;
  20257. }
  20258. state.length = hold & 0xffff;
  20259. //Tracev((stderr, "inflate: stored length %u\n",
  20260. // state.length));
  20261. //=== INITBITS();
  20262. hold = 0;
  20263. bits = 0;
  20264. //===//
  20265. state.mode = COPY_;
  20266. if (flush === Z_TREES) { break inf_leave; }
  20267. /* falls through */
  20268. case COPY_:
  20269. state.mode = COPY;
  20270. /* falls through */
  20271. case COPY:
  20272. copy = state.length;
  20273. if (copy) {
  20274. if (copy > have) { copy = have; }
  20275. if (copy > left) { copy = left; }
  20276. if (copy === 0) { break inf_leave; }
  20277. //--- zmemcpy(put, next, copy); ---
  20278. utils.arraySet(output, input, next, copy, put);
  20279. //---//
  20280. have -= copy;
  20281. next += copy;
  20282. left -= copy;
  20283. put += copy;
  20284. state.length -= copy;
  20285. break;
  20286. }
  20287. //Tracev((stderr, "inflate: stored end\n"));
  20288. state.mode = TYPE;
  20289. break;
  20290. case TABLE:
  20291. //=== NEEDBITS(14); */
  20292. while (bits < 14) {
  20293. if (have === 0) { break inf_leave; }
  20294. have--;
  20295. hold += input[next++] << bits;
  20296. bits += 8;
  20297. }
  20298. //===//
  20299. state.nlen = (hold & 0x1f)/*BITS(5)*/ + 257;
  20300. //--- DROPBITS(5) ---//
  20301. hold >>>= 5;
  20302. bits -= 5;
  20303. //---//
  20304. state.ndist = (hold & 0x1f)/*BITS(5)*/ + 1;
  20305. //--- DROPBITS(5) ---//
  20306. hold >>>= 5;
  20307. bits -= 5;
  20308. //---//
  20309. state.ncode = (hold & 0x0f)/*BITS(4)*/ + 4;
  20310. //--- DROPBITS(4) ---//
  20311. hold >>>= 4;
  20312. bits -= 4;
  20313. //---//
  20314. //#ifndef PKZIP_BUG_WORKAROUND
  20315. if (state.nlen > 286 || state.ndist > 30) {
  20316. strm.msg = 'too many length or distance symbols';
  20317. state.mode = BAD;
  20318. break;
  20319. }
  20320. //#endif
  20321. //Tracev((stderr, "inflate: table sizes ok\n"));
  20322. state.have = 0;
  20323. state.mode = LENLENS;
  20324. /* falls through */
  20325. case LENLENS:
  20326. while (state.have < state.ncode) {
  20327. //=== NEEDBITS(3);
  20328. while (bits < 3) {
  20329. if (have === 0) { break inf_leave; }
  20330. have--;
  20331. hold += input[next++] << bits;
  20332. bits += 8;
  20333. }
  20334. //===//
  20335. state.lens[order[state.have++]] = (hold & 0x07);//BITS(3);
  20336. //--- DROPBITS(3) ---//
  20337. hold >>>= 3;
  20338. bits -= 3;
  20339. //---//
  20340. }
  20341. while (state.have < 19) {
  20342. state.lens[order[state.have++]] = 0;
  20343. }
  20344. // We have separate tables & no pointers. 2 commented lines below not needed.
  20345. //state.next = state.codes;
  20346. //state.lencode = state.next;
  20347. // Switch to use dynamic table
  20348. state.lencode = state.lendyn;
  20349. state.lenbits = 7;
  20350. opts = {bits: state.lenbits};
  20351. ret = inflate_table(CODES, state.lens, 0, 19, state.lencode, 0, state.work, opts);
  20352. state.lenbits = opts.bits;
  20353. if (ret) {
  20354. strm.msg = 'invalid code lengths set';
  20355. state.mode = BAD;
  20356. break;
  20357. }
  20358. //Tracev((stderr, "inflate: code lengths ok\n"));
  20359. state.have = 0;
  20360. state.mode = CODELENS;
  20361. /* falls through */
  20362. case CODELENS:
  20363. while (state.have < state.nlen + state.ndist) {
  20364. for (;;) {
  20365. here = state.lencode[hold & ((1 << state.lenbits) - 1)];/*BITS(state.lenbits)*/
  20366. here_bits = here >>> 24;
  20367. here_op = (here >>> 16) & 0xff;
  20368. here_val = here & 0xffff;
  20369. if ((here_bits) <= bits) { break; }
  20370. //--- PULLBYTE() ---//
  20371. if (have === 0) { break inf_leave; }
  20372. have--;
  20373. hold += input[next++] << bits;
  20374. bits += 8;
  20375. //---//
  20376. }
  20377. if (here_val < 16) {
  20378. //--- DROPBITS(here.bits) ---//
  20379. hold >>>= here_bits;
  20380. bits -= here_bits;
  20381. //---//
  20382. state.lens[state.have++] = here_val;
  20383. }
  20384. else {
  20385. if (here_val === 16) {
  20386. //=== NEEDBITS(here.bits + 2);
  20387. n = here_bits + 2;
  20388. while (bits < n) {
  20389. if (have === 0) { break inf_leave; }
  20390. have--;
  20391. hold += input[next++] << bits;
  20392. bits += 8;
  20393. }
  20394. //===//
  20395. //--- DROPBITS(here.bits) ---//
  20396. hold >>>= here_bits;
  20397. bits -= here_bits;
  20398. //---//
  20399. if (state.have === 0) {
  20400. strm.msg = 'invalid bit length repeat';
  20401. state.mode = BAD;
  20402. break;
  20403. }
  20404. len = state.lens[state.have - 1];
  20405. copy = 3 + (hold & 0x03);//BITS(2);
  20406. //--- DROPBITS(2) ---//
  20407. hold >>>= 2;
  20408. bits -= 2;
  20409. //---//
  20410. }
  20411. else if (here_val === 17) {
  20412. //=== NEEDBITS(here.bits + 3);
  20413. n = here_bits + 3;
  20414. while (bits < n) {
  20415. if (have === 0) { break inf_leave; }
  20416. have--;
  20417. hold += input[next++] << bits;
  20418. bits += 8;
  20419. }
  20420. //===//
  20421. //--- DROPBITS(here.bits) ---//
  20422. hold >>>= here_bits;
  20423. bits -= here_bits;
  20424. //---//
  20425. len = 0;
  20426. copy = 3 + (hold & 0x07);//BITS(3);
  20427. //--- DROPBITS(3) ---//
  20428. hold >>>= 3;
  20429. bits -= 3;
  20430. //---//
  20431. }
  20432. else {
  20433. //=== NEEDBITS(here.bits + 7);
  20434. n = here_bits + 7;
  20435. while (bits < n) {
  20436. if (have === 0) { break inf_leave; }
  20437. have--;
  20438. hold += input[next++] << bits;
  20439. bits += 8;
  20440. }
  20441. //===//
  20442. //--- DROPBITS(here.bits) ---//
  20443. hold >>>= here_bits;
  20444. bits -= here_bits;
  20445. //---//
  20446. len = 0;
  20447. copy = 11 + (hold & 0x7f);//BITS(7);
  20448. //--- DROPBITS(7) ---//
  20449. hold >>>= 7;
  20450. bits -= 7;
  20451. //---//
  20452. }
  20453. if (state.have + copy > state.nlen + state.ndist) {
  20454. strm.msg = 'invalid bit length repeat';
  20455. state.mode = BAD;
  20456. break;
  20457. }
  20458. while (copy--) {
  20459. state.lens[state.have++] = len;
  20460. }
  20461. }
  20462. }
  20463. /* handle error breaks in while */
  20464. if (state.mode === BAD) { break; }
  20465. /* check for end-of-block code (better have one) */
  20466. if (state.lens[256] === 0) {
  20467. strm.msg = 'invalid code -- missing end-of-block';
  20468. state.mode = BAD;
  20469. break;
  20470. }
  20471. /* build code tables -- note: do not change the lenbits or distbits
  20472. values here (9 and 6) without reading the comments in inftrees.h
  20473. concerning the ENOUGH constants, which depend on those values */
  20474. state.lenbits = 9;
  20475. opts = {bits: state.lenbits};
  20476. ret = inflate_table(LENS, state.lens, 0, state.nlen, state.lencode, 0, state.work, opts);
  20477. // We have separate tables & no pointers. 2 commented lines below not needed.
  20478. // state.next_index = opts.table_index;
  20479. state.lenbits = opts.bits;
  20480. // state.lencode = state.next;
  20481. if (ret) {
  20482. strm.msg = 'invalid literal/lengths set';
  20483. state.mode = BAD;
  20484. break;
  20485. }
  20486. state.distbits = 6;
  20487. //state.distcode.copy(state.codes);
  20488. // Switch to use dynamic table
  20489. state.distcode = state.distdyn;
  20490. opts = {bits: state.distbits};
  20491. ret = inflate_table(DISTS, state.lens, state.nlen, state.ndist, state.distcode, 0, state.work, opts);
  20492. // We have separate tables & no pointers. 2 commented lines below not needed.
  20493. // state.next_index = opts.table_index;
  20494. state.distbits = opts.bits;
  20495. // state.distcode = state.next;
  20496. if (ret) {
  20497. strm.msg = 'invalid distances set';
  20498. state.mode = BAD;
  20499. break;
  20500. }
  20501. //Tracev((stderr, 'inflate: codes ok\n'));
  20502. state.mode = LEN_;
  20503. if (flush === Z_TREES) { break inf_leave; }
  20504. /* falls through */
  20505. case LEN_:
  20506. state.mode = LEN;
  20507. /* falls through */
  20508. case LEN:
  20509. if (have >= 6 && left >= 258) {
  20510. //--- RESTORE() ---
  20511. strm.next_out = put;
  20512. strm.avail_out = left;
  20513. strm.next_in = next;
  20514. strm.avail_in = have;
  20515. state.hold = hold;
  20516. state.bits = bits;
  20517. //---
  20518. inflate_fast(strm, _out);
  20519. //--- LOAD() ---
  20520. put = strm.next_out;
  20521. output = strm.output;
  20522. left = strm.avail_out;
  20523. next = strm.next_in;
  20524. input = strm.input;
  20525. have = strm.avail_in;
  20526. hold = state.hold;
  20527. bits = state.bits;
  20528. //---
  20529. if (state.mode === TYPE) {
  20530. state.back = -1;
  20531. }
  20532. break;
  20533. }
  20534. state.back = 0;
  20535. for (;;) {
  20536. here = state.lencode[hold & ((1 << state.lenbits) -1)]; /*BITS(state.lenbits)*/
  20537. here_bits = here >>> 24;
  20538. here_op = (here >>> 16) & 0xff;
  20539. here_val = here & 0xffff;
  20540. if (here_bits <= bits) { break; }
  20541. //--- PULLBYTE() ---//
  20542. if (have === 0) { break inf_leave; }
  20543. have--;
  20544. hold += input[next++] << bits;
  20545. bits += 8;
  20546. //---//
  20547. }
  20548. if (here_op && (here_op & 0xf0) === 0) {
  20549. last_bits = here_bits;
  20550. last_op = here_op;
  20551. last_val = here_val;
  20552. for (;;) {
  20553. here = state.lencode[last_val +
  20554. ((hold & ((1 << (last_bits + last_op)) -1))/*BITS(last.bits + last.op)*/ >> last_bits)];
  20555. here_bits = here >>> 24;
  20556. here_op = (here >>> 16) & 0xff;
  20557. here_val = here & 0xffff;
  20558. if ((last_bits + here_bits) <= bits) { break; }
  20559. //--- PULLBYTE() ---//
  20560. if (have === 0) { break inf_leave; }
  20561. have--;
  20562. hold += input[next++] << bits;
  20563. bits += 8;
  20564. //---//
  20565. }
  20566. //--- DROPBITS(last.bits) ---//
  20567. hold >>>= last_bits;
  20568. bits -= last_bits;
  20569. //---//
  20570. state.back += last_bits;
  20571. }
  20572. //--- DROPBITS(here.bits) ---//
  20573. hold >>>= here_bits;
  20574. bits -= here_bits;
  20575. //---//
  20576. state.back += here_bits;
  20577. state.length = here_val;
  20578. if (here_op === 0) {
  20579. //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
  20580. // "inflate: literal '%c'\n" :
  20581. // "inflate: literal 0x%02x\n", here.val));
  20582. state.mode = LIT;
  20583. break;
  20584. }
  20585. if (here_op & 32) {
  20586. //Tracevv((stderr, "inflate: end of block\n"));
  20587. state.back = -1;
  20588. state.mode = TYPE;
  20589. break;
  20590. }
  20591. if (here_op & 64) {
  20592. strm.msg = 'invalid literal/length code';
  20593. state.mode = BAD;
  20594. break;
  20595. }
  20596. state.extra = here_op & 15;
  20597. state.mode = LENEXT;
  20598. /* falls through */
  20599. case LENEXT:
  20600. if (state.extra) {
  20601. //=== NEEDBITS(state.extra);
  20602. n = state.extra;
  20603. while (bits < n) {
  20604. if (have === 0) { break inf_leave; }
  20605. have--;
  20606. hold += input[next++] << bits;
  20607. bits += 8;
  20608. }
  20609. //===//
  20610. state.length += hold & ((1 << state.extra) -1)/*BITS(state.extra)*/;
  20611. //--- DROPBITS(state.extra) ---//
  20612. hold >>>= state.extra;
  20613. bits -= state.extra;
  20614. //---//
  20615. state.back += state.extra;
  20616. }
  20617. //Tracevv((stderr, "inflate: length %u\n", state.length));
  20618. state.was = state.length;
  20619. state.mode = DIST;
  20620. /* falls through */
  20621. case DIST:
  20622. for (;;) {
  20623. here = state.distcode[hold & ((1 << state.distbits) -1)];/*BITS(state.distbits)*/
  20624. here_bits = here >>> 24;
  20625. here_op = (here >>> 16) & 0xff;
  20626. here_val = here & 0xffff;
  20627. if ((here_bits) <= bits) { break; }
  20628. //--- PULLBYTE() ---//
  20629. if (have === 0) { break inf_leave; }
  20630. have--;
  20631. hold += input[next++] << bits;
  20632. bits += 8;
  20633. //---//
  20634. }
  20635. if ((here_op & 0xf0) === 0) {
  20636. last_bits = here_bits;
  20637. last_op = here_op;
  20638. last_val = here_val;
  20639. for (;;) {
  20640. here = state.distcode[last_val +
  20641. ((hold & ((1 << (last_bits + last_op)) -1))/*BITS(last.bits + last.op)*/ >> last_bits)];
  20642. here_bits = here >>> 24;
  20643. here_op = (here >>> 16) & 0xff;
  20644. here_val = here & 0xffff;
  20645. if ((last_bits + here_bits) <= bits) { break; }
  20646. //--- PULLBYTE() ---//
  20647. if (have === 0) { break inf_leave; }
  20648. have--;
  20649. hold += input[next++] << bits;
  20650. bits += 8;
  20651. //---//
  20652. }
  20653. //--- DROPBITS(last.bits) ---//
  20654. hold >>>= last_bits;
  20655. bits -= last_bits;
  20656. //---//
  20657. state.back += last_bits;
  20658. }
  20659. //--- DROPBITS(here.bits) ---//
  20660. hold >>>= here_bits;
  20661. bits -= here_bits;
  20662. //---//
  20663. state.back += here_bits;
  20664. if (here_op & 64) {
  20665. strm.msg = 'invalid distance code';
  20666. state.mode = BAD;
  20667. break;
  20668. }
  20669. state.offset = here_val;
  20670. state.extra = (here_op) & 15;
  20671. state.mode = DISTEXT;
  20672. /* falls through */
  20673. case DISTEXT:
  20674. if (state.extra) {
  20675. //=== NEEDBITS(state.extra);
  20676. n = state.extra;
  20677. while (bits < n) {
  20678. if (have === 0) { break inf_leave; }
  20679. have--;
  20680. hold += input[next++] << bits;
  20681. bits += 8;
  20682. }
  20683. //===//
  20684. state.offset += hold & ((1 << state.extra) -1)/*BITS(state.extra)*/;
  20685. //--- DROPBITS(state.extra) ---//
  20686. hold >>>= state.extra;
  20687. bits -= state.extra;
  20688. //---//
  20689. state.back += state.extra;
  20690. }
  20691. //#ifdef INFLATE_STRICT
  20692. if (state.offset > state.dmax) {
  20693. strm.msg = 'invalid distance too far back';
  20694. state.mode = BAD;
  20695. break;
  20696. }
  20697. //#endif
  20698. //Tracevv((stderr, "inflate: distance %u\n", state.offset));
  20699. state.mode = MATCH;
  20700. /* falls through */
  20701. case MATCH:
  20702. if (left === 0) { break inf_leave; }
  20703. copy = _out - left;
  20704. if (state.offset > copy) { /* copy from window */
  20705. copy = state.offset - copy;
  20706. if (copy > state.whave) {
  20707. if (state.sane) {
  20708. strm.msg = 'invalid distance too far back';
  20709. state.mode = BAD;
  20710. break;
  20711. }
  20712. // (!) This block is disabled in zlib defailts,
  20713. // don't enable it for binary compatibility
  20714. //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
  20715. // Trace((stderr, "inflate.c too far\n"));
  20716. // copy -= state.whave;
  20717. // if (copy > state.length) { copy = state.length; }
  20718. // if (copy > left) { copy = left; }
  20719. // left -= copy;
  20720. // state.length -= copy;
  20721. // do {
  20722. // output[put++] = 0;
  20723. // } while (--copy);
  20724. // if (state.length === 0) { state.mode = LEN; }
  20725. // break;
  20726. //#endif
  20727. }
  20728. if (copy > state.wnext) {
  20729. copy -= state.wnext;
  20730. from = state.wsize - copy;
  20731. }
  20732. else {
  20733. from = state.wnext - copy;
  20734. }
  20735. if (copy > state.length) { copy = state.length; }
  20736. from_source = state.window;
  20737. }
  20738. else { /* copy from output */
  20739. from_source = output;
  20740. from = put - state.offset;
  20741. copy = state.length;
  20742. }
  20743. if (copy > left) { copy = left; }
  20744. left -= copy;
  20745. state.length -= copy;
  20746. do {
  20747. output[put++] = from_source[from++];
  20748. } while (--copy);
  20749. if (state.length === 0) { state.mode = LEN; }
  20750. break;
  20751. case LIT:
  20752. if (left === 0) { break inf_leave; }
  20753. output[put++] = state.length;
  20754. left--;
  20755. state.mode = LEN;
  20756. break;
  20757. case CHECK:
  20758. if (state.wrap) {
  20759. //=== NEEDBITS(32);
  20760. while (bits < 32) {
  20761. if (have === 0) { break inf_leave; }
  20762. have--;
  20763. // Use '|' insdead of '+' to make sure that result is signed
  20764. hold |= input[next++] << bits;
  20765. bits += 8;
  20766. }
  20767. //===//
  20768. _out -= left;
  20769. strm.total_out += _out;
  20770. state.total += _out;
  20771. if (_out) {
  20772. strm.adler = state.check =
  20773. /*UPDATE(state.check, put - _out, _out);*/
  20774. (state.flags ? crc32(state.check, output, _out, put - _out) : adler32(state.check, output, _out, put - _out));
  20775. }
  20776. _out = left;
  20777. // NB: crc32 stored as signed 32-bit int, ZSWAP32 returns signed too
  20778. if ((state.flags ? hold : ZSWAP32(hold)) !== state.check) {
  20779. strm.msg = 'incorrect data check';
  20780. state.mode = BAD;
  20781. break;
  20782. }
  20783. //=== INITBITS();
  20784. hold = 0;
  20785. bits = 0;
  20786. //===//
  20787. //Tracev((stderr, "inflate: check matches trailer\n"));
  20788. }
  20789. state.mode = LENGTH;
  20790. /* falls through */
  20791. case LENGTH:
  20792. if (state.wrap && state.flags) {
  20793. //=== NEEDBITS(32);
  20794. while (bits < 32) {
  20795. if (have === 0) { break inf_leave; }
  20796. have--;
  20797. hold += input[next++] << bits;
  20798. bits += 8;
  20799. }
  20800. //===//
  20801. if (hold !== (state.total & 0xffffffff)) {
  20802. strm.msg = 'incorrect length check';
  20803. state.mode = BAD;
  20804. break;
  20805. }
  20806. //=== INITBITS();
  20807. hold = 0;
  20808. bits = 0;
  20809. //===//
  20810. //Tracev((stderr, "inflate: length matches trailer\n"));
  20811. }
  20812. state.mode = DONE;
  20813. /* falls through */
  20814. case DONE:
  20815. ret = Z_STREAM_END;
  20816. break inf_leave;
  20817. case BAD:
  20818. ret = Z_DATA_ERROR;
  20819. break inf_leave;
  20820. case MEM:
  20821. return Z_MEM_ERROR;
  20822. case SYNC:
  20823. /* falls through */
  20824. default:
  20825. return Z_STREAM_ERROR;
  20826. }
  20827. }
  20828. // inf_leave <- here is real place for "goto inf_leave", emulated via "break inf_leave"
  20829. /*
  20830. Return from inflate(), updating the total counts and the check value.
  20831. If there was no progress during the inflate() call, return a buffer
  20832. error. Call updatewindow() to create and/or update the window state.
  20833. Note: a memory error from inflate() is non-recoverable.
  20834. */
  20835. //--- RESTORE() ---
  20836. strm.next_out = put;
  20837. strm.avail_out = left;
  20838. strm.next_in = next;
  20839. strm.avail_in = have;
  20840. state.hold = hold;
  20841. state.bits = bits;
  20842. //---
  20843. if (state.wsize || (_out !== strm.avail_out && state.mode < BAD &&
  20844. (state.mode < CHECK || flush !== Z_FINISH))) {
  20845. if (updatewindow(strm, strm.output, strm.next_out, _out - strm.avail_out)) {
  20846. state.mode = MEM;
  20847. return Z_MEM_ERROR;
  20848. }
  20849. }
  20850. _in -= strm.avail_in;
  20851. _out -= strm.avail_out;
  20852. strm.total_in += _in;
  20853. strm.total_out += _out;
  20854. state.total += _out;
  20855. if (state.wrap && _out) {
  20856. strm.adler = state.check = /*UPDATE(state.check, strm.next_out - _out, _out);*/
  20857. (state.flags ? crc32(state.check, output, _out, strm.next_out - _out) : adler32(state.check, output, _out, strm.next_out - _out));
  20858. }
  20859. strm.data_type = state.bits + (state.last ? 64 : 0) +
  20860. (state.mode === TYPE ? 128 : 0) +
  20861. (state.mode === LEN_ || state.mode === COPY_ ? 256 : 0);
  20862. if (((_in === 0 && _out === 0) || flush === Z_FINISH) && ret === Z_OK) {
  20863. ret = Z_BUF_ERROR;
  20864. }
  20865. return ret;
  20866. }
  20867. function inflateEnd(strm) {
  20868. if (!strm || !strm.state /*|| strm->zfree == (free_func)0*/) {
  20869. return Z_STREAM_ERROR;
  20870. }
  20871. var state = strm.state;
  20872. if (state.window) {
  20873. state.window = null;
  20874. }
  20875. strm.state = null;
  20876. return Z_OK;
  20877. }
  20878. function inflateGetHeader(strm, head) {
  20879. var state;
  20880. /* check state */
  20881. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  20882. state = strm.state;
  20883. if ((state.wrap & 2) === 0) { return Z_STREAM_ERROR; }
  20884. /* save header structure */
  20885. state.head = head;
  20886. head.done = false;
  20887. return Z_OK;
  20888. }
  20889. exports.inflateReset = inflateReset;
  20890. exports.inflateReset2 = inflateReset2;
  20891. exports.inflateResetKeep = inflateResetKeep;
  20892. exports.inflateInit = inflateInit;
  20893. exports.inflateInit2 = inflateInit2;
  20894. exports.inflate = inflate;
  20895. exports.inflateEnd = inflateEnd;
  20896. exports.inflateGetHeader = inflateGetHeader;
  20897. exports.inflateInfo = 'pako inflate (from Nodeca project)';
  20898. /* Not implemented
  20899. exports.inflateCopy = inflateCopy;
  20900. exports.inflateGetDictionary = inflateGetDictionary;
  20901. exports.inflateMark = inflateMark;
  20902. exports.inflatePrime = inflatePrime;
  20903. exports.inflateSetDictionary = inflateSetDictionary;
  20904. exports.inflateSync = inflateSync;
  20905. exports.inflateSyncPoint = inflateSyncPoint;
  20906. exports.inflateUndermine = inflateUndermine;
  20907. */
  20908. },{"../utils/common":65,"./adler32":67,"./crc32":69,"./inffast":72,"./inftrees":74}],74:[function(require,module,exports){
  20909. 'use strict';
  20910. var utils = require('../utils/common');
  20911. var MAXBITS = 15;
  20912. var ENOUGH_LENS = 852;
  20913. var ENOUGH_DISTS = 592;
  20914. //var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
  20915. var CODES = 0;
  20916. var LENS = 1;
  20917. var DISTS = 2;
  20918. var lbase = [ /* Length codes 257..285 base */
  20919. 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
  20920. 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0
  20921. ];
  20922. var lext = [ /* Length codes 257..285 extra */
  20923. 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,
  20924. 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 72, 78
  20925. ];
  20926. var dbase = [ /* Distance codes 0..29 base */
  20927. 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
  20928. 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
  20929. 8193, 12289, 16385, 24577, 0, 0
  20930. ];
  20931. var dext = [ /* Distance codes 0..29 extra */
  20932. 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,
  20933. 23, 23, 24, 24, 25, 25, 26, 26, 27, 27,
  20934. 28, 28, 29, 29, 64, 64
  20935. ];
  20936. module.exports = function inflate_table(type, lens, lens_index, codes, table, table_index, work, opts)
  20937. {
  20938. var bits = opts.bits;
  20939. //here = opts.here; /* table entry for duplication */
  20940. var len = 0; /* a code's length in bits */
  20941. var sym = 0; /* index of code symbols */
  20942. var min = 0, max = 0; /* minimum and maximum code lengths */
  20943. var root = 0; /* number of index bits for root table */
  20944. var curr = 0; /* number of index bits for current table */
  20945. var drop = 0; /* code bits to drop for sub-table */
  20946. var left = 0; /* number of prefix codes available */
  20947. var used = 0; /* code entries in table used */
  20948. var huff = 0; /* Huffman code */
  20949. var incr; /* for incrementing code, index */
  20950. var fill; /* index for replicating entries */
  20951. var low; /* low bits for current root entry */
  20952. var mask; /* mask for low root bits */
  20953. var next; /* next available space in table */
  20954. var base = null; /* base value table to use */
  20955. var base_index = 0;
  20956. // var shoextra; /* extra bits table to use */
  20957. var end; /* use base and extra for symbol > end */
  20958. var count = new utils.Buf16(MAXBITS+1); //[MAXBITS+1]; /* number of codes of each length */
  20959. var offs = new utils.Buf16(MAXBITS+1); //[MAXBITS+1]; /* offsets in table for each length */
  20960. var extra = null;
  20961. var extra_index = 0;
  20962. var here_bits, here_op, here_val;
  20963. /*
  20964. Process a set of code lengths to create a canonical Huffman code. The
  20965. code lengths are lens[0..codes-1]. Each length corresponds to the
  20966. symbols 0..codes-1. The Huffman code is generated by first sorting the
  20967. symbols by length from short to long, and retaining the symbol order
  20968. for codes with equal lengths. Then the code starts with all zero bits
  20969. for the first code of the shortest length, and the codes are integer
  20970. increments for the same length, and zeros are appended as the length
  20971. increases. For the deflate format, these bits are stored backwards
  20972. from their more natural integer increment ordering, and so when the
  20973. decoding tables are built in the large loop below, the integer codes
  20974. are incremented backwards.
  20975. This routine assumes, but does not check, that all of the entries in
  20976. lens[] are in the range 0..MAXBITS. The caller must assure this.
  20977. 1..MAXBITS is interpreted as that code length. zero means that that
  20978. symbol does not occur in this code.
  20979. The codes are sorted by computing a count of codes for each length,
  20980. creating from that a table of starting indices for each length in the
  20981. sorted table, and then entering the symbols in order in the sorted
  20982. table. The sorted table is work[], with that space being provided by
  20983. the caller.
  20984. The length counts are used for other purposes as well, i.e. finding
  20985. the minimum and maximum length codes, determining if there are any
  20986. codes at all, checking for a valid set of lengths, and looking ahead
  20987. at length counts to determine sub-table sizes when building the
  20988. decoding tables.
  20989. */
  20990. /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */
  20991. for (len = 0; len <= MAXBITS; len++) {
  20992. count[len] = 0;
  20993. }
  20994. for (sym = 0; sym < codes; sym++) {
  20995. count[lens[lens_index + sym]]++;
  20996. }
  20997. /* bound code lengths, force root to be within code lengths */
  20998. root = bits;
  20999. for (max = MAXBITS; max >= 1; max--) {
  21000. if (count[max] !== 0) { break; }
  21001. }
  21002. if (root > max) {
  21003. root = max;
  21004. }
  21005. if (max === 0) { /* no symbols to code at all */
  21006. //table.op[opts.table_index] = 64; //here.op = (var char)64; /* invalid code marker */
  21007. //table.bits[opts.table_index] = 1; //here.bits = (var char)1;
  21008. //table.val[opts.table_index++] = 0; //here.val = (var short)0;
  21009. table[table_index++] = (1 << 24) | (64 << 16) | 0;
  21010. //table.op[opts.table_index] = 64;
  21011. //table.bits[opts.table_index] = 1;
  21012. //table.val[opts.table_index++] = 0;
  21013. table[table_index++] = (1 << 24) | (64 << 16) | 0;
  21014. opts.bits = 1;
  21015. return 0; /* no symbols, but wait for decoding to report error */
  21016. }
  21017. for (min = 1; min < max; min++) {
  21018. if (count[min] !== 0) { break; }
  21019. }
  21020. if (root < min) {
  21021. root = min;
  21022. }
  21023. /* check for an over-subscribed or incomplete set of lengths */
  21024. left = 1;
  21025. for (len = 1; len <= MAXBITS; len++) {
  21026. left <<= 1;
  21027. left -= count[len];
  21028. if (left < 0) {
  21029. return -1;
  21030. } /* over-subscribed */
  21031. }
  21032. if (left > 0 && (type === CODES || max !== 1)) {
  21033. return -1; /* incomplete set */
  21034. }
  21035. /* generate offsets into symbol table for each length for sorting */
  21036. offs[1] = 0;
  21037. for (len = 1; len < MAXBITS; len++) {
  21038. offs[len + 1] = offs[len] + count[len];
  21039. }
  21040. /* sort symbols by length, by symbol order within each length */
  21041. for (sym = 0; sym < codes; sym++) {
  21042. if (lens[lens_index + sym] !== 0) {
  21043. work[offs[lens[lens_index + sym]]++] = sym;
  21044. }
  21045. }
  21046. /*
  21047. Create and fill in decoding tables. In this loop, the table being
  21048. filled is at next and has curr index bits. The code being used is huff
  21049. with length len. That code is converted to an index by dropping drop
  21050. bits off of the bottom. For codes where len is less than drop + curr,
  21051. those top drop + curr - len bits are incremented through all values to
  21052. fill the table with replicated entries.
  21053. root is the number of index bits for the root table. When len exceeds
  21054. root, sub-tables are created pointed to by the root entry with an index
  21055. of the low root bits of huff. This is saved in low to check for when a
  21056. new sub-table should be started. drop is zero when the root table is
  21057. being filled, and drop is root when sub-tables are being filled.
  21058. When a new sub-table is needed, it is necessary to look ahead in the
  21059. code lengths to determine what size sub-table is needed. The length
  21060. counts are used for this, and so count[] is decremented as codes are
  21061. entered in the tables.
  21062. used keeps track of how many table entries have been allocated from the
  21063. provided *table space. It is checked for LENS and DIST tables against
  21064. the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in
  21065. the initial root table size constants. See the comments in inftrees.h
  21066. for more information.
  21067. sym increments through all symbols, and the loop terminates when
  21068. all codes of length max, i.e. all codes, have been processed. This
  21069. routine permits incomplete codes, so another loop after this one fills
  21070. in the rest of the decoding tables with invalid code markers.
  21071. */
  21072. /* set up for code type */
  21073. // poor man optimization - use if-else instead of switch,
  21074. // to avoid deopts in old v8
  21075. if (type === CODES) {
  21076. base = extra = work; /* dummy value--not used */
  21077. end = 19;
  21078. } else if (type === LENS) {
  21079. base = lbase;
  21080. base_index -= 257;
  21081. extra = lext;
  21082. extra_index -= 257;
  21083. end = 256;
  21084. } else { /* DISTS */
  21085. base = dbase;
  21086. extra = dext;
  21087. end = -1;
  21088. }
  21089. /* initialize opts for loop */
  21090. huff = 0; /* starting code */
  21091. sym = 0; /* starting code symbol */
  21092. len = min; /* starting code length */
  21093. next = table_index; /* current table to fill in */
  21094. curr = root; /* current table index bits */
  21095. drop = 0; /* current bits to drop from code for index */
  21096. low = -1; /* trigger new sub-table when len > root */
  21097. used = 1 << root; /* use root table entries */
  21098. mask = used - 1; /* mask for comparing low */
  21099. /* check available table space */
  21100. if ((type === LENS && used > ENOUGH_LENS) ||
  21101. (type === DISTS && used > ENOUGH_DISTS)) {
  21102. return 1;
  21103. }
  21104. var i=0;
  21105. /* process all codes and make table entries */
  21106. for (;;) {
  21107. i++;
  21108. /* create table entry */
  21109. here_bits = len - drop;
  21110. if (work[sym] < end) {
  21111. here_op = 0;
  21112. here_val = work[sym];
  21113. }
  21114. else if (work[sym] > end) {
  21115. here_op = extra[extra_index + work[sym]];
  21116. here_val = base[base_index + work[sym]];
  21117. }
  21118. else {
  21119. here_op = 32 + 64; /* end of block */
  21120. here_val = 0;
  21121. }
  21122. /* replicate for those indices with low len bits equal to huff */
  21123. incr = 1 << (len - drop);
  21124. fill = 1 << curr;
  21125. min = fill; /* save offset to next table */
  21126. do {
  21127. fill -= incr;
  21128. table[next + (huff >> drop) + fill] = (here_bits << 24) | (here_op << 16) | here_val |0;
  21129. } while (fill !== 0);
  21130. /* backwards increment the len-bit code huff */
  21131. incr = 1 << (len - 1);
  21132. while (huff & incr) {
  21133. incr >>= 1;
  21134. }
  21135. if (incr !== 0) {
  21136. huff &= incr - 1;
  21137. huff += incr;
  21138. } else {
  21139. huff = 0;
  21140. }
  21141. /* go to next symbol, update count, len */
  21142. sym++;
  21143. if (--count[len] === 0) {
  21144. if (len === max) { break; }
  21145. len = lens[lens_index + work[sym]];
  21146. }
  21147. /* create new sub-table if needed */
  21148. if (len > root && (huff & mask) !== low) {
  21149. /* if first time, transition to sub-tables */
  21150. if (drop === 0) {
  21151. drop = root;
  21152. }
  21153. /* increment past last table */
  21154. next += min; /* here min is 1 << curr */
  21155. /* determine length of next table */
  21156. curr = len - drop;
  21157. left = 1 << curr;
  21158. while (curr + drop < max) {
  21159. left -= count[curr + drop];
  21160. if (left <= 0) { break; }
  21161. curr++;
  21162. left <<= 1;
  21163. }
  21164. /* check for enough space */
  21165. used += 1 << curr;
  21166. if ((type === LENS && used > ENOUGH_LENS) ||
  21167. (type === DISTS && used > ENOUGH_DISTS)) {
  21168. return 1;
  21169. }
  21170. /* point entry in root table to sub-table */
  21171. low = huff & mask;
  21172. /*table.op[low] = curr;
  21173. table.bits[low] = root;
  21174. table.val[low] = next - opts.table_index;*/
  21175. table[low] = (root << 24) | (curr << 16) | (next - table_index) |0;
  21176. }
  21177. }
  21178. /* fill in remaining table entry if code is incomplete (guaranteed to have
  21179. at most one remaining entry, since if the code is incomplete, the
  21180. maximum code length that was allowed to get this far is one bit) */
  21181. if (huff !== 0) {
  21182. //table.op[next + huff] = 64; /* invalid code marker */
  21183. //table.bits[next + huff] = len - drop;
  21184. //table.val[next + huff] = 0;
  21185. table[next + huff] = ((len - drop) << 24) | (64 << 16) |0;
  21186. }
  21187. /* set return parameters */
  21188. //opts.table_index += used;
  21189. opts.bits = root;
  21190. return 0;
  21191. };
  21192. },{"../utils/common":65}],75:[function(require,module,exports){
  21193. 'use strict';
  21194. module.exports = {
  21195. '2': 'need dictionary', /* Z_NEED_DICT 2 */
  21196. '1': 'stream end', /* Z_STREAM_END 1 */
  21197. '0': '', /* Z_OK 0 */
  21198. '-1': 'file error', /* Z_ERRNO (-1) */
  21199. '-2': 'stream error', /* Z_STREAM_ERROR (-2) */
  21200. '-3': 'data error', /* Z_DATA_ERROR (-3) */
  21201. '-4': 'insufficient memory', /* Z_MEM_ERROR (-4) */
  21202. '-5': 'buffer error', /* Z_BUF_ERROR (-5) */
  21203. '-6': 'incompatible version' /* Z_VERSION_ERROR (-6) */
  21204. };
  21205. },{}],76:[function(require,module,exports){
  21206. 'use strict';
  21207. var utils = require('../utils/common');
  21208. /* Public constants ==========================================================*/
  21209. /* ===========================================================================*/
  21210. //var Z_FILTERED = 1;
  21211. //var Z_HUFFMAN_ONLY = 2;
  21212. //var Z_RLE = 3;
  21213. var Z_FIXED = 4;
  21214. //var Z_DEFAULT_STRATEGY = 0;
  21215. /* Possible values of the data_type field (though see inflate()) */
  21216. var Z_BINARY = 0;
  21217. var Z_TEXT = 1;
  21218. //var Z_ASCII = 1; // = Z_TEXT
  21219. var Z_UNKNOWN = 2;
  21220. /*============================================================================*/
  21221. function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
  21222. // From zutil.h
  21223. var STORED_BLOCK = 0;
  21224. var STATIC_TREES = 1;
  21225. var DYN_TREES = 2;
  21226. /* The three kinds of block type */
  21227. var MIN_MATCH = 3;
  21228. var MAX_MATCH = 258;
  21229. /* The minimum and maximum match lengths */
  21230. // From deflate.h
  21231. /* ===========================================================================
  21232. * Internal compression state.
  21233. */
  21234. var LENGTH_CODES = 29;
  21235. /* number of length codes, not counting the special END_BLOCK code */
  21236. var LITERALS = 256;
  21237. /* number of literal bytes 0..255 */
  21238. var L_CODES = LITERALS + 1 + LENGTH_CODES;
  21239. /* number of Literal or Length codes, including the END_BLOCK code */
  21240. var D_CODES = 30;
  21241. /* number of distance codes */
  21242. var BL_CODES = 19;
  21243. /* number of codes used to transfer the bit lengths */
  21244. var HEAP_SIZE = 2*L_CODES + 1;
  21245. /* maximum heap size */
  21246. var MAX_BITS = 15;
  21247. /* All codes must not exceed MAX_BITS bits */
  21248. var Buf_size = 16;
  21249. /* size of bit buffer in bi_buf */
  21250. /* ===========================================================================
  21251. * Constants
  21252. */
  21253. var MAX_BL_BITS = 7;
  21254. /* Bit length codes must not exceed MAX_BL_BITS bits */
  21255. var END_BLOCK = 256;
  21256. /* end of block literal code */
  21257. var REP_3_6 = 16;
  21258. /* repeat previous bit length 3-6 times (2 bits of repeat count) */
  21259. var REPZ_3_10 = 17;
  21260. /* repeat a zero length 3-10 times (3 bits of repeat count) */
  21261. var REPZ_11_138 = 18;
  21262. /* repeat a zero length 11-138 times (7 bits of repeat count) */
  21263. var extra_lbits = /* extra bits for each length code */
  21264. [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];
  21265. var extra_dbits = /* extra bits for each distance code */
  21266. [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];
  21267. var extra_blbits = /* extra bits for each bit length code */
  21268. [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7];
  21269. var bl_order =
  21270. [16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];
  21271. /* The lengths of the bit length codes are sent in order of decreasing
  21272. * probability, to avoid transmitting the lengths for unused bit length codes.
  21273. */
  21274. /* ===========================================================================
  21275. * Local data. These are initialized only once.
  21276. */
  21277. // We pre-fill arrays with 0 to avoid uninitialized gaps
  21278. var DIST_CODE_LEN = 512; /* see definition of array dist_code below */
  21279. // !!!! Use flat array insdead of structure, Freq = i*2, Len = i*2+1
  21280. var static_ltree = new Array((L_CODES+2) * 2);
  21281. zero(static_ltree);
  21282. /* The static literal tree. Since the bit lengths are imposed, there is no
  21283. * need for the L_CODES extra codes used during heap construction. However
  21284. * The codes 286 and 287 are needed to build a canonical tree (see _tr_init
  21285. * below).
  21286. */
  21287. var static_dtree = new Array(D_CODES * 2);
  21288. zero(static_dtree);
  21289. /* The static distance tree. (Actually a trivial tree since all codes use
  21290. * 5 bits.)
  21291. */
  21292. var _dist_code = new Array(DIST_CODE_LEN);
  21293. zero(_dist_code);
  21294. /* Distance codes. The first 256 values correspond to the distances
  21295. * 3 .. 258, the last 256 values correspond to the top 8 bits of
  21296. * the 15 bit distances.
  21297. */
  21298. var _length_code = new Array(MAX_MATCH-MIN_MATCH+1);
  21299. zero(_length_code);
  21300. /* length code for each normalized match length (0 == MIN_MATCH) */
  21301. var base_length = new Array(LENGTH_CODES);
  21302. zero(base_length);
  21303. /* First normalized length for each code (0 = MIN_MATCH) */
  21304. var base_dist = new Array(D_CODES);
  21305. zero(base_dist);
  21306. /* First normalized distance for each code (0 = distance of 1) */
  21307. var StaticTreeDesc = function (static_tree, extra_bits, extra_base, elems, max_length) {
  21308. this.static_tree = static_tree; /* static tree or NULL */
  21309. this.extra_bits = extra_bits; /* extra bits for each code or NULL */
  21310. this.extra_base = extra_base; /* base index for extra_bits */
  21311. this.elems = elems; /* max number of elements in the tree */
  21312. this.max_length = max_length; /* max bit length for the codes */
  21313. // show if `static_tree` has data or dummy - needed for monomorphic objects
  21314. this.has_stree = static_tree && static_tree.length;
  21315. };
  21316. var static_l_desc;
  21317. var static_d_desc;
  21318. var static_bl_desc;
  21319. var TreeDesc = function(dyn_tree, stat_desc) {
  21320. this.dyn_tree = dyn_tree; /* the dynamic tree */
  21321. this.max_code = 0; /* largest code with non zero frequency */
  21322. this.stat_desc = stat_desc; /* the corresponding static tree */
  21323. };
  21324. function d_code(dist) {
  21325. return dist < 256 ? _dist_code[dist] : _dist_code[256 + (dist >>> 7)];
  21326. }
  21327. /* ===========================================================================
  21328. * Output a short LSB first on the stream.
  21329. * IN assertion: there is enough room in pendingBuf.
  21330. */
  21331. function put_short (s, w) {
  21332. // put_byte(s, (uch)((w) & 0xff));
  21333. // put_byte(s, (uch)((ush)(w) >> 8));
  21334. s.pending_buf[s.pending++] = (w) & 0xff;
  21335. s.pending_buf[s.pending++] = (w >>> 8) & 0xff;
  21336. }
  21337. /* ===========================================================================
  21338. * Send a value on a given number of bits.
  21339. * IN assertion: length <= 16 and value fits in length bits.
  21340. */
  21341. function send_bits(s, value, length) {
  21342. if (s.bi_valid > (Buf_size - length)) {
  21343. s.bi_buf |= (value << s.bi_valid) & 0xffff;
  21344. put_short(s, s.bi_buf);
  21345. s.bi_buf = value >> (Buf_size - s.bi_valid);
  21346. s.bi_valid += length - Buf_size;
  21347. } else {
  21348. s.bi_buf |= (value << s.bi_valid) & 0xffff;
  21349. s.bi_valid += length;
  21350. }
  21351. }
  21352. function send_code(s, c, tree) {
  21353. send_bits(s, tree[c*2]/*.Code*/, tree[c*2 + 1]/*.Len*/);
  21354. }
  21355. /* ===========================================================================
  21356. * Reverse the first len bits of a code, using straightforward code (a faster
  21357. * method would use a table)
  21358. * IN assertion: 1 <= len <= 15
  21359. */
  21360. function bi_reverse(code, len) {
  21361. var res = 0;
  21362. do {
  21363. res |= code & 1;
  21364. code >>>= 1;
  21365. res <<= 1;
  21366. } while (--len > 0);
  21367. return res >>> 1;
  21368. }
  21369. /* ===========================================================================
  21370. * Flush the bit buffer, keeping at most 7 bits in it.
  21371. */
  21372. function bi_flush(s) {
  21373. if (s.bi_valid === 16) {
  21374. put_short(s, s.bi_buf);
  21375. s.bi_buf = 0;
  21376. s.bi_valid = 0;
  21377. } else if (s.bi_valid >= 8) {
  21378. s.pending_buf[s.pending++] = s.bi_buf & 0xff;
  21379. s.bi_buf >>= 8;
  21380. s.bi_valid -= 8;
  21381. }
  21382. }
  21383. /* ===========================================================================
  21384. * Compute the optimal bit lengths for a tree and update the total bit length
  21385. * for the current block.
  21386. * IN assertion: the fields freq and dad are set, heap[heap_max] and
  21387. * above are the tree nodes sorted by increasing frequency.
  21388. * OUT assertions: the field len is set to the optimal bit length, the
  21389. * array bl_count contains the frequencies for each bit length.
  21390. * The length opt_len is updated; static_len is also updated if stree is
  21391. * not null.
  21392. */
  21393. function gen_bitlen(s, desc)
  21394. // deflate_state *s;
  21395. // tree_desc *desc; /* the tree descriptor */
  21396. {
  21397. var tree = desc.dyn_tree;
  21398. var max_code = desc.max_code;
  21399. var stree = desc.stat_desc.static_tree;
  21400. var has_stree = desc.stat_desc.has_stree;
  21401. var extra = desc.stat_desc.extra_bits;
  21402. var base = desc.stat_desc.extra_base;
  21403. var max_length = desc.stat_desc.max_length;
  21404. var h; /* heap index */
  21405. var n, m; /* iterate over the tree elements */
  21406. var bits; /* bit length */
  21407. var xbits; /* extra bits */
  21408. var f; /* frequency */
  21409. var overflow = 0; /* number of elements with bit length too large */
  21410. for (bits = 0; bits <= MAX_BITS; bits++) {
  21411. s.bl_count[bits] = 0;
  21412. }
  21413. /* In a first pass, compute the optimal bit lengths (which may
  21414. * overflow in the case of the bit length tree).
  21415. */
  21416. tree[s.heap[s.heap_max]*2 + 1]/*.Len*/ = 0; /* root of the heap */
  21417. for (h = s.heap_max+1; h < HEAP_SIZE; h++) {
  21418. n = s.heap[h];
  21419. bits = tree[tree[n*2 +1]/*.Dad*/ * 2 + 1]/*.Len*/ + 1;
  21420. if (bits > max_length) {
  21421. bits = max_length;
  21422. overflow++;
  21423. }
  21424. tree[n*2 + 1]/*.Len*/ = bits;
  21425. /* We overwrite tree[n].Dad which is no longer needed */
  21426. if (n > max_code) { continue; } /* not a leaf node */
  21427. s.bl_count[bits]++;
  21428. xbits = 0;
  21429. if (n >= base) {
  21430. xbits = extra[n-base];
  21431. }
  21432. f = tree[n * 2]/*.Freq*/;
  21433. s.opt_len += f * (bits + xbits);
  21434. if (has_stree) {
  21435. s.static_len += f * (stree[n*2 + 1]/*.Len*/ + xbits);
  21436. }
  21437. }
  21438. if (overflow === 0) { return; }
  21439. // Trace((stderr,"\nbit length overflow\n"));
  21440. /* This happens for example on obj2 and pic of the Calgary corpus */
  21441. /* Find the first bit length which could increase: */
  21442. do {
  21443. bits = max_length-1;
  21444. while (s.bl_count[bits] === 0) { bits--; }
  21445. s.bl_count[bits]--; /* move one leaf down the tree */
  21446. s.bl_count[bits+1] += 2; /* move one overflow item as its brother */
  21447. s.bl_count[max_length]--;
  21448. /* The brother of the overflow item also moves one step up,
  21449. * but this does not affect bl_count[max_length]
  21450. */
  21451. overflow -= 2;
  21452. } while (overflow > 0);
  21453. /* Now recompute all bit lengths, scanning in increasing frequency.
  21454. * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all
  21455. * lengths instead of fixing only the wrong ones. This idea is taken
  21456. * from 'ar' written by Haruhiko Okumura.)
  21457. */
  21458. for (bits = max_length; bits !== 0; bits--) {
  21459. n = s.bl_count[bits];
  21460. while (n !== 0) {
  21461. m = s.heap[--h];
  21462. if (m > max_code) { continue; }
  21463. if (tree[m*2 + 1]/*.Len*/ !== bits) {
  21464. // Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits));
  21465. s.opt_len += (bits - tree[m*2 + 1]/*.Len*/)*tree[m*2]/*.Freq*/;
  21466. tree[m*2 + 1]/*.Len*/ = bits;
  21467. }
  21468. n--;
  21469. }
  21470. }
  21471. }
  21472. /* ===========================================================================
  21473. * Generate the codes for a given tree and bit counts (which need not be
  21474. * optimal).
  21475. * IN assertion: the array bl_count contains the bit length statistics for
  21476. * the given tree and the field len is set for all tree elements.
  21477. * OUT assertion: the field code is set for all tree elements of non
  21478. * zero code length.
  21479. */
  21480. function gen_codes(tree, max_code, bl_count)
  21481. // ct_data *tree; /* the tree to decorate */
  21482. // int max_code; /* largest code with non zero frequency */
  21483. // ushf *bl_count; /* number of codes at each bit length */
  21484. {
  21485. var next_code = new Array(MAX_BITS+1); /* next code value for each bit length */
  21486. var code = 0; /* running code value */
  21487. var bits; /* bit index */
  21488. var n; /* code index */
  21489. /* The distribution counts are first used to generate the code values
  21490. * without bit reversal.
  21491. */
  21492. for (bits = 1; bits <= MAX_BITS; bits++) {
  21493. next_code[bits] = code = (code + bl_count[bits-1]) << 1;
  21494. }
  21495. /* Check that the bit counts in bl_count are consistent. The last code
  21496. * must be all ones.
  21497. */
  21498. //Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,
  21499. // "inconsistent bit counts");
  21500. //Tracev((stderr,"\ngen_codes: max_code %d ", max_code));
  21501. for (n = 0; n <= max_code; n++) {
  21502. var len = tree[n*2 + 1]/*.Len*/;
  21503. if (len === 0) { continue; }
  21504. /* Now reverse the bits */
  21505. tree[n*2]/*.Code*/ = bi_reverse(next_code[len]++, len);
  21506. //Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ",
  21507. // n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1));
  21508. }
  21509. }
  21510. /* ===========================================================================
  21511. * Initialize the various 'constant' tables.
  21512. */
  21513. function tr_static_init() {
  21514. var n; /* iterates over tree elements */
  21515. var bits; /* bit counter */
  21516. var length; /* length value */
  21517. var code; /* code value */
  21518. var dist; /* distance index */
  21519. var bl_count = new Array(MAX_BITS+1);
  21520. /* number of codes at each bit length for an optimal tree */
  21521. // do check in _tr_init()
  21522. //if (static_init_done) return;
  21523. /* For some embedded targets, global variables are not initialized: */
  21524. /*#ifdef NO_INIT_GLOBAL_POINTERS
  21525. static_l_desc.static_tree = static_ltree;
  21526. static_l_desc.extra_bits = extra_lbits;
  21527. static_d_desc.static_tree = static_dtree;
  21528. static_d_desc.extra_bits = extra_dbits;
  21529. static_bl_desc.extra_bits = extra_blbits;
  21530. #endif*/
  21531. /* Initialize the mapping length (0..255) -> length code (0..28) */
  21532. length = 0;
  21533. for (code = 0; code < LENGTH_CODES-1; code++) {
  21534. base_length[code] = length;
  21535. for (n = 0; n < (1<<extra_lbits[code]); n++) {
  21536. _length_code[length++] = code;
  21537. }
  21538. }
  21539. //Assert (length == 256, "tr_static_init: length != 256");
  21540. /* Note that the length 255 (match length 258) can be represented
  21541. * in two different ways: code 284 + 5 bits or code 285, so we
  21542. * overwrite length_code[255] to use the best encoding:
  21543. */
  21544. _length_code[length-1] = code;
  21545. /* Initialize the mapping dist (0..32K) -> dist code (0..29) */
  21546. dist = 0;
  21547. for (code = 0 ; code < 16; code++) {
  21548. base_dist[code] = dist;
  21549. for (n = 0; n < (1<<extra_dbits[code]); n++) {
  21550. _dist_code[dist++] = code;
  21551. }
  21552. }
  21553. //Assert (dist == 256, "tr_static_init: dist != 256");
  21554. dist >>= 7; /* from now on, all distances are divided by 128 */
  21555. for ( ; code < D_CODES; code++) {
  21556. base_dist[code] = dist << 7;
  21557. for (n = 0; n < (1<<(extra_dbits[code]-7)); n++) {
  21558. _dist_code[256 + dist++] = code;
  21559. }
  21560. }
  21561. //Assert (dist == 256, "tr_static_init: 256+dist != 512");
  21562. /* Construct the codes of the static literal tree */
  21563. for (bits = 0; bits <= MAX_BITS; bits++) {
  21564. bl_count[bits] = 0;
  21565. }
  21566. n = 0;
  21567. while (n <= 143) {
  21568. static_ltree[n*2 + 1]/*.Len*/ = 8;
  21569. n++;
  21570. bl_count[8]++;
  21571. }
  21572. while (n <= 255) {
  21573. static_ltree[n*2 + 1]/*.Len*/ = 9;
  21574. n++;
  21575. bl_count[9]++;
  21576. }
  21577. while (n <= 279) {
  21578. static_ltree[n*2 + 1]/*.Len*/ = 7;
  21579. n++;
  21580. bl_count[7]++;
  21581. }
  21582. while (n <= 287) {
  21583. static_ltree[n*2 + 1]/*.Len*/ = 8;
  21584. n++;
  21585. bl_count[8]++;
  21586. }
  21587. /* Codes 286 and 287 do not exist, but we must include them in the
  21588. * tree construction to get a canonical Huffman tree (longest code
  21589. * all ones)
  21590. */
  21591. gen_codes(static_ltree, L_CODES+1, bl_count);
  21592. /* The static distance tree is trivial: */
  21593. for (n = 0; n < D_CODES; n++) {
  21594. static_dtree[n*2 + 1]/*.Len*/ = 5;
  21595. static_dtree[n*2]/*.Code*/ = bi_reverse(n, 5);
  21596. }
  21597. // Now data ready and we can init static trees
  21598. static_l_desc = new StaticTreeDesc(static_ltree, extra_lbits, LITERALS+1, L_CODES, MAX_BITS);
  21599. static_d_desc = new StaticTreeDesc(static_dtree, extra_dbits, 0, D_CODES, MAX_BITS);
  21600. static_bl_desc =new StaticTreeDesc(new Array(0), extra_blbits, 0, BL_CODES, MAX_BL_BITS);
  21601. //static_init_done = true;
  21602. }
  21603. /* ===========================================================================
  21604. * Initialize a new block.
  21605. */
  21606. function init_block(s) {
  21607. var n; /* iterates over tree elements */
  21608. /* Initialize the trees. */
  21609. for (n = 0; n < L_CODES; n++) { s.dyn_ltree[n*2]/*.Freq*/ = 0; }
  21610. for (n = 0; n < D_CODES; n++) { s.dyn_dtree[n*2]/*.Freq*/ = 0; }
  21611. for (n = 0; n < BL_CODES; n++) { s.bl_tree[n*2]/*.Freq*/ = 0; }
  21612. s.dyn_ltree[END_BLOCK*2]/*.Freq*/ = 1;
  21613. s.opt_len = s.static_len = 0;
  21614. s.last_lit = s.matches = 0;
  21615. }
  21616. /* ===========================================================================
  21617. * Flush the bit buffer and align the output on a byte boundary
  21618. */
  21619. function bi_windup(s)
  21620. {
  21621. if (s.bi_valid > 8) {
  21622. put_short(s, s.bi_buf);
  21623. } else if (s.bi_valid > 0) {
  21624. //put_byte(s, (Byte)s->bi_buf);
  21625. s.pending_buf[s.pending++] = s.bi_buf;
  21626. }
  21627. s.bi_buf = 0;
  21628. s.bi_valid = 0;
  21629. }
  21630. /* ===========================================================================
  21631. * Copy a stored block, storing first the length and its
  21632. * one's complement if requested.
  21633. */
  21634. function copy_block(s, buf, len, header)
  21635. //DeflateState *s;
  21636. //charf *buf; /* the input data */
  21637. //unsigned len; /* its length */
  21638. //int header; /* true if block header must be written */
  21639. {
  21640. bi_windup(s); /* align on byte boundary */
  21641. if (header) {
  21642. put_short(s, len);
  21643. put_short(s, ~len);
  21644. }
  21645. // while (len--) {
  21646. // put_byte(s, *buf++);
  21647. // }
  21648. utils.arraySet(s.pending_buf, s.window, buf, len, s.pending);
  21649. s.pending += len;
  21650. }
  21651. /* ===========================================================================
  21652. * Compares to subtrees, using the tree depth as tie breaker when
  21653. * the subtrees have equal frequency. This minimizes the worst case length.
  21654. */
  21655. function smaller(tree, n, m, depth) {
  21656. var _n2 = n*2;
  21657. var _m2 = m*2;
  21658. return (tree[_n2]/*.Freq*/ < tree[_m2]/*.Freq*/ ||
  21659. (tree[_n2]/*.Freq*/ === tree[_m2]/*.Freq*/ && depth[n] <= depth[m]));
  21660. }
  21661. /* ===========================================================================
  21662. * Restore the heap property by moving down the tree starting at node k,
  21663. * exchanging a node with the smallest of its two sons if necessary, stopping
  21664. * when the heap property is re-established (each father smaller than its
  21665. * two sons).
  21666. */
  21667. function pqdownheap(s, tree, k)
  21668. // deflate_state *s;
  21669. // ct_data *tree; /* the tree to restore */
  21670. // int k; /* node to move down */
  21671. {
  21672. var v = s.heap[k];
  21673. var j = k << 1; /* left son of k */
  21674. while (j <= s.heap_len) {
  21675. /* Set j to the smallest of the two sons: */
  21676. if (j < s.heap_len &&
  21677. smaller(tree, s.heap[j+1], s.heap[j], s.depth)) {
  21678. j++;
  21679. }
  21680. /* Exit if v is smaller than both sons */
  21681. if (smaller(tree, v, s.heap[j], s.depth)) { break; }
  21682. /* Exchange v with the smallest son */
  21683. s.heap[k] = s.heap[j];
  21684. k = j;
  21685. /* And continue down the tree, setting j to the left son of k */
  21686. j <<= 1;
  21687. }
  21688. s.heap[k] = v;
  21689. }
  21690. // inlined manually
  21691. // var SMALLEST = 1;
  21692. /* ===========================================================================
  21693. * Send the block data compressed using the given Huffman trees
  21694. */
  21695. function compress_block(s, ltree, dtree)
  21696. // deflate_state *s;
  21697. // const ct_data *ltree; /* literal tree */
  21698. // const ct_data *dtree; /* distance tree */
  21699. {
  21700. var dist; /* distance of matched string */
  21701. var lc; /* match length or unmatched char (if dist == 0) */
  21702. var lx = 0; /* running index in l_buf */
  21703. var code; /* the code to send */
  21704. var extra; /* number of extra bits to send */
  21705. if (s.last_lit !== 0) {
  21706. do {
  21707. dist = (s.pending_buf[s.d_buf + lx*2] << 8) | (s.pending_buf[s.d_buf + lx*2 + 1]);
  21708. lc = s.pending_buf[s.l_buf + lx];
  21709. lx++;
  21710. if (dist === 0) {
  21711. send_code(s, lc, ltree); /* send a literal byte */
  21712. //Tracecv(isgraph(lc), (stderr," '%c' ", lc));
  21713. } else {
  21714. /* Here, lc is the match length - MIN_MATCH */
  21715. code = _length_code[lc];
  21716. send_code(s, code+LITERALS+1, ltree); /* send the length code */
  21717. extra = extra_lbits[code];
  21718. if (extra !== 0) {
  21719. lc -= base_length[code];
  21720. send_bits(s, lc, extra); /* send the extra length bits */
  21721. }
  21722. dist--; /* dist is now the match distance - 1 */
  21723. code = d_code(dist);
  21724. //Assert (code < D_CODES, "bad d_code");
  21725. send_code(s, code, dtree); /* send the distance code */
  21726. extra = extra_dbits[code];
  21727. if (extra !== 0) {
  21728. dist -= base_dist[code];
  21729. send_bits(s, dist, extra); /* send the extra distance bits */
  21730. }
  21731. } /* literal or match pair ? */
  21732. /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */
  21733. //Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx,
  21734. // "pendingBuf overflow");
  21735. } while (lx < s.last_lit);
  21736. }
  21737. send_code(s, END_BLOCK, ltree);
  21738. }
  21739. /* ===========================================================================
  21740. * Construct one Huffman tree and assigns the code bit strings and lengths.
  21741. * Update the total bit length for the current block.
  21742. * IN assertion: the field freq is set for all tree elements.
  21743. * OUT assertions: the fields len and code are set to the optimal bit length
  21744. * and corresponding code. The length opt_len is updated; static_len is
  21745. * also updated if stree is not null. The field max_code is set.
  21746. */
  21747. function build_tree(s, desc)
  21748. // deflate_state *s;
  21749. // tree_desc *desc; /* the tree descriptor */
  21750. {
  21751. var tree = desc.dyn_tree;
  21752. var stree = desc.stat_desc.static_tree;
  21753. var has_stree = desc.stat_desc.has_stree;
  21754. var elems = desc.stat_desc.elems;
  21755. var n, m; /* iterate over heap elements */
  21756. var max_code = -1; /* largest code with non zero frequency */
  21757. var node; /* new node being created */
  21758. /* Construct the initial heap, with least frequent element in
  21759. * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
  21760. * heap[0] is not used.
  21761. */
  21762. s.heap_len = 0;
  21763. s.heap_max = HEAP_SIZE;
  21764. for (n = 0; n < elems; n++) {
  21765. if (tree[n * 2]/*.Freq*/ !== 0) {
  21766. s.heap[++s.heap_len] = max_code = n;
  21767. s.depth[n] = 0;
  21768. } else {
  21769. tree[n*2 + 1]/*.Len*/ = 0;
  21770. }
  21771. }
  21772. /* The pkzip format requires that at least one distance code exists,
  21773. * and that at least one bit should be sent even if there is only one
  21774. * possible code. So to avoid special checks later on we force at least
  21775. * two codes of non zero frequency.
  21776. */
  21777. while (s.heap_len < 2) {
  21778. node = s.heap[++s.heap_len] = (max_code < 2 ? ++max_code : 0);
  21779. tree[node * 2]/*.Freq*/ = 1;
  21780. s.depth[node] = 0;
  21781. s.opt_len--;
  21782. if (has_stree) {
  21783. s.static_len -= stree[node*2 + 1]/*.Len*/;
  21784. }
  21785. /* node is 0 or 1 so it does not have extra bits */
  21786. }
  21787. desc.max_code = max_code;
  21788. /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
  21789. * establish sub-heaps of increasing lengths:
  21790. */
  21791. for (n = (s.heap_len >> 1/*int /2*/); n >= 1; n--) { pqdownheap(s, tree, n); }
  21792. /* Construct the Huffman tree by repeatedly combining the least two
  21793. * frequent nodes.
  21794. */
  21795. node = elems; /* next internal node of the tree */
  21796. do {
  21797. //pqremove(s, tree, n); /* n = node of least frequency */
  21798. /*** pqremove ***/
  21799. n = s.heap[1/*SMALLEST*/];
  21800. s.heap[1/*SMALLEST*/] = s.heap[s.heap_len--];
  21801. pqdownheap(s, tree, 1/*SMALLEST*/);
  21802. /***/
  21803. m = s.heap[1/*SMALLEST*/]; /* m = node of next least frequency */
  21804. s.heap[--s.heap_max] = n; /* keep the nodes sorted by frequency */
  21805. s.heap[--s.heap_max] = m;
  21806. /* Create a new node father of n and m */
  21807. tree[node * 2]/*.Freq*/ = tree[n * 2]/*.Freq*/ + tree[m * 2]/*.Freq*/;
  21808. s.depth[node] = (s.depth[n] >= s.depth[m] ? s.depth[n] : s.depth[m]) + 1;
  21809. tree[n*2 + 1]/*.Dad*/ = tree[m*2 + 1]/*.Dad*/ = node;
  21810. /* and insert the new node in the heap */
  21811. s.heap[1/*SMALLEST*/] = node++;
  21812. pqdownheap(s, tree, 1/*SMALLEST*/);
  21813. } while (s.heap_len >= 2);
  21814. s.heap[--s.heap_max] = s.heap[1/*SMALLEST*/];
  21815. /* At this point, the fields freq and dad are set. We can now
  21816. * generate the bit lengths.
  21817. */
  21818. gen_bitlen(s, desc);
  21819. /* The field len is now set, we can generate the bit codes */
  21820. gen_codes(tree, max_code, s.bl_count);
  21821. }
  21822. /* ===========================================================================
  21823. * Scan a literal or distance tree to determine the frequencies of the codes
  21824. * in the bit length tree.
  21825. */
  21826. function scan_tree(s, tree, max_code)
  21827. // deflate_state *s;
  21828. // ct_data *tree; /* the tree to be scanned */
  21829. // int max_code; /* and its largest code of non zero frequency */
  21830. {
  21831. var n; /* iterates over all tree elements */
  21832. var prevlen = -1; /* last emitted length */
  21833. var curlen; /* length of current code */
  21834. var nextlen = tree[0*2 + 1]/*.Len*/; /* length of next code */
  21835. var count = 0; /* repeat count of the current code */
  21836. var max_count = 7; /* max repeat count */
  21837. var min_count = 4; /* min repeat count */
  21838. if (nextlen === 0) {
  21839. max_count = 138;
  21840. min_count = 3;
  21841. }
  21842. tree[(max_code+1)*2 + 1]/*.Len*/ = 0xffff; /* guard */
  21843. for (n = 0; n <= max_code; n++) {
  21844. curlen = nextlen;
  21845. nextlen = tree[(n+1)*2 + 1]/*.Len*/;
  21846. if (++count < max_count && curlen === nextlen) {
  21847. continue;
  21848. } else if (count < min_count) {
  21849. s.bl_tree[curlen * 2]/*.Freq*/ += count;
  21850. } else if (curlen !== 0) {
  21851. if (curlen !== prevlen) { s.bl_tree[curlen * 2]/*.Freq*/++; }
  21852. s.bl_tree[REP_3_6*2]/*.Freq*/++;
  21853. } else if (count <= 10) {
  21854. s.bl_tree[REPZ_3_10*2]/*.Freq*/++;
  21855. } else {
  21856. s.bl_tree[REPZ_11_138*2]/*.Freq*/++;
  21857. }
  21858. count = 0;
  21859. prevlen = curlen;
  21860. if (nextlen === 0) {
  21861. max_count = 138;
  21862. min_count = 3;
  21863. } else if (curlen === nextlen) {
  21864. max_count = 6;
  21865. min_count = 3;
  21866. } else {
  21867. max_count = 7;
  21868. min_count = 4;
  21869. }
  21870. }
  21871. }
  21872. /* ===========================================================================
  21873. * Send a literal or distance tree in compressed form, using the codes in
  21874. * bl_tree.
  21875. */
  21876. function send_tree(s, tree, max_code)
  21877. // deflate_state *s;
  21878. // ct_data *tree; /* the tree to be scanned */
  21879. // int max_code; /* and its largest code of non zero frequency */
  21880. {
  21881. var n; /* iterates over all tree elements */
  21882. var prevlen = -1; /* last emitted length */
  21883. var curlen; /* length of current code */
  21884. var nextlen = tree[0*2 + 1]/*.Len*/; /* length of next code */
  21885. var count = 0; /* repeat count of the current code */
  21886. var max_count = 7; /* max repeat count */
  21887. var min_count = 4; /* min repeat count */
  21888. /* tree[max_code+1].Len = -1; */ /* guard already set */
  21889. if (nextlen === 0) {
  21890. max_count = 138;
  21891. min_count = 3;
  21892. }
  21893. for (n = 0; n <= max_code; n++) {
  21894. curlen = nextlen;
  21895. nextlen = tree[(n+1)*2 + 1]/*.Len*/;
  21896. if (++count < max_count && curlen === nextlen) {
  21897. continue;
  21898. } else if (count < min_count) {
  21899. do { send_code(s, curlen, s.bl_tree); } while (--count !== 0);
  21900. } else if (curlen !== 0) {
  21901. if (curlen !== prevlen) {
  21902. send_code(s, curlen, s.bl_tree);
  21903. count--;
  21904. }
  21905. //Assert(count >= 3 && count <= 6, " 3_6?");
  21906. send_code(s, REP_3_6, s.bl_tree);
  21907. send_bits(s, count-3, 2);
  21908. } else if (count <= 10) {
  21909. send_code(s, REPZ_3_10, s.bl_tree);
  21910. send_bits(s, count-3, 3);
  21911. } else {
  21912. send_code(s, REPZ_11_138, s.bl_tree);
  21913. send_bits(s, count-11, 7);
  21914. }
  21915. count = 0;
  21916. prevlen = curlen;
  21917. if (nextlen === 0) {
  21918. max_count = 138;
  21919. min_count = 3;
  21920. } else if (curlen === nextlen) {
  21921. max_count = 6;
  21922. min_count = 3;
  21923. } else {
  21924. max_count = 7;
  21925. min_count = 4;
  21926. }
  21927. }
  21928. }
  21929. /* ===========================================================================
  21930. * Construct the Huffman tree for the bit lengths and return the index in
  21931. * bl_order of the last bit length code to send.
  21932. */
  21933. function build_bl_tree(s) {
  21934. var max_blindex; /* index of last bit length code of non zero freq */
  21935. /* Determine the bit length frequencies for literal and distance trees */
  21936. scan_tree(s, s.dyn_ltree, s.l_desc.max_code);
  21937. scan_tree(s, s.dyn_dtree, s.d_desc.max_code);
  21938. /* Build the bit length tree: */
  21939. build_tree(s, s.bl_desc);
  21940. /* opt_len now includes the length of the tree representations, except
  21941. * the lengths of the bit lengths codes and the 5+5+4 bits for the counts.
  21942. */
  21943. /* Determine the number of bit length codes to send. The pkzip format
  21944. * requires that at least 4 bit length codes be sent. (appnote.txt says
  21945. * 3 but the actual value used is 4.)
  21946. */
  21947. for (max_blindex = BL_CODES-1; max_blindex >= 3; max_blindex--) {
  21948. if (s.bl_tree[bl_order[max_blindex]*2 + 1]/*.Len*/ !== 0) {
  21949. break;
  21950. }
  21951. }
  21952. /* Update opt_len to include the bit length tree and counts */
  21953. s.opt_len += 3*(max_blindex+1) + 5+5+4;
  21954. //Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld",
  21955. // s->opt_len, s->static_len));
  21956. return max_blindex;
  21957. }
  21958. /* ===========================================================================
  21959. * Send the header for a block using dynamic Huffman trees: the counts, the
  21960. * lengths of the bit length codes, the literal tree and the distance tree.
  21961. * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
  21962. */
  21963. function send_all_trees(s, lcodes, dcodes, blcodes)
  21964. // deflate_state *s;
  21965. // int lcodes, dcodes, blcodes; /* number of codes for each tree */
  21966. {
  21967. var rank; /* index in bl_order */
  21968. //Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes");
  21969. //Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,
  21970. // "too many codes");
  21971. //Tracev((stderr, "\nbl counts: "));
  21972. send_bits(s, lcodes-257, 5); /* not +255 as stated in appnote.txt */
  21973. send_bits(s, dcodes-1, 5);
  21974. send_bits(s, blcodes-4, 4); /* not -3 as stated in appnote.txt */
  21975. for (rank = 0; rank < blcodes; rank++) {
  21976. //Tracev((stderr, "\nbl code %2d ", bl_order[rank]));
  21977. send_bits(s, s.bl_tree[bl_order[rank]*2 + 1]/*.Len*/, 3);
  21978. }
  21979. //Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent));
  21980. send_tree(s, s.dyn_ltree, lcodes-1); /* literal tree */
  21981. //Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent));
  21982. send_tree(s, s.dyn_dtree, dcodes-1); /* distance tree */
  21983. //Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent));
  21984. }
  21985. /* ===========================================================================
  21986. * Check if the data type is TEXT or BINARY, using the following algorithm:
  21987. * - TEXT if the two conditions below are satisfied:
  21988. * a) There are no non-portable control characters belonging to the
  21989. * "black list" (0..6, 14..25, 28..31).
  21990. * b) There is at least one printable character belonging to the
  21991. * "white list" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255).
  21992. * - BINARY otherwise.
  21993. * - The following partially-portable control characters form a
  21994. * "gray list" that is ignored in this detection algorithm:
  21995. * (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}).
  21996. * IN assertion: the fields Freq of dyn_ltree are set.
  21997. */
  21998. function detect_data_type(s) {
  21999. /* black_mask is the bit mask of black-listed bytes
  22000. * set bits 0..6, 14..25, and 28..31
  22001. * 0xf3ffc07f = binary 11110011111111111100000001111111
  22002. */
  22003. var black_mask = 0xf3ffc07f;
  22004. var n;
  22005. /* Check for non-textual ("black-listed") bytes. */
  22006. for (n = 0; n <= 31; n++, black_mask >>>= 1) {
  22007. if ((black_mask & 1) && (s.dyn_ltree[n*2]/*.Freq*/ !== 0)) {
  22008. return Z_BINARY;
  22009. }
  22010. }
  22011. /* Check for textual ("white-listed") bytes. */
  22012. if (s.dyn_ltree[9 * 2]/*.Freq*/ !== 0 || s.dyn_ltree[10 * 2]/*.Freq*/ !== 0 ||
  22013. s.dyn_ltree[13 * 2]/*.Freq*/ !== 0) {
  22014. return Z_TEXT;
  22015. }
  22016. for (n = 32; n < LITERALS; n++) {
  22017. if (s.dyn_ltree[n * 2]/*.Freq*/ !== 0) {
  22018. return Z_TEXT;
  22019. }
  22020. }
  22021. /* There are no "black-listed" or "white-listed" bytes:
  22022. * this stream either is empty or has tolerated ("gray-listed") bytes only.
  22023. */
  22024. return Z_BINARY;
  22025. }
  22026. var static_init_done = false;
  22027. /* ===========================================================================
  22028. * Initialize the tree data structures for a new zlib stream.
  22029. */
  22030. function _tr_init(s)
  22031. {
  22032. if (!static_init_done) {
  22033. tr_static_init();
  22034. static_init_done = true;
  22035. }
  22036. s.l_desc = new TreeDesc(s.dyn_ltree, static_l_desc);
  22037. s.d_desc = new TreeDesc(s.dyn_dtree, static_d_desc);
  22038. s.bl_desc = new TreeDesc(s.bl_tree, static_bl_desc);
  22039. s.bi_buf = 0;
  22040. s.bi_valid = 0;
  22041. /* Initialize the first block of the first file: */
  22042. init_block(s);
  22043. }
  22044. /* ===========================================================================
  22045. * Send a stored block
  22046. */
  22047. function _tr_stored_block(s, buf, stored_len, last)
  22048. //DeflateState *s;
  22049. //charf *buf; /* input block */
  22050. //ulg stored_len; /* length of input block */
  22051. //int last; /* one if this is the last block for a file */
  22052. {
  22053. send_bits(s, (STORED_BLOCK<<1)+(last ? 1 : 0), 3); /* send block type */
  22054. copy_block(s, buf, stored_len, true); /* with header */
  22055. }
  22056. /* ===========================================================================
  22057. * Send one empty static block to give enough lookahead for inflate.
  22058. * This takes 10 bits, of which 7 may remain in the bit buffer.
  22059. */
  22060. function _tr_align(s) {
  22061. send_bits(s, STATIC_TREES<<1, 3);
  22062. send_code(s, END_BLOCK, static_ltree);
  22063. bi_flush(s);
  22064. }
  22065. /* ===========================================================================
  22066. * Determine the best encoding for the current block: dynamic trees, static
  22067. * trees or store, and output the encoded block to the zip file.
  22068. */
  22069. function _tr_flush_block(s, buf, stored_len, last)
  22070. //DeflateState *s;
  22071. //charf *buf; /* input block, or NULL if too old */
  22072. //ulg stored_len; /* length of input block */
  22073. //int last; /* one if this is the last block for a file */
  22074. {
  22075. var opt_lenb, static_lenb; /* opt_len and static_len in bytes */
  22076. var max_blindex = 0; /* index of last bit length code of non zero freq */
  22077. /* Build the Huffman trees unless a stored block is forced */
  22078. if (s.level > 0) {
  22079. /* Check if the file is binary or text */
  22080. if (s.strm.data_type === Z_UNKNOWN) {
  22081. s.strm.data_type = detect_data_type(s);
  22082. }
  22083. /* Construct the literal and distance trees */
  22084. build_tree(s, s.l_desc);
  22085. // Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len,
  22086. // s->static_len));
  22087. build_tree(s, s.d_desc);
  22088. // Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len,
  22089. // s->static_len));
  22090. /* At this point, opt_len and static_len are the total bit lengths of
  22091. * the compressed block data, excluding the tree representations.
  22092. */
  22093. /* Build the bit length tree for the above two trees, and get the index
  22094. * in bl_order of the last bit length code to send.
  22095. */
  22096. max_blindex = build_bl_tree(s);
  22097. /* Determine the best encoding. Compute the block lengths in bytes. */
  22098. opt_lenb = (s.opt_len+3+7) >>> 3;
  22099. static_lenb = (s.static_len+3+7) >>> 3;
  22100. // Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ",
  22101. // opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,
  22102. // s->last_lit));
  22103. if (static_lenb <= opt_lenb) { opt_lenb = static_lenb; }
  22104. } else {
  22105. // Assert(buf != (char*)0, "lost buf");
  22106. opt_lenb = static_lenb = stored_len + 5; /* force a stored block */
  22107. }
  22108. if ((stored_len+4 <= opt_lenb) && (buf !== -1)) {
  22109. /* 4: two words for the lengths */
  22110. /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
  22111. * Otherwise we can't have processed more than WSIZE input bytes since
  22112. * the last block flush, because compression would have been
  22113. * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
  22114. * transform a block into a stored block.
  22115. */
  22116. _tr_stored_block(s, buf, stored_len, last);
  22117. } else if (s.strategy === Z_FIXED || static_lenb === opt_lenb) {
  22118. send_bits(s, (STATIC_TREES<<1) + (last ? 1 : 0), 3);
  22119. compress_block(s, static_ltree, static_dtree);
  22120. } else {
  22121. send_bits(s, (DYN_TREES<<1) + (last ? 1 : 0), 3);
  22122. send_all_trees(s, s.l_desc.max_code+1, s.d_desc.max_code+1, max_blindex+1);
  22123. compress_block(s, s.dyn_ltree, s.dyn_dtree);
  22124. }
  22125. // Assert (s->compressed_len == s->bits_sent, "bad compressed size");
  22126. /* The above check is made mod 2^32, for files larger than 512 MB
  22127. * and uLong implemented on 32 bits.
  22128. */
  22129. init_block(s);
  22130. if (last) {
  22131. bi_windup(s);
  22132. }
  22133. // Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3,
  22134. // s->compressed_len-7*last));
  22135. }
  22136. /* ===========================================================================
  22137. * Save the match info and tally the frequency counts. Return true if
  22138. * the current block must be flushed.
  22139. */
  22140. function _tr_tally(s, dist, lc)
  22141. // deflate_state *s;
  22142. // unsigned dist; /* distance of matched string */
  22143. // unsigned lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */
  22144. {
  22145. //var out_length, in_length, dcode;
  22146. s.pending_buf[s.d_buf + s.last_lit * 2] = (dist >>> 8) & 0xff;
  22147. s.pending_buf[s.d_buf + s.last_lit * 2 + 1] = dist & 0xff;
  22148. s.pending_buf[s.l_buf + s.last_lit] = lc & 0xff;
  22149. s.last_lit++;
  22150. if (dist === 0) {
  22151. /* lc is the unmatched char */
  22152. s.dyn_ltree[lc*2]/*.Freq*/++;
  22153. } else {
  22154. s.matches++;
  22155. /* Here, lc is the match length - MIN_MATCH */
  22156. dist--; /* dist = match distance - 1 */
  22157. //Assert((ush)dist < (ush)MAX_DIST(s) &&
  22158. // (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&
  22159. // (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match");
  22160. s.dyn_ltree[(_length_code[lc]+LITERALS+1) * 2]/*.Freq*/++;
  22161. s.dyn_dtree[d_code(dist) * 2]/*.Freq*/++;
  22162. }
  22163. // (!) This block is disabled in zlib defailts,
  22164. // don't enable it for binary compatibility
  22165. //#ifdef TRUNCATE_BLOCK
  22166. // /* Try to guess if it is profitable to stop the current block here */
  22167. // if ((s.last_lit & 0x1fff) === 0 && s.level > 2) {
  22168. // /* Compute an upper bound for the compressed length */
  22169. // out_length = s.last_lit*8;
  22170. // in_length = s.strstart - s.block_start;
  22171. //
  22172. // for (dcode = 0; dcode < D_CODES; dcode++) {
  22173. // out_length += s.dyn_dtree[dcode*2]/*.Freq*/ * (5 + extra_dbits[dcode]);
  22174. // }
  22175. // out_length >>>= 3;
  22176. // //Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ",
  22177. // // s->last_lit, in_length, out_length,
  22178. // // 100L - out_length*100L/in_length));
  22179. // if (s.matches < (s.last_lit>>1)/*int /2*/ && out_length < (in_length>>1)/*int /2*/) {
  22180. // return true;
  22181. // }
  22182. // }
  22183. //#endif
  22184. return (s.last_lit === s.lit_bufsize-1);
  22185. /* We avoid equality with lit_bufsize because of wraparound at 64K
  22186. * on 16 bit machines and because stored blocks are restricted to
  22187. * 64K-1 bytes.
  22188. */
  22189. }
  22190. exports._tr_init = _tr_init;
  22191. exports._tr_stored_block = _tr_stored_block;
  22192. exports._tr_flush_block = _tr_flush_block;
  22193. exports._tr_tally = _tr_tally;
  22194. exports._tr_align = _tr_align;
  22195. },{"../utils/common":65}],77:[function(require,module,exports){
  22196. 'use strict';
  22197. function ZStream() {
  22198. /* next input byte */
  22199. this.input = null; // JS specific, because we have no pointers
  22200. this.next_in = 0;
  22201. /* number of bytes available at input */
  22202. this.avail_in = 0;
  22203. /* total number of input bytes read so far */
  22204. this.total_in = 0;
  22205. /* next output byte should be put there */
  22206. this.output = null; // JS specific, because we have no pointers
  22207. this.next_out = 0;
  22208. /* remaining free space at output */
  22209. this.avail_out = 0;
  22210. /* total number of bytes output so far */
  22211. this.total_out = 0;
  22212. /* last error message, NULL if no error */
  22213. this.msg = ''/*Z_NULL*/;
  22214. /* not visible by applications */
  22215. this.state = null;
  22216. /* best guess about the data type: binary or text */
  22217. this.data_type = 2/*Z_UNKNOWN*/;
  22218. /* adler32 value of the uncompressed data */
  22219. this.adler = 0;
  22220. }
  22221. module.exports = ZStream;
  22222. },{}],78:[function(require,module,exports){
  22223. module.exports = function arrayEquals(array) {
  22224. // if the other array is a falsy value, return
  22225. if (!array)
  22226. return false;
  22227. // compare lengths - can save a lot of time
  22228. if (this.length != array.length)
  22229. return false;
  22230. for (var i = 0, l = this.length; i < l; i++) {
  22231. // Check if we have nested arrays
  22232. if (this[i] instanceof Array && array[i] instanceof Array) {
  22233. // recurse into the nested arrays
  22234. if (!arrayEquals.apply(this[i], [array[i]]))
  22235. return false;
  22236. } else if (this[i] != array[i]) {
  22237. // Warning - two different object instances will never be equal:
  22238. // {x:20} != {x:20}
  22239. return false;
  22240. }
  22241. }
  22242. return true;
  22243. }
  22244. },{}],79:[function(require,module,exports){
  22245. exports.Interop = require('./interop');
  22246. },{"./interop":80}],80:[function(require,module,exports){
  22247. var transform = require('./transform');
  22248. var arrayEquals = require('./array-equals');
  22249. function Interop() { }
  22250. module.exports = Interop;
  22251. /**
  22252. * This map holds the most recent Plan A offer/answer SDP that was converted
  22253. * to Plan B, with the SDP type ('offer' or 'answer') as keys and the SDP
  22254. * string as values.
  22255. *
  22256. * @type {{}}
  22257. */
  22258. var cache = {};
  22259. /**
  22260. * This method transforms a Plan A SDP to an equivalent Plan B SDP. A
  22261. * PeerConnection wrapper transforms the SDP to Plan B before passing it to the
  22262. * application.
  22263. *
  22264. * @param desc
  22265. * @returns {*}
  22266. */
  22267. Interop.prototype.toPlanB = function(desc) {
  22268. //#region Preliminary input validation.
  22269. if (typeof desc !== 'object' || desc === null ||
  22270. typeof desc.sdp !== 'string') {
  22271. console.warn('An empty description was passed as an argument.');
  22272. return desc;
  22273. }
  22274. // Objectify the SDP for easier manipulation.
  22275. var session = transform.parse(desc.sdp);
  22276. // If the SDP contains no media, there's nothing to transform.
  22277. if (typeof session.media === 'undefined' ||
  22278. !Array.isArray(session.media) || session.media.length === 0) {
  22279. console.warn('The description has no media.');
  22280. return desc;
  22281. }
  22282. // Try some heuristics to "make sure" this is a Plan A SDP. Plan B SDP has
  22283. // a video, an audio and a data "channel" at most.
  22284. if (session.media.length <= 3 && session.media.every(function(m) {
  22285. return ['video', 'audio', 'data'].indexOf(m.mid) !== -1;
  22286. })) {
  22287. console.warn('This description does not look like Plan A.');
  22288. return desc;
  22289. }
  22290. //#endregion
  22291. // Plan A SDP is our "precious". Cache it for later use in the Plan B ->
  22292. // Plan A transformation.
  22293. cache[desc.type] = desc.sdp;
  22294. //#region Convert from Plan A to Plan B.
  22295. // We rebuild the session.media array.
  22296. var media = session.media;
  22297. session.media = [];
  22298. // Associative array that maps channel types to channel objects for fast
  22299. // access to channel objects by their type, e.g. channels['audio']->channel
  22300. // obj.
  22301. var channels = {};
  22302. // Used to build the group:BUNDLE value after the channels construction
  22303. // loop.
  22304. var types = [];
  22305. // Implode the Plan A m-lines/tracks into Plan B "channels".
  22306. media.forEach(function(mLine) {
  22307. // rtcp-mux is required in the Plan B SDP.
  22308. if (typeof mLine.rtcpMux !== 'string' ||
  22309. mLine.rtcpMux !== 'rtcp-mux') {
  22310. throw new Error('Cannot convert to Plan B because m-lines ' +
  22311. 'without the rtcp-mux attribute were found.');
  22312. }
  22313. // If we don't have a channel for this mLine.type, then use this mLine
  22314. // as the channel basis.
  22315. if (typeof channels[mLine.type] === 'undefined') {
  22316. channels[mLine.type] = mLine;
  22317. }
  22318. // Add sources to the channel and handle a=msid.
  22319. if (typeof mLine.sources === 'object') {
  22320. Object.keys(mLine.sources).forEach(function(ssrc) {
  22321. // Assign the sources to the channel.
  22322. channels[mLine.type].sources[ssrc] = mLine.sources[ssrc];
  22323. // In Plan B the msid is an SSRC attribute.
  22324. channels[mLine.type].sources[ssrc].msid = mLine.msid;
  22325. });
  22326. }
  22327. if (channels[mLine.type] === mLine) {
  22328. // Copy ICE related stuff from the principal media line.
  22329. mLine.candidates = media[0].candidates;
  22330. mLine.iceUfrag = media[0].iceUfrag;
  22331. mLine.icePwd = media[0].icePwd;
  22332. mLine.fingerprint = media[0].fingerprint;
  22333. // Plan B mids are in ['audio', 'video', 'data']
  22334. mLine.mid = mLine.type;
  22335. // Plan B doesn't support/need the bundle-only attribute.
  22336. delete mLine.bundleOnly;
  22337. // In Plan B the msid is an SSRC attribute.
  22338. delete mLine.msid;
  22339. // Used to build the group:BUNDLE value after this loop.
  22340. types.push(mLine.type);
  22341. // Add the channel to the new media array.
  22342. session.media.push(mLine);
  22343. }
  22344. // TODO(gp) add support for ssrc-group.
  22345. });
  22346. // We regenerate the BUNDLE group with the new mids.
  22347. session.groups.every(function(group) {
  22348. if (group.type === 'BUNDLE') {
  22349. group.mids = types.join(' ');
  22350. return false;
  22351. } else {
  22352. return true;
  22353. }
  22354. });
  22355. // msid semantic
  22356. session.msidSemantic = {
  22357. semantic: 'WMS',
  22358. token: '*'
  22359. };
  22360. var resStr = transform.write(session);
  22361. return new RTCSessionDescription({
  22362. type: desc.type,
  22363. sdp: resStr
  22364. });
  22365. //#endregion
  22366. };
  22367. /**
  22368. * This method transforms a Plan B SDP to an equivalent Plan A SDP. A
  22369. * PeerConnection wrapper transforms the SDP to Plan A before passing it to FF.
  22370. *
  22371. * @param desc
  22372. * @returns {*}
  22373. */
  22374. Interop.prototype.toPlanA = function(desc) {
  22375. //#region Preliminary input validation.
  22376. if (typeof desc !== 'object' || desc === null ||
  22377. typeof desc.sdp !== 'string') {
  22378. console.warn('An empty description was passed as an argument.');
  22379. return desc;
  22380. }
  22381. var session = transform.parse(desc.sdp);
  22382. // If the SDP contains no media, there's nothing to transform.
  22383. if (typeof session.media === 'undefined' ||
  22384. !Array.isArray(session.media) || session.media.length === 0) {
  22385. console.warn('The description has no media.');
  22386. return desc;
  22387. }
  22388. // Try some heuristics to "make sure" this is a Plan B SDP. Plan B SDP has
  22389. // a video, an audio and a data "channel" at most.
  22390. if (session.media.length > 3 || !session.media.every(function(m) {
  22391. return ['video', 'audio', 'data'].indexOf(m.mid) !== -1;
  22392. })) {
  22393. console.warn('This description does not look like Plan B.');
  22394. return desc;
  22395. }
  22396. // Make sure this Plan B SDP can be converted to a Plan A SDP.
  22397. var mids = [];
  22398. session.media.forEach(function(m) {
  22399. mids.push(m.mid);
  22400. });
  22401. var hasBundle = false;
  22402. if (typeof session.groups !== 'undefined' &&
  22403. Array.isArray(session.groups)) {
  22404. hasBundle = session.groups.every(function(g) {
  22405. return g.type !== 'BUNDLE' ||
  22406. arrayEquals.apply(g.mids.sort(), [mids.sort()]);
  22407. });
  22408. }
  22409. if (!hasBundle) {
  22410. throw new Error("Cannot convert to Plan A because m-lines that are " +
  22411. "not bundled were found.");
  22412. }
  22413. //#endregion
  22414. //#region Convert from Plan B to Plan A.
  22415. // Unfortunately, a Plan B offer/answer doesn't have enough information to
  22416. // rebuild an equivalent Plan A offer/answer.
  22417. //
  22418. // For example, if this is a local answer (in Plan A style) that we convert
  22419. // to Plan B prior to handing it over to the application (the
  22420. // PeerConnection wrapper called us, for instance, after a successful
  22421. // createAnswer), we want to remember the m-line at which we've seen the
  22422. // (local) SSRC. That's because when the application wants to do call the
  22423. // SLD method, forcing us to do the inverse transformation (from Plan B to
  22424. // Plan A), we need to know to which m-line to assign the (local) SSRC. We
  22425. // also need to know all the other m-lines that the original answer had and
  22426. // include them in the transformed answer as well.
  22427. //
  22428. // Another example is if this is a remote offer that we convert to Plan B
  22429. // prior to giving it to the application, we want to remember the mid at
  22430. // which we've seen the (remote) SSRC.
  22431. //
  22432. // In the iteration that follows, we use the cached Plan A (if it exists)
  22433. // to assign mids to ssrcs.
  22434. var cached;
  22435. if (typeof cache[desc.type] !== 'undefined') {
  22436. cached = transform.parse(cache[desc.type]);
  22437. }
  22438. // A helper map that sends mids to m-line objects. We use it later to
  22439. // rebuild the Plan A style session.media array.
  22440. var media = {};
  22441. session.media.forEach(function(channel) {
  22442. if (typeof channel.rtcpMux !== 'string' ||
  22443. channel.rtcpMux !== 'rtcp-mux') {
  22444. throw new Error("Cannot convert to Plan A because m-lines " +
  22445. "without the rtcp-mux attribute were found.");
  22446. }
  22447. // With rtcp-mux and bundle all the channels should have the same ICE
  22448. // stuff.
  22449. var sources = channel.sources;
  22450. var candidates = channel.candidates;
  22451. var iceUfrag = channel.iceUfrag;
  22452. var icePwd = channel.icePwd;
  22453. var fingerprint = channel.fingerprint;
  22454. var port = channel.port;
  22455. // We'll use the "channel" object as a prototype for each new "mLine"
  22456. // that we create, but first we need to clean it up a bit.
  22457. delete channel.sources;
  22458. delete channel.candidates;
  22459. delete channel.iceUfrag;
  22460. delete channel.icePwd;
  22461. delete channel.fingerprint;
  22462. delete channel.port;
  22463. delete channel.mid;
  22464. if (typeof sources === 'object') {
  22465. // Explode the Plan B channel sources with one m-line per source.
  22466. Object.keys(sources).forEach(function(ssrc) {
  22467. // Use the "channel" as a prototype for the "mLine".
  22468. var mLine = Object.create(channel);
  22469. // Assign the msid of the source to the m-line.
  22470. mLine.msid = sources[ssrc].msid;
  22471. delete sources[ssrc].msid;
  22472. // We assign one SSRC per media line.
  22473. mLine.sources = {};
  22474. mLine.sources[ssrc] = sources[ssrc];
  22475. // Use the cached Plan A SDP (if it exists) to assign SSRCs to
  22476. // mids.
  22477. if (typeof cached !== 'undefined' &&
  22478. typeof cached.media !== 'undefined' &&
  22479. Array.isArray(cached.media)) {
  22480. cached.media.forEach(function(m) {
  22481. if (typeof m.sources === 'object') {
  22482. Object.keys(m.sources).forEach(function(s) {
  22483. if (s === ssrc) {
  22484. mLine.mid = m.mid;
  22485. }
  22486. });
  22487. }
  22488. });
  22489. }
  22490. if (typeof mLine.mid === 'undefined') {
  22491. // If this is an SSRC that we see for the first time assign
  22492. // it a new mid. This is typically the case when this
  22493. // method is called to transform a remote description for
  22494. // the first time or when there is a new SSRC in the remote
  22495. // description because a new peer has joined the
  22496. // conference. Local SSRCs should have already been added
  22497. // to the map in the toPlanB method.
  22498. //
  22499. // Because FF generates answers in Plan A style, we MUST
  22500. // already have a cached answer with all the local SSRCs
  22501. // mapped to some mLine/mid.
  22502. if (desc.type === 'answer') {
  22503. throw new Error("An unmapped SSRC was found.");
  22504. }
  22505. mLine.mid = [channel.type, '-', ssrc].join('');
  22506. }
  22507. // Include the candidates in the 1st media line.
  22508. mLine.candidates = candidates;
  22509. mLine.iceUfrag = iceUfrag;
  22510. mLine.icePwd = icePwd;
  22511. mLine.fingerprint = fingerprint;
  22512. mLine.port = port;
  22513. media[mLine.mid] = mLine;
  22514. });
  22515. }
  22516. // TODO(gp) add support for ssrc-groups
  22517. });
  22518. // Rebuild the media array in the right order and add the missing mLines
  22519. // (missing from the Plan B SDP).
  22520. session.media = [];
  22521. mids = []; // reuse
  22522. if (desc.type === 'answer') {
  22523. // The media lines in the answer must match the media lines in the
  22524. // offer. The order is important too. Here we use the cached offer to
  22525. // find the m-lines that are missing (from the converted answer), and
  22526. // use the cached answer to complete the converted answer.
  22527. if (typeof cache['offer'] === 'undefined') {
  22528. throw new Error("An answer is being processed but we couldn't " +
  22529. "find a cached offer.");
  22530. }
  22531. var cachedOffer = transform.parse(cache['offer']);
  22532. if (typeof cachedOffer === 'undefined' ||
  22533. typeof cachedOffer.media === 'undefined' ||
  22534. !Array.isArray(cachedOffer.media)) {
  22535. // FIXME(gp) is this really a problem in the general case?
  22536. throw new Error("The cached offer has no media.");
  22537. }
  22538. cachedOffer.media.forEach(function(mo) {
  22539. var mLine;
  22540. if (typeof media[mo.mid] === 'undefined') {
  22541. // This is probably an m-line containing a remote track only.
  22542. // It MUST exist in the cached answer as a remote track only
  22543. // mLine.
  22544. cached.media.every(function(ma) {
  22545. if (mo.mid == ma.mid) {
  22546. mLine = ma;
  22547. return false;
  22548. } else {
  22549. return true;
  22550. }
  22551. });
  22552. } else {
  22553. mLine = media[mo.mid];
  22554. }
  22555. if (typeof mLine === 'undefined') {
  22556. throw new Error("The cached offer contains an m-line that " +
  22557. "doesn't exist neither in the cached answer nor in " +
  22558. "the converted answer.");
  22559. }
  22560. session.media.push(mLine);
  22561. mids.push(mLine.mid);
  22562. });
  22563. } else {
  22564. // Add all the m-lines that are in both the cached and the transformed
  22565. // SDP in the order of the cached SDP. We take the intersection because
  22566. // don't want to add m-lines from the cached SDP that have been removed
  22567. // from the transformed SDP.
  22568. if (typeof cached !== 'undefined' &&
  22569. typeof cached.media !== 'undefined' &&
  22570. Array.isArray(cached.media)) {
  22571. cached.media.forEach(function(pm) {
  22572. if (typeof media[pm.mid] !== 'undefined') {
  22573. mids.push(pm.mid);
  22574. session.media.push(media[pm.mid]);
  22575. }
  22576. });
  22577. }
  22578. // Add all the remaining (new) m-lines of the transformed SDP.
  22579. Object.keys(media).forEach(function(mid) {
  22580. if (mids.indexOf(mid) === -1) {
  22581. mids.push(mid);
  22582. session.media.push(media[mid]);
  22583. }
  22584. });
  22585. }
  22586. // We regenerate the BUNDLE group (since we regenerated the mids)
  22587. session.groups.every(function(group) {
  22588. if (group.type === 'BUNDLE') {
  22589. group.mids = mids.join(' ');
  22590. return false;
  22591. } else {
  22592. return true;
  22593. }
  22594. });
  22595. // msid semantic
  22596. session.msidSemantic = {
  22597. semantic: 'WMS',
  22598. token: '*'
  22599. };
  22600. var resStr = transform.write(session);
  22601. // Cache the transformed SDP (Plan A) for later re-use in this function.
  22602. cache[desc.type] = resStr;
  22603. return new RTCSessionDescription({
  22604. type: desc.type,
  22605. sdp: resStr
  22606. });
  22607. //#endregion
  22608. };
  22609. },{"./array-equals":78,"./transform":81}],81:[function(require,module,exports){
  22610. var transform = require('sdp-transform');
  22611. exports.write = function(session, opts) {
  22612. // expand sources to ssrcs
  22613. if (typeof session !== 'undefined' &&
  22614. typeof session.media !== 'undefined' &&
  22615. Array.isArray(session.media)) {
  22616. session.media.forEach(function (mLine) {
  22617. if (typeof mLine.sources !== 'undefined' &&
  22618. Object.keys(mLine.sources).length !== 0) {
  22619. mLine.ssrcs = [];
  22620. Object.keys(mLine.sources).forEach(function (ssrc) {
  22621. var source = mLine.sources[ssrc];
  22622. Object.keys(source).forEach(function (attribute) {
  22623. mLine.ssrcs.push({
  22624. id: ssrc,
  22625. attribute: attribute,
  22626. value: source[attribute]
  22627. });
  22628. });
  22629. });
  22630. delete mLine.sources;
  22631. }
  22632. });
  22633. }
  22634. // join group mids
  22635. if (typeof session !== 'undefined' &&
  22636. typeof session.groups !== 'undefined' && Array.isArray(session.groups)) {
  22637. session.groups.forEach(function (g) {
  22638. if (typeof g.mids !== 'undefined' && Array.isArray(g.mids)) {
  22639. g.mids = g.mids.join(' ');
  22640. }
  22641. });
  22642. }
  22643. return transform.write(session, opts);
  22644. };
  22645. exports.parse = function(sdp) {
  22646. var session = transform.parse(sdp);
  22647. if (typeof session !== 'undefined' && typeof session.media !== 'undefined' &&
  22648. Array.isArray(session.media)) {
  22649. // group sources attributes by ssrc
  22650. session.media.forEach(function (mLine) {
  22651. if (typeof mLine.ssrcs !== 'undefined' && Array.isArray(mLine.ssrcs)) {
  22652. mLine.sources = {};
  22653. mLine.ssrcs.forEach(function (ssrc) {
  22654. if (!mLine.sources[ssrc.id])
  22655. mLine.sources[ssrc.id] = {};
  22656. mLine.sources[ssrc.id][ssrc.attribute] = ssrc.value;
  22657. });
  22658. delete mLine.ssrcs;
  22659. }
  22660. });
  22661. }
  22662. // split group mids
  22663. if (typeof session !== 'undefined' &&
  22664. typeof session.groups !== 'undefined' && Array.isArray(session.groups)) {
  22665. session.groups.forEach(function (g) {
  22666. if (typeof g.mids === 'string') {
  22667. g.mids = g.mids.split(' ');
  22668. }
  22669. });
  22670. }
  22671. return session;
  22672. };
  22673. },{"sdp-transform":83}],82:[function(require,module,exports){
  22674. var grammar = module.exports = {
  22675. v: [{
  22676. name: 'version',
  22677. reg: /^(\d*)$/
  22678. }],
  22679. o: [{ //o=- 20518 0 IN IP4 203.0.113.1
  22680. // NB: sessionId will be a String in most cases because it is huge
  22681. name: 'origin',
  22682. reg: /^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/,
  22683. names: ['username', 'sessionId', 'sessionVersion', 'netType', 'ipVer', 'address'],
  22684. format: "%s %s %d %s IP%d %s"
  22685. }],
  22686. // default parsing of these only (though some of these feel outdated)
  22687. s: [{ name: 'name' }],
  22688. i: [{ name: 'description' }],
  22689. u: [{ name: 'uri' }],
  22690. e: [{ name: 'email' }],
  22691. p: [{ name: 'phone' }],
  22692. z: [{ name: 'timezones' }], // TODO: this one can actually be parsed properly..
  22693. r: [{ name: 'repeats' }], // TODO: this one can also be parsed properly
  22694. //k: [{}], // outdated thing ignored
  22695. t: [{ //t=0 0
  22696. name: 'timing',
  22697. reg: /^(\d*) (\d*)/,
  22698. names: ['start', 'stop'],
  22699. format: "%d %d"
  22700. }],
  22701. c: [{ //c=IN IP4 10.47.197.26
  22702. name: 'connection',
  22703. reg: /^IN IP(\d) (\S*)/,
  22704. names: ['version', 'ip'],
  22705. format: "IN IP%d %s"
  22706. }],
  22707. b: [{ //b=AS:4000
  22708. push: 'bandwidth',
  22709. reg: /^(TIAS|AS|CT|RR|RS):(\d*)/,
  22710. names: ['type', 'limit'],
  22711. format: "%s:%s"
  22712. }],
  22713. m: [{ //m=video 51744 RTP/AVP 126 97 98 34 31
  22714. // NB: special - pushes to session
  22715. // TODO: rtp/fmtp should be filtered by the payloads found here?
  22716. reg: /^(\w*) (\d*) ([\w\/]*)(?: (.*))?/,
  22717. names: ['type', 'port', 'protocol', 'payloads'],
  22718. format: "%s %d %s %s"
  22719. }],
  22720. a: [
  22721. { //a=rtpmap:110 opus/48000/2
  22722. push: 'rtp',
  22723. reg: /^rtpmap:(\d*) ([\w\-]*)\/(\d*)(?:\s*\/(\S*))?/,
  22724. names: ['payload', 'codec', 'rate', 'encoding'],
  22725. format: function (o) {
  22726. return (o.encoding) ?
  22727. "rtpmap:%d %s/%s/%s":
  22728. "rtpmap:%d %s/%s";
  22729. }
  22730. },
  22731. { //a=fmtp:108 profile-level-id=24;object=23;bitrate=64000
  22732. push: 'fmtp',
  22733. reg: /^fmtp:(\d*) (\S*)/,
  22734. names: ['payload', 'config'],
  22735. format: "fmtp:%d %s"
  22736. },
  22737. { //a=control:streamid=0
  22738. name: 'control',
  22739. reg: /^control:(.*)/,
  22740. format: "control:%s"
  22741. },
  22742. { //a=rtcp:65179 IN IP4 193.84.77.194
  22743. name: 'rtcp',
  22744. reg: /^rtcp:(\d*)(?: (\S*) IP(\d) (\S*))?/,
  22745. names: ['port', 'netType', 'ipVer', 'address'],
  22746. format: function (o) {
  22747. return (o.address != null) ?
  22748. "rtcp:%d %s IP%d %s":
  22749. "rtcp:%d";
  22750. }
  22751. },
  22752. { //a=rtcp-fb:98 trr-int 100
  22753. push: 'rtcpFbTrrInt',
  22754. reg: /^rtcp-fb:(\*|\d*) trr-int (\d*)/,
  22755. names: ['payload', 'value'],
  22756. format: "rtcp-fb:%d trr-int %d"
  22757. },
  22758. { //a=rtcp-fb:98 nack rpsi
  22759. push: 'rtcpFb',
  22760. reg: /^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,
  22761. names: ['payload', 'type', 'subtype'],
  22762. format: function (o) {
  22763. return (o.subtype != null) ?
  22764. "rtcp-fb:%s %s %s":
  22765. "rtcp-fb:%s %s";
  22766. }
  22767. },
  22768. { //a=extmap:2 urn:ietf:params:rtp-hdrext:toffset
  22769. //a=extmap:1/recvonly URI-gps-string
  22770. push: 'ext',
  22771. reg: /^extmap:([\w_\/]*) (\S*)(?: (\S*))?/,
  22772. names: ['value', 'uri', 'config'], // value may include "/direction" suffix
  22773. format: function (o) {
  22774. return (o.config != null) ?
  22775. "extmap:%s %s %s":
  22776. "extmap:%s %s";
  22777. }
  22778. },
  22779. {
  22780. //a=crypto:1 AES_CM_128_HMAC_SHA1_80 inline:PS1uQCVeeCFCanVmcjkpPywjNWhcYD0mXXtxaVBR|2^20|1:32
  22781. push: 'crypto',
  22782. reg: /^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,
  22783. names: ['id', 'suite', 'config', 'sessionConfig'],
  22784. format: function (o) {
  22785. return (o.sessionConfig != null) ?
  22786. "crypto:%d %s %s %s":
  22787. "crypto:%d %s %s";
  22788. }
  22789. },
  22790. { //a=setup:actpass
  22791. name: 'setup',
  22792. reg: /^setup:(\w*)/,
  22793. format: "setup:%s"
  22794. },
  22795. { //a=mid:1
  22796. name: 'mid',
  22797. reg: /^mid:([^\s]*)/,
  22798. format: "mid:%s"
  22799. },
  22800. { //a=msid:0c8b064d-d807-43b4-b434-f92a889d8587 98178685-d409-46e0-8e16-7ef0db0db64a
  22801. name: 'msid',
  22802. reg: /^msid:(.*)/,
  22803. format: "msid:%s"
  22804. },
  22805. { //a=ptime:20
  22806. name: 'ptime',
  22807. reg: /^ptime:(\d*)/,
  22808. format: "ptime:%d"
  22809. },
  22810. { //a=maxptime:60
  22811. name: 'maxptime',
  22812. reg: /^maxptime:(\d*)/,
  22813. format: "maxptime:%d"
  22814. },
  22815. { //a=sendrecv
  22816. name: 'direction',
  22817. reg: /^(sendrecv|recvonly|sendonly|inactive)/
  22818. },
  22819. { //a=ice-lite
  22820. name: 'icelite',
  22821. reg: /^(ice-lite)/
  22822. },
  22823. { //a=ice-ufrag:F7gI
  22824. name: 'iceUfrag',
  22825. reg: /^ice-ufrag:(\S*)/,
  22826. format: "ice-ufrag:%s"
  22827. },
  22828. { //a=ice-pwd:x9cml/YzichV2+XlhiMu8g
  22829. name: 'icePwd',
  22830. reg: /^ice-pwd:(\S*)/,
  22831. format: "ice-pwd:%s"
  22832. },
  22833. { //a=fingerprint:SHA-1 00:11:22:33:44:55:66:77:88:99:AA:BB:CC:DD:EE:FF:00:11:22:33
  22834. name: 'fingerprint',
  22835. reg: /^fingerprint:(\S*) (\S*)/,
  22836. names: ['type', 'hash'],
  22837. format: "fingerprint:%s %s"
  22838. },
  22839. {
  22840. //a=candidate:0 1 UDP 2113667327 203.0.113.1 54400 typ host
  22841. //a=candidate:1162875081 1 udp 2113937151 192.168.34.75 60017 typ host generation 0
  22842. //a=candidate:3289912957 2 udp 1845501695 193.84.77.194 60017 typ srflx raddr 192.168.34.75 rport 60017 generation 0
  22843. push:'candidates',
  22844. reg: /^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: generation (\d*))?/,
  22845. names: ['foundation', 'component', 'transport', 'priority', 'ip', 'port', 'type', 'raddr', 'rport', 'generation'],
  22846. format: function (o) {
  22847. var str = "candidate:%s %d %s %d %s %d typ %s";
  22848. // NB: candidate has two optional chunks, so %void middle one if it's missing
  22849. str += (o.raddr != null) ? " raddr %s rport %d" : "%v%v";
  22850. if (o.generation != null) {
  22851. str += " generation %d";
  22852. }
  22853. return str;
  22854. }
  22855. },
  22856. { //a=remote-candidates:1 203.0.113.1 54400 2 203.0.113.1 54401 ...
  22857. name: 'remoteCandidates',
  22858. reg: /^remote-candidates:(.*)/,
  22859. format: "remote-candidates:%s"
  22860. },
  22861. { //a=ice-options:google-ice
  22862. name: 'iceOptions',
  22863. reg: /^ice-options:(\S*)/,
  22864. format: "ice-options:%s"
  22865. },
  22866. { //a=ssrc:2566107569 cname:t9YU8M1UxTF8Y1A1
  22867. push: "ssrcs",
  22868. reg: /^ssrc:(\d*) ([\w_]*):(.*)/,
  22869. names: ['id', 'attribute', 'value'],
  22870. format: "ssrc:%d %s:%s"
  22871. },
  22872. { //a=msid-semantic: WMS Jvlam5X3SX1OP6pn20zWogvaKJz5Hjf9OnlV
  22873. name: "msidSemantic",
  22874. reg: /^msid-semantic:\s?(\w*) (\S*)/,
  22875. names: ['semantic', 'token'],
  22876. format: "msid-semantic: %s %s" // space after ":" is not accidental
  22877. },
  22878. { //a=group:BUNDLE audio video
  22879. push: 'groups',
  22880. reg: /^group:(\w*) (.*)/,
  22881. names: ['type', 'mids'],
  22882. format: "group:%s %s"
  22883. },
  22884. { //a=rtcp-mux
  22885. name: 'rtcpMux',
  22886. reg: /^(rtcp-mux)/
  22887. },
  22888. { // any a= that we don't understand is kepts verbatim on media.invalid
  22889. push: 'invalid',
  22890. names: ["value"]
  22891. }
  22892. ]
  22893. };
  22894. // set sensible defaults to avoid polluting the grammar with boring details
  22895. Object.keys(grammar).forEach(function (key) {
  22896. var objs = grammar[key];
  22897. objs.forEach(function (obj) {
  22898. if (!obj.reg) {
  22899. obj.reg = /(.*)/;
  22900. }
  22901. if (!obj.format) {
  22902. obj.format = "%s";
  22903. }
  22904. });
  22905. });
  22906. },{}],83:[function(require,module,exports){
  22907. var parser = require('./parser');
  22908. var writer = require('./writer');
  22909. exports.write = writer;
  22910. exports.parse = parser.parse;
  22911. exports.parseFmtpConfig = parser.parseFmtpConfig;
  22912. exports.parsePayloads = parser.parsePayloads;
  22913. exports.parseRemoteCandidates = parser.parseRemoteCandidates;
  22914. },{"./parser":84,"./writer":85}],84:[function(require,module,exports){
  22915. var toIntIfInt = function (v) {
  22916. return String(Number(v)) === v ? Number(v) : v;
  22917. };
  22918. var attachProperties = function (match, location, names, rawName) {
  22919. if (rawName && !names) {
  22920. location[rawName] = toIntIfInt(match[1]);
  22921. }
  22922. else {
  22923. for (var i = 0; i < names.length; i += 1) {
  22924. if (match[i+1] != null) {
  22925. location[names[i]] = toIntIfInt(match[i+1]);
  22926. }
  22927. }
  22928. }
  22929. };
  22930. var parseReg = function (obj, location, content) {
  22931. var needsBlank = obj.name && obj.names;
  22932. if (obj.push && !location[obj.push]) {
  22933. location[obj.push] = [];
  22934. }
  22935. else if (needsBlank && !location[obj.name]) {
  22936. location[obj.name] = {};
  22937. }
  22938. var keyLocation = obj.push ?
  22939. {} : // blank object that will be pushed
  22940. needsBlank ? location[obj.name] : location; // otherwise, named location or root
  22941. attachProperties(content.match(obj.reg), keyLocation, obj.names, obj.name);
  22942. if (obj.push) {
  22943. location[obj.push].push(keyLocation);
  22944. }
  22945. };
  22946. var grammar = require('./grammar');
  22947. var validLine = RegExp.prototype.test.bind(/^([a-z])=(.*)/);
  22948. exports.parse = function (sdp) {
  22949. var session = {}
  22950. , media = []
  22951. , location = session; // points at where properties go under (one of the above)
  22952. // parse lines we understand
  22953. sdp.split(/(\r\n|\r|\n)/).filter(validLine).forEach(function (l) {
  22954. var type = l[0];
  22955. var content = l.slice(2);
  22956. if (type === 'm') {
  22957. media.push({rtp: [], fmtp: []});
  22958. location = media[media.length-1]; // point at latest media line
  22959. }
  22960. for (var j = 0; j < (grammar[type] || []).length; j += 1) {
  22961. var obj = grammar[type][j];
  22962. if (obj.reg.test(content)) {
  22963. return parseReg(obj, location, content);
  22964. }
  22965. }
  22966. });
  22967. session.media = media; // link it up
  22968. return session;
  22969. };
  22970. var fmtpReducer = function (acc, expr) {
  22971. var s = expr.split('=');
  22972. if (s.length === 2) {
  22973. acc[s[0]] = toIntIfInt(s[1]);
  22974. }
  22975. return acc;
  22976. };
  22977. exports.parseFmtpConfig = function (str) {
  22978. return str.split(';').reduce(fmtpReducer, {});
  22979. };
  22980. exports.parsePayloads = function (str) {
  22981. return str.split(' ').map(Number);
  22982. };
  22983. exports.parseRemoteCandidates = function (str) {
  22984. var candidates = [];
  22985. var parts = str.split(' ').map(toIntIfInt);
  22986. for (var i = 0; i < parts.length; i += 3) {
  22987. candidates.push({
  22988. component: parts[i],
  22989. ip: parts[i + 1],
  22990. port: parts[i + 2]
  22991. });
  22992. }
  22993. return candidates;
  22994. };
  22995. },{"./grammar":82}],85:[function(require,module,exports){
  22996. var grammar = require('./grammar');
  22997. // customized util.format - discards excess arguments and can void middle ones
  22998. var formatRegExp = /%[sdv%]/g;
  22999. var format = function (formatStr) {
  23000. var i = 1;
  23001. var args = arguments;
  23002. var len = args.length;
  23003. return formatStr.replace(formatRegExp, function (x) {
  23004. if (i >= len) {
  23005. return x; // missing argument
  23006. }
  23007. var arg = args[i];
  23008. i += 1;
  23009. switch (x) {
  23010. case '%%':
  23011. return '%';
  23012. case '%s':
  23013. return String(arg);
  23014. case '%d':
  23015. return Number(arg);
  23016. case '%v':
  23017. return '';
  23018. }
  23019. });
  23020. // NB: we discard excess arguments - they are typically undefined from makeLine
  23021. };
  23022. var makeLine = function (type, obj, location) {
  23023. var str = obj.format instanceof Function ?
  23024. (obj.format(obj.push ? location : location[obj.name])) :
  23025. obj.format;
  23026. var args = [type + '=' + str];
  23027. if (obj.names) {
  23028. for (var i = 0; i < obj.names.length; i += 1) {
  23029. var n = obj.names[i];
  23030. if (obj.name) {
  23031. args.push(location[obj.name][n]);
  23032. }
  23033. else { // for mLine and push attributes
  23034. args.push(location[obj.names[i]]);
  23035. }
  23036. }
  23037. }
  23038. else {
  23039. args.push(location[obj.name]);
  23040. }
  23041. return format.apply(null, args);
  23042. };
  23043. // RFC specified order
  23044. // TODO: extend this with all the rest
  23045. var defaultOuterOrder = [
  23046. 'v', 'o', 's', 'i',
  23047. 'u', 'e', 'p', 'c',
  23048. 'b', 't', 'r', 'z', 'a'
  23049. ];
  23050. var defaultInnerOrder = ['i', 'c', 'b', 'a'];
  23051. module.exports = function (session, opts) {
  23052. opts = opts || {};
  23053. // ensure certain properties exist
  23054. if (session.version == null) {
  23055. session.version = 0; // "v=0" must be there (only defined version atm)
  23056. }
  23057. if (session.name == null) {
  23058. session.name = " "; // "s= " must be there if no meaningful name set
  23059. }
  23060. session.media.forEach(function (mLine) {
  23061. if (mLine.payloads == null) {
  23062. mLine.payloads = "";
  23063. }
  23064. });
  23065. var outerOrder = opts.outerOrder || defaultOuterOrder;
  23066. var innerOrder = opts.innerOrder || defaultInnerOrder;
  23067. var sdp = [];
  23068. // loop through outerOrder for matching properties on session
  23069. outerOrder.forEach(function (type) {
  23070. grammar[type].forEach(function (obj) {
  23071. if (obj.name in session && typeof session[obj.name] !== 'undefined') {
  23072. sdp.push(makeLine(type, obj, session));
  23073. }
  23074. else if (obj.push in session && typeof session[obj.push] !== 'undefined') {
  23075. session[obj.push].forEach(function (el) {
  23076. sdp.push(makeLine(type, obj, el));
  23077. });
  23078. }
  23079. });
  23080. });
  23081. // then for each media line, follow the innerOrder
  23082. session.media.forEach(function (mLine) {
  23083. sdp.push(makeLine('m', grammar.m[0], mLine));
  23084. innerOrder.forEach(function (type) {
  23085. grammar[type].forEach(function (obj) {
  23086. if (obj.name in mLine && typeof mLine[obj.name] !== 'undefined') {
  23087. sdp.push(makeLine(type, obj, mLine));
  23088. }
  23089. else if (obj.push in mLine && typeof mLine[obj.push] !== 'undefined') {
  23090. mLine[obj.push].forEach(function (el) {
  23091. sdp.push(makeLine(type, obj, el));
  23092. });
  23093. }
  23094. });
  23095. });
  23096. });
  23097. return sdp.join('\r\n') + '\r\n';
  23098. };
  23099. },{"./grammar":82}],86:[function(require,module,exports){
  23100. var MediaStreamType = {
  23101. VIDEO_TYPE: "Video",
  23102. AUDIO_TYPE: "Audio"
  23103. };
  23104. module.exports = MediaStreamType;
  23105. },{}],87:[function(require,module,exports){
  23106. var RTCBrowserType = {
  23107. RTC_BROWSER_CHROME: "rtc_browser.chrome",
  23108. RTC_BROWSER_FIREFOX: "rtc_browser.firefox"
  23109. };
  23110. module.exports = RTCBrowserType;
  23111. },{}],88:[function(require,module,exports){
  23112. var RTCEvents = {
  23113. LASTN_CHANGED: "rtc.lastn_changed",
  23114. DOMINANTSPEAKER_CHANGED: "rtc.dominantspeaker_changed",
  23115. LASTN_ENDPOINT_CHANGED: "rtc.lastn_endpoint_changed",
  23116. SIMULCAST_LAYER_CHANGED: "rtc.simulcast_layer_changed",
  23117. SIMULCAST_LAYER_CHANGING: "rtc.simulcast_layer_changing",
  23118. SIMULCAST_START: "rtc.simlcast_start",
  23119. SIMULCAST_STOP: "rtc.simlcast_stop"
  23120. };
  23121. module.exports = RTCEvents;
  23122. },{}],89:[function(require,module,exports){
  23123. var Resolutions = {
  23124. "1080": {
  23125. width: 1920,
  23126. height: 1080,
  23127. order: 7
  23128. },
  23129. "fullhd": {
  23130. width: 1920,
  23131. height: 1080,
  23132. order: 7
  23133. },
  23134. "720": {
  23135. width: 1280,
  23136. height: 720,
  23137. order: 6
  23138. },
  23139. "hd": {
  23140. width: 1280,
  23141. height: 720,
  23142. order: 6
  23143. },
  23144. "960": {
  23145. width: 960,
  23146. height: 720,
  23147. order: 5
  23148. },
  23149. "640": {
  23150. width: 640,
  23151. height: 480,
  23152. order: 4
  23153. },
  23154. "vga": {
  23155. width: 640,
  23156. height: 480,
  23157. order: 4
  23158. },
  23159. "360": {
  23160. width: 640,
  23161. height: 360,
  23162. order: 3
  23163. },
  23164. "320": {
  23165. width: 320,
  23166. height: 240,
  23167. order: 2
  23168. },
  23169. "180": {
  23170. width: 320,
  23171. height: 180,
  23172. order: 1
  23173. }
  23174. };
  23175. module.exports = Resolutions;
  23176. },{}],90:[function(require,module,exports){
  23177. var StreamEventTypes = {
  23178. EVENT_TYPE_LOCAL_CREATED: "stream.local_created",
  23179. EVENT_TYPE_LOCAL_CHANGED: "stream.local_changed",
  23180. EVENT_TYPE_LOCAL_ENDED: "stream.local_ended",
  23181. EVENT_TYPE_REMOTE_CREATED: "stream.remote_created",
  23182. EVENT_TYPE_REMOTE_ENDED: "stream.remote_ended"
  23183. };
  23184. module.exports = StreamEventTypes;
  23185. },{}],91:[function(require,module,exports){
  23186. var UIEvents = {
  23187. NICKNAME_CHANGED: "UI.nickname_changed",
  23188. SELECTED_ENDPOINT: "UI.selected_endpoint",
  23189. PINNED_ENDPOINT: "UI.pinned_endpoint"
  23190. };
  23191. module.exports = UIEvents;
  23192. },{}],92:[function(require,module,exports){
  23193. var AuthenticationEvents = {
  23194. /**
  23195. * Event callback arguments:
  23196. * function(authenticationEnabled, userIdentity)
  23197. * authenticationEnabled - indicates whether authentication has been enabled
  23198. * in this session
  23199. * userIdentity - if user has been logged in then it contains user name. If
  23200. * contains 'null' or 'undefined' then user is not logged in.
  23201. */
  23202. IDENTITY_UPDATED: "authentication.identity_updated"
  23203. };
  23204. module.exports = AuthenticationEvents;
  23205. },{}],93:[function(require,module,exports){
  23206. var CQEvents = {
  23207. LOCALSTATS_UPDATED: "cq.localstats_updated",
  23208. REMOTESTATS_UPDATED: "cq.remotestats_updated",
  23209. STOP: "cq.stop"
  23210. };
  23211. module.exports = CQEvents;
  23212. },{}],94:[function(require,module,exports){
  23213. var DesktopSharingEventTypes = {
  23214. INIT: "ds.init",
  23215. SWITCHING_DONE: "ds.switching_done",
  23216. NEW_STREAM_CREATED: "ds.new_stream_created"
  23217. };
  23218. module.exports = DesktopSharingEventTypes;
  23219. },{}],95:[function(require,module,exports){
  23220. module.exports = {
  23221. getLanguages : function () {
  23222. var languages = [];
  23223. for(var lang in this)
  23224. {
  23225. if(typeof this[lang] === "string")
  23226. languages.push(this[lang]);
  23227. }
  23228. return languages;
  23229. },
  23230. EN: "en",
  23231. BG: "bg",
  23232. DE: "de"
  23233. }
  23234. },{}],96:[function(require,module,exports){
  23235. var XMPPEvents = {
  23236. CONFERENCE_CERATED: "xmpp.conferenceCreated.jingle",
  23237. CALL_TERMINATED: "xmpp.callterminated.jingle",
  23238. CALL_INCOMING: "xmpp.callincoming.jingle",
  23239. DISPOSE_CONFERENCE: "xmpp.dispoce_confernce",
  23240. GRACEFUL_SHUTDOWN: "xmpp.graceful_shutdown",
  23241. KICKED: "xmpp.kicked",
  23242. BRIDGE_DOWN: "xmpp.bridge_down",
  23243. USER_ID_CHANGED: "xmpp.user_id_changed",
  23244. CHANGED_STREAMS: "xmpp.changed_streams",
  23245. MUC_JOINED: "xmpp.muc_joined",
  23246. MUC_ENTER: "xmpp.muc_enter",
  23247. MUC_ROLE_CHANGED: "xmpp.muc_role_changed",
  23248. MUC_LEFT: "xmpp.muc_left",
  23249. MUC_DESTROYED: "xmpp.muc_destroyed",
  23250. DISPLAY_NAME_CHANGED: "xmpp.display_name_changed",
  23251. REMOTE_STATS: "xmpp.remote_stats",
  23252. LOCALROLE_CHANGED: "xmpp.localrole_changed",
  23253. PRESENCE_STATUS: "xmpp.presence_status",
  23254. RESERVATION_ERROR: "xmpp.room_reservation_error",
  23255. SUBJECT_CHANGED: "xmpp.subject_changed",
  23256. MESSAGE_RECEIVED: "xmpp.message_received",
  23257. SENDING_CHAT_MESSAGE: "xmpp.sending_chat_message",
  23258. PASSWORD_REQUIRED: "xmpp.password_required",
  23259. AUTHENTICATION_REQUIRED: "xmpp.authentication_required",
  23260. CHAT_ERROR_RECEIVED: "xmpp.chat_error_received",
  23261. ETHERPAD: "xmpp.etherpad"
  23262. };
  23263. module.exports = XMPPEvents;
  23264. },{}],97:[function(require,module,exports){
  23265. // Copyright Joyent, Inc. and other Node contributors.
  23266. //
  23267. // Permission is hereby granted, free of charge, to any person obtaining a
  23268. // copy of this software and associated documentation files (the
  23269. // "Software"), to deal in the Software without restriction, including
  23270. // without limitation the rights to use, copy, modify, merge, publish,
  23271. // distribute, sublicense, and/or sell copies of the Software, and to permit
  23272. // persons to whom the Software is furnished to do so, subject to the
  23273. // following conditions:
  23274. //
  23275. // The above copyright notice and this permission notice shall be included
  23276. // in all copies or substantial portions of the Software.
  23277. //
  23278. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  23279. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  23280. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  23281. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  23282. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  23283. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  23284. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  23285. function EventEmitter() {
  23286. this._events = this._events || {};
  23287. this._maxListeners = this._maxListeners || undefined;
  23288. }
  23289. module.exports = EventEmitter;
  23290. // Backwards-compat with node 0.10.x
  23291. EventEmitter.EventEmitter = EventEmitter;
  23292. EventEmitter.prototype._events = undefined;
  23293. EventEmitter.prototype._maxListeners = undefined;
  23294. // By default EventEmitters will print a warning if more than 10 listeners are
  23295. // added to it. This is a useful default which helps finding memory leaks.
  23296. EventEmitter.defaultMaxListeners = 10;
  23297. // Obviously not all Emitters should be limited to 10. This function allows
  23298. // that to be increased. Set to zero for unlimited.
  23299. EventEmitter.prototype.setMaxListeners = function(n) {
  23300. if (!isNumber(n) || n < 0 || isNaN(n))
  23301. throw TypeError('n must be a positive number');
  23302. this._maxListeners = n;
  23303. return this;
  23304. };
  23305. EventEmitter.prototype.emit = function(type) {
  23306. var er, handler, len, args, i, listeners;
  23307. if (!this._events)
  23308. this._events = {};
  23309. // If there is no 'error' event listener then throw.
  23310. if (type === 'error') {
  23311. if (!this._events.error ||
  23312. (isObject(this._events.error) && !this._events.error.length)) {
  23313. er = arguments[1];
  23314. if (er instanceof Error) {
  23315. throw er; // Unhandled 'error' event
  23316. }
  23317. throw TypeError('Uncaught, unspecified "error" event.');
  23318. }
  23319. }
  23320. handler = this._events[type];
  23321. if (isUndefined(handler))
  23322. return false;
  23323. if (isFunction(handler)) {
  23324. switch (arguments.length) {
  23325. // fast cases
  23326. case 1:
  23327. handler.call(this);
  23328. break;
  23329. case 2:
  23330. handler.call(this, arguments[1]);
  23331. break;
  23332. case 3:
  23333. handler.call(this, arguments[1], arguments[2]);
  23334. break;
  23335. // slower
  23336. default:
  23337. len = arguments.length;
  23338. args = new Array(len - 1);
  23339. for (i = 1; i < len; i++)
  23340. args[i - 1] = arguments[i];
  23341. handler.apply(this, args);
  23342. }
  23343. } else if (isObject(handler)) {
  23344. len = arguments.length;
  23345. args = new Array(len - 1);
  23346. for (i = 1; i < len; i++)
  23347. args[i - 1] = arguments[i];
  23348. listeners = handler.slice();
  23349. len = listeners.length;
  23350. for (i = 0; i < len; i++)
  23351. listeners[i].apply(this, args);
  23352. }
  23353. return true;
  23354. };
  23355. EventEmitter.prototype.addListener = function(type, listener) {
  23356. var m;
  23357. if (!isFunction(listener))
  23358. throw TypeError('listener must be a function');
  23359. if (!this._events)
  23360. this._events = {};
  23361. // To avoid recursion in the case that type === "newListener"! Before
  23362. // adding it to the listeners, first emit "newListener".
  23363. if (this._events.newListener)
  23364. this.emit('newListener', type,
  23365. isFunction(listener.listener) ?
  23366. listener.listener : listener);
  23367. if (!this._events[type])
  23368. // Optimize the case of one listener. Don't need the extra array object.
  23369. this._events[type] = listener;
  23370. else if (isObject(this._events[type]))
  23371. // If we've already got an array, just append.
  23372. this._events[type].push(listener);
  23373. else
  23374. // Adding the second element, need to change to array.
  23375. this._events[type] = [this._events[type], listener];
  23376. // Check for listener leak
  23377. if (isObject(this._events[type]) && !this._events[type].warned) {
  23378. var m;
  23379. if (!isUndefined(this._maxListeners)) {
  23380. m = this._maxListeners;
  23381. } else {
  23382. m = EventEmitter.defaultMaxListeners;
  23383. }
  23384. if (m && m > 0 && this._events[type].length > m) {
  23385. this._events[type].warned = true;
  23386. console.error('(node) warning: possible EventEmitter memory ' +
  23387. 'leak detected. %d listeners added. ' +
  23388. 'Use emitter.setMaxListeners() to increase limit.',
  23389. this._events[type].length);
  23390. if (typeof console.trace === 'function') {
  23391. // not supported in IE 10
  23392. console.trace();
  23393. }
  23394. }
  23395. }
  23396. return this;
  23397. };
  23398. EventEmitter.prototype.on = EventEmitter.prototype.addListener;
  23399. EventEmitter.prototype.once = function(type, listener) {
  23400. if (!isFunction(listener))
  23401. throw TypeError('listener must be a function');
  23402. var fired = false;
  23403. function g() {
  23404. this.removeListener(type, g);
  23405. if (!fired) {
  23406. fired = true;
  23407. listener.apply(this, arguments);
  23408. }
  23409. }
  23410. g.listener = listener;
  23411. this.on(type, g);
  23412. return this;
  23413. };
  23414. // emits a 'removeListener' event iff the listener was removed
  23415. EventEmitter.prototype.removeListener = function(type, listener) {
  23416. var list, position, length, i;
  23417. if (!isFunction(listener))
  23418. throw TypeError('listener must be a function');
  23419. if (!this._events || !this._events[type])
  23420. return this;
  23421. list = this._events[type];
  23422. length = list.length;
  23423. position = -1;
  23424. if (list === listener ||
  23425. (isFunction(list.listener) && list.listener === listener)) {
  23426. delete this._events[type];
  23427. if (this._events.removeListener)
  23428. this.emit('removeListener', type, listener);
  23429. } else if (isObject(list)) {
  23430. for (i = length; i-- > 0;) {
  23431. if (list[i] === listener ||
  23432. (list[i].listener && list[i].listener === listener)) {
  23433. position = i;
  23434. break;
  23435. }
  23436. }
  23437. if (position < 0)
  23438. return this;
  23439. if (list.length === 1) {
  23440. list.length = 0;
  23441. delete this._events[type];
  23442. } else {
  23443. list.splice(position, 1);
  23444. }
  23445. if (this._events.removeListener)
  23446. this.emit('removeListener', type, listener);
  23447. }
  23448. return this;
  23449. };
  23450. EventEmitter.prototype.removeAllListeners = function(type) {
  23451. var key, listeners;
  23452. if (!this._events)
  23453. return this;
  23454. // not listening for removeListener, no need to emit
  23455. if (!this._events.removeListener) {
  23456. if (arguments.length === 0)
  23457. this._events = {};
  23458. else if (this._events[type])
  23459. delete this._events[type];
  23460. return this;
  23461. }
  23462. // emit removeListener for all listeners on all events
  23463. if (arguments.length === 0) {
  23464. for (key in this._events) {
  23465. if (key === 'removeListener') continue;
  23466. this.removeAllListeners(key);
  23467. }
  23468. this.removeAllListeners('removeListener');
  23469. this._events = {};
  23470. return this;
  23471. }
  23472. listeners = this._events[type];
  23473. if (isFunction(listeners)) {
  23474. this.removeListener(type, listeners);
  23475. } else {
  23476. // LIFO order
  23477. while (listeners.length)
  23478. this.removeListener(type, listeners[listeners.length - 1]);
  23479. }
  23480. delete this._events[type];
  23481. return this;
  23482. };
  23483. EventEmitter.prototype.listeners = function(type) {
  23484. var ret;
  23485. if (!this._events || !this._events[type])
  23486. ret = [];
  23487. else if (isFunction(this._events[type]))
  23488. ret = [this._events[type]];
  23489. else
  23490. ret = this._events[type].slice();
  23491. return ret;
  23492. };
  23493. EventEmitter.listenerCount = function(emitter, type) {
  23494. var ret;
  23495. if (!emitter._events || !emitter._events[type])
  23496. ret = 0;
  23497. else if (isFunction(emitter._events[type]))
  23498. ret = 1;
  23499. else
  23500. ret = emitter._events[type].length;
  23501. return ret;
  23502. };
  23503. function isFunction(arg) {
  23504. return typeof arg === 'function';
  23505. }
  23506. function isNumber(arg) {
  23507. return typeof arg === 'number';
  23508. }
  23509. function isObject(arg) {
  23510. return typeof arg === 'object' && arg !== null;
  23511. }
  23512. function isUndefined(arg) {
  23513. return arg === void 0;
  23514. }
  23515. },{}]},{},[1])(1)
  23516. });