Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

app.bundle.js 884KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840
  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. sharedKeyText = sharedKeyText.replace(/\n/g, "%0D%0A");
  4200. }
  4201. var conferenceName = roomUrl.substring(roomUrl.lastIndexOf('/') + 1);
  4202. var subject = APP.translation.translateString("email.subject",
  4203. {appName:interfaceConfig.APP_NAME, conferenceName: conferenceName});
  4204. var body = APP.translation.translateString("email.body",
  4205. {appName:interfaceConfig.APP_NAME, sharedKeyText: sharedKeyText,
  4206. roomUrl: roomUrl});
  4207. body = body.replace(/\n/g, "%0D%0A");
  4208. if (window.localStorage.displayname) {
  4209. body += "%0D%0A%0D%0A" + window.localStorage.displayname;
  4210. }
  4211. if (interfaceConfig.INVITATION_POWERED_BY) {
  4212. body += "%0D%0A%0D%0A--%0D%0Apowered by jitsi.org";
  4213. }
  4214. window.open("mailto:?subject=" + subject + "&body=" + body, '_blank');
  4215. }
  4216. function callSipButtonClicked()
  4217. {
  4218. var defaultNumber
  4219. = config.defaultSipNumber ? config.defaultSipNumber : '';
  4220. var sipMsg = APP.translation.generateTranslatonHTML(
  4221. "dialog.sipMsg");
  4222. messageHandler.openTwoButtonDialog(null, null, null,
  4223. '<h2>' + sipMsg + '</h2>' +
  4224. '<input id="sipNumber" type="text"' +
  4225. ' value="' + defaultNumber + '" autofocus>',
  4226. false,
  4227. "dialog.Dial",
  4228. function (e, v, m, f) {
  4229. if (v) {
  4230. var numberInput = document.getElementById('sipNumber');
  4231. if (numberInput.value) {
  4232. APP.xmpp.dial(numberInput.value, 'fromnumber',
  4233. UI.getRoomName(), sharedKey);
  4234. }
  4235. }
  4236. },
  4237. function (event) {
  4238. document.getElementById('sipNumber').focus();
  4239. }
  4240. );
  4241. }
  4242. var Toolbar = (function (my) {
  4243. my.init = function (ui) {
  4244. for(var k in buttonHandlers)
  4245. $("#" + k).click(buttonHandlers[k]);
  4246. UI = ui;
  4247. // Update login info
  4248. APP.xmpp.addListener(
  4249. AuthenticationEvents.IDENTITY_UPDATED,
  4250. function (authenticationEnabled, userIdentity) {
  4251. var loggedIn = false;
  4252. if (userIdentity) {
  4253. loggedIn = true;
  4254. }
  4255. //FIXME: XMPP authentication need improvements for "live" login
  4256. if (!APP.xmpp.isExternalAuthEnabled() && !loggedIn)
  4257. {
  4258. authenticationEnabled = false;
  4259. }
  4260. Toolbar.showAuthenticateButton(authenticationEnabled);
  4261. if (authenticationEnabled) {
  4262. Toolbar.setAuthenticatedIdentity(userIdentity);
  4263. Toolbar.showLoginButton(!loggedIn);
  4264. Toolbar.showLogoutButton(loggedIn);
  4265. }
  4266. }
  4267. );
  4268. },
  4269. /**
  4270. * Sets shared key
  4271. * @param sKey the shared key
  4272. */
  4273. my.setSharedKey = function (sKey) {
  4274. sharedKey = sKey;
  4275. };
  4276. my.authenticateClicked = function () {
  4277. Authentication.focusAuthenticationWindow();
  4278. // Get authentication URL
  4279. if (!APP.xmpp.getMUCJoined()) {
  4280. APP.xmpp.getLoginUrl(UI.getRoomName(), function (url) {
  4281. // If conference has not been started yet - redirect to login page
  4282. window.location.href = url;
  4283. });
  4284. } else {
  4285. APP.xmpp.getPopupLoginUrl(UI.getRoomName(), function (url) {
  4286. // Otherwise - open popup with authentication URL
  4287. var authenticationWindow = Authentication.createAuthenticationWindow(
  4288. function () {
  4289. // On popup closed - retry room allocation
  4290. APP.xmpp.allocateConferenceFocus(
  4291. APP.UI.getRoomName(),
  4292. function () { console.info("AUTH DONE"); }
  4293. );
  4294. }, url);
  4295. if (!authenticationWindow) {
  4296. messageHandler.openMessageDialog(
  4297. null, "dialog.popupError");
  4298. }
  4299. });
  4300. }
  4301. };
  4302. /**
  4303. * Updates the room invite url.
  4304. */
  4305. my.updateRoomUrl = function (newRoomUrl) {
  4306. roomUrl = newRoomUrl;
  4307. // If the invite dialog has been already opened we update the information.
  4308. var inviteLink = document.getElementById('inviteLinkRef');
  4309. if (inviteLink) {
  4310. inviteLink.value = roomUrl;
  4311. inviteLink.select();
  4312. document.getElementById('jqi_state0_buttonInvite').disabled = false;
  4313. }
  4314. };
  4315. /**
  4316. * Disables and enables some of the buttons.
  4317. */
  4318. my.setupButtonsFromConfig = function () {
  4319. if (config.disablePrezi)
  4320. {
  4321. $("#prezi_button").css({display: "none"});
  4322. }
  4323. };
  4324. /**
  4325. * Opens the lock room dialog.
  4326. */
  4327. my.openLockDialog = function () {
  4328. // Only the focus is able to set a shared key.
  4329. if (!APP.xmpp.isModerator()) {
  4330. if (sharedKey) {
  4331. messageHandler.openMessageDialog(null,
  4332. "dialog.passwordError");
  4333. } else {
  4334. messageHandler.openMessageDialog(null, "dialog.passwordError2");
  4335. }
  4336. } else {
  4337. if (sharedKey) {
  4338. messageHandler.openTwoButtonDialog(null, null,
  4339. "dialog.passwordCheck",
  4340. null,
  4341. false,
  4342. "dialog.Remove",
  4343. function (e, v) {
  4344. if (v) {
  4345. Toolbar.setSharedKey('');
  4346. lockRoom(false);
  4347. }
  4348. });
  4349. } else {
  4350. var msg = APP.translation.generateTranslatonHTML(
  4351. "dialog.passwordMsg");
  4352. var yourPassword = APP.translation.translateString(
  4353. "dialog.yourPassword");
  4354. messageHandler.openTwoButtonDialog(null, null, null,
  4355. '<h2>' + msg + '</h2>' +
  4356. '<input id="lockKey" type="text"' +
  4357. ' data-i18n="[placeholder]dialog.yourPassword" ' +
  4358. 'placeholder="' + yourPassword + '" autofocus>',
  4359. false,
  4360. "dialog.Save",
  4361. function (e, v) {
  4362. if (v) {
  4363. var lockKey = document.getElementById('lockKey');
  4364. if (lockKey.value) {
  4365. Toolbar.setSharedKey(UIUtil.escapeHtml(lockKey.value));
  4366. lockRoom(true);
  4367. }
  4368. }
  4369. },
  4370. function () {
  4371. document.getElementById('lockKey').focus();
  4372. }
  4373. );
  4374. }
  4375. }
  4376. };
  4377. /**
  4378. * Opens the invite link dialog.
  4379. */
  4380. my.openLinkDialog = function () {
  4381. var inviteAttreibutes;
  4382. if (roomUrl === null) {
  4383. inviteAttreibutes = 'data-i18n="[value]roomUrlDefaultMsg" value="' +
  4384. APP.translation.translateString("roomUrlDefaultMsg") + '"';
  4385. } else {
  4386. inviteAttreibutes = "value=\"" + encodeURI(roomUrl) + "\"";
  4387. }
  4388. messageHandler.openTwoButtonDialog("dialog.shareLink",
  4389. null, null,
  4390. '<input id="inviteLinkRef" type="text" ' +
  4391. inviteAttreibutes + ' onclick="this.select();" readonly>',
  4392. false,
  4393. "dialog.Invite",
  4394. function (e, v) {
  4395. if (v) {
  4396. if (roomUrl) {
  4397. inviteParticipants();
  4398. }
  4399. }
  4400. },
  4401. function () {
  4402. if (roomUrl) {
  4403. document.getElementById('inviteLinkRef').select();
  4404. } else {
  4405. document.getElementById('jqi_state0_buttonInvite')
  4406. .disabled = true;
  4407. }
  4408. }
  4409. );
  4410. };
  4411. /**
  4412. * Opens the settings dialog.
  4413. */
  4414. my.openSettingsDialog = function () {
  4415. var settings1 = APP.translation.generateTranslatonHTML(
  4416. "dialog.settings1");
  4417. var settings2 = APP.translation.generateTranslatonHTML(
  4418. "dialog.settings2");
  4419. var settings3 = APP.translation.generateTranslatonHTML(
  4420. "dialog.settings3");
  4421. var yourPassword = APP.translation.translateString(
  4422. "dialog.yourPassword");
  4423. messageHandler.openTwoButtonDialog(null,
  4424. '<h2>' + settings1 + '</h2>' +
  4425. '<input type="checkbox" id="initMuted">' +
  4426. settings2 + '<br/>' +
  4427. '<input type="checkbox" id="requireNicknames">' +
  4428. settings3 +
  4429. '<input id="lockKey" type="text" placeholder="' + yourPassword +
  4430. '" data-i18n="[placeholder]dialog.yourPassword" autofocus>',
  4431. null,
  4432. null,
  4433. false,
  4434. "dialog.Save",
  4435. function () {
  4436. document.getElementById('lockKey').focus();
  4437. },
  4438. function (e, v) {
  4439. if (v) {
  4440. if ($('#initMuted').is(":checked")) {
  4441. // it is checked
  4442. }
  4443. if ($('#requireNicknames').is(":checked")) {
  4444. // it is checked
  4445. }
  4446. /*
  4447. var lockKey = document.getElementById('lockKey');
  4448. if (lockKey.value) {
  4449. setSharedKey(lockKey.value);
  4450. lockRoom(true);
  4451. }
  4452. */
  4453. }
  4454. }
  4455. );
  4456. };
  4457. /**
  4458. * Toggles the application in and out of full screen mode
  4459. * (a.k.a. presentation mode in Chrome).
  4460. */
  4461. my.toggleFullScreen = function () {
  4462. var fsElement = document.documentElement;
  4463. if (!document.mozFullScreen && !document.webkitIsFullScreen) {
  4464. //Enter Full Screen
  4465. if (fsElement.mozRequestFullScreen) {
  4466. fsElement.mozRequestFullScreen();
  4467. }
  4468. else {
  4469. fsElement.webkitRequestFullScreen(Element.ALLOW_KEYBOARD_INPUT);
  4470. }
  4471. } else {
  4472. //Exit Full Screen
  4473. if (document.mozCancelFullScreen) {
  4474. document.mozCancelFullScreen();
  4475. } else {
  4476. document.webkitCancelFullScreen();
  4477. }
  4478. }
  4479. };
  4480. /**
  4481. * Unlocks the lock button state.
  4482. */
  4483. my.unlockLockButton = function () {
  4484. if ($("#lockIcon").hasClass("icon-security-locked"))
  4485. UIUtil.buttonClick("#lockIcon", "icon-security icon-security-locked");
  4486. };
  4487. /**
  4488. * Updates the lock button state to locked.
  4489. */
  4490. my.lockLockButton = function () {
  4491. if ($("#lockIcon").hasClass("icon-security"))
  4492. UIUtil.buttonClick("#lockIcon", "icon-security icon-security-locked");
  4493. };
  4494. /**
  4495. * Shows or hides authentication button
  4496. * @param show <tt>true</tt> to show or <tt>false</tt> to hide
  4497. */
  4498. my.showAuthenticateButton = function (show) {
  4499. if (show) {
  4500. $('#authentication').css({display: "inline"});
  4501. }
  4502. else {
  4503. $('#authentication').css({display: "none"});
  4504. }
  4505. };
  4506. // Shows or hides the 'recording' button.
  4507. my.showRecordingButton = function (show) {
  4508. if (!config.enableRecording) {
  4509. return;
  4510. }
  4511. if (show) {
  4512. $('#recording').css({display: "inline"});
  4513. }
  4514. else {
  4515. $('#recording').css({display: "none"});
  4516. }
  4517. };
  4518. // Sets the state of the recording button
  4519. my.setRecordingButtonState = function (isRecording) {
  4520. if (isRecording) {
  4521. $('#recordButton').removeClass("icon-recEnable");
  4522. $('#recordButton').addClass("icon-recEnable active");
  4523. } else {
  4524. $('#recordButton').removeClass("icon-recEnable active");
  4525. $('#recordButton').addClass("icon-recEnable");
  4526. }
  4527. };
  4528. // Shows or hides SIP calls button
  4529. my.showSipCallButton = function (show) {
  4530. if (APP.xmpp.isSipGatewayEnabled() && show) {
  4531. $('#sipCallButton').css({display: "inline-block"});
  4532. } else {
  4533. $('#sipCallButton').css({display: "none"});
  4534. }
  4535. };
  4536. /**
  4537. * Displays user authenticated identity name(login).
  4538. * @param authIdentity identity name to be displayed.
  4539. */
  4540. my.setAuthenticatedIdentity = function (authIdentity) {
  4541. if (authIdentity) {
  4542. $('#toolbar_auth_identity').css({display: "list-item"});
  4543. $('#toolbar_auth_identity').text(authIdentity);
  4544. } else {
  4545. $('#toolbar_auth_identity').css({display: "none"});
  4546. }
  4547. };
  4548. /**
  4549. * Shows/hides login button.
  4550. * @param show <tt>true</tt> to show
  4551. */
  4552. my.showLoginButton = function (show) {
  4553. if (show) {
  4554. $('#toolbar_button_login').css({display: "list-item"});
  4555. } else {
  4556. $('#toolbar_button_login').css({display: "none"});
  4557. }
  4558. };
  4559. /**
  4560. * Shows/hides logout button.
  4561. * @param show <tt>true</tt> to show
  4562. */
  4563. my.showLogoutButton = function (show) {
  4564. if (show) {
  4565. $('#toolbar_button_logout').css({display: "list-item"});
  4566. } else {
  4567. $('#toolbar_button_logout').css({display: "none"});
  4568. }
  4569. };
  4570. /**
  4571. * Sets the state of the button. The button has blue glow if desktop
  4572. * streaming is active.
  4573. * @param active the state of the desktop streaming.
  4574. */
  4575. my.changeDesktopSharingButtonState = function (active) {
  4576. var button = $("#desktopsharing > a");
  4577. if (active)
  4578. {
  4579. button.addClass("glow");
  4580. }
  4581. else
  4582. {
  4583. button.removeClass("glow");
  4584. }
  4585. };
  4586. return my;
  4587. }(Toolbar || {}));
  4588. module.exports = Toolbar;
  4589. },{"../../../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){
  4590. /* global $, interfaceConfig, Moderator, DesktopStreaming.showDesktopSharingButton */
  4591. var toolbarTimeoutObject,
  4592. toolbarTimeout = interfaceConfig.INITIAL_TOOLBAR_TIMEOUT;
  4593. function showDesktopSharingButton() {
  4594. if (APP.desktopsharing.isDesktopSharingEnabled()) {
  4595. $('#desktopsharing').css({display: "inline"});
  4596. } else {
  4597. $('#desktopsharing').css({display: "none"});
  4598. }
  4599. }
  4600. /**
  4601. * Hides the toolbar.
  4602. */
  4603. function hideToolbar() {
  4604. var header = $("#header"),
  4605. bottomToolbar = $("#bottomToolbar");
  4606. var isToolbarHover = false;
  4607. header.find('*').each(function () {
  4608. var id = $(this).attr('id');
  4609. if ($("#" + id + ":hover").length > 0) {
  4610. isToolbarHover = true;
  4611. }
  4612. });
  4613. if ($("#bottomToolbar:hover").length > 0) {
  4614. isToolbarHover = true;
  4615. }
  4616. clearTimeout(toolbarTimeoutObject);
  4617. toolbarTimeoutObject = null;
  4618. if (!isToolbarHover) {
  4619. header.hide("slide", { direction: "up", duration: 300});
  4620. $('#subject').animate({top: "-=40"}, 300);
  4621. if ($("#remoteVideos").hasClass("hidden")) {
  4622. bottomToolbar.hide(
  4623. "slide", {direction: "right", duration: 300});
  4624. }
  4625. }
  4626. else {
  4627. toolbarTimeoutObject = setTimeout(hideToolbar, toolbarTimeout);
  4628. }
  4629. }
  4630. var ToolbarToggler = {
  4631. /**
  4632. * Shows the main toolbar.
  4633. */
  4634. showToolbar: function () {
  4635. var header = $("#header"),
  4636. bottomToolbar = $("#bottomToolbar");
  4637. if (!header.is(':visible') || !bottomToolbar.is(":visible")) {
  4638. header.show("slide", { direction: "up", duration: 300});
  4639. $('#subject').animate({top: "+=40"}, 300);
  4640. if (!bottomToolbar.is(":visible")) {
  4641. bottomToolbar.show(
  4642. "slide", {direction: "right", duration: 300});
  4643. }
  4644. if (toolbarTimeoutObject) {
  4645. clearTimeout(toolbarTimeoutObject);
  4646. toolbarTimeoutObject = null;
  4647. }
  4648. toolbarTimeoutObject = setTimeout(hideToolbar, toolbarTimeout);
  4649. toolbarTimeout = interfaceConfig.TOOLBAR_TIMEOUT;
  4650. }
  4651. if (APP.xmpp.isModerator())
  4652. {
  4653. // TODO: Enable settings functionality.
  4654. // Need to uncomment the settings button in index.html.
  4655. // $('#settingsButton').css({visibility:"visible"});
  4656. }
  4657. // Show/hide desktop sharing button
  4658. showDesktopSharingButton();
  4659. },
  4660. /**
  4661. * Docks/undocks the toolbar.
  4662. *
  4663. * @param isDock indicates what operation to perform
  4664. */
  4665. dockToolbar: function (isDock) {
  4666. if (isDock) {
  4667. // First make sure the toolbar is shown.
  4668. if (!$('#header').is(':visible')) {
  4669. this.showToolbar();
  4670. }
  4671. // Then clear the time out, to dock the toolbar.
  4672. if (toolbarTimeoutObject) {
  4673. clearTimeout(toolbarTimeoutObject);
  4674. toolbarTimeoutObject = null;
  4675. }
  4676. }
  4677. else {
  4678. if (!$('#header').is(':visible')) {
  4679. this.showToolbar();
  4680. }
  4681. else {
  4682. toolbarTimeoutObject = setTimeout(hideToolbar, toolbarTimeout);
  4683. }
  4684. }
  4685. },
  4686. showDesktopSharingButton: showDesktopSharingButton
  4687. };
  4688. module.exports = ToolbarToggler;
  4689. },{}],26:[function(require,module,exports){
  4690. var JitsiPopover = (function () {
  4691. /**
  4692. * Constructs new JitsiPopover and attaches it to the element
  4693. * @param element jquery selector
  4694. * @param options the options for the popover.
  4695. * @constructor
  4696. */
  4697. function JitsiPopover(element, options)
  4698. {
  4699. this.options = {
  4700. skin: "white",
  4701. content: ""
  4702. };
  4703. if(options)
  4704. {
  4705. if(options.skin)
  4706. this.options.skin = options.skin;
  4707. if(options.content)
  4708. this.options.content = options.content;
  4709. }
  4710. this.elementIsHovered = false;
  4711. this.popoverIsHovered = false;
  4712. this.popoverShown = false;
  4713. element.data("jitsi_popover", this);
  4714. this.element = element;
  4715. this.template = ' <div class="jitsipopover ' + this.options.skin +
  4716. '"><div class="arrow"></div><div class="jitsipopover-content"></div>' +
  4717. '<div class="jitsiPopupmenuPadding"></div></div>';
  4718. var self = this;
  4719. this.element.on("mouseenter", function () {
  4720. self.elementIsHovered = true;
  4721. self.show();
  4722. }).on("mouseleave", function () {
  4723. self.elementIsHovered = false;
  4724. setTimeout(function () {
  4725. self.hide();
  4726. }, 10);
  4727. });
  4728. }
  4729. /**
  4730. * Shows the popover
  4731. */
  4732. JitsiPopover.prototype.show = function () {
  4733. this.createPopover();
  4734. this.popoverShown = true;
  4735. };
  4736. /**
  4737. * Hides the popover
  4738. */
  4739. JitsiPopover.prototype.hide = function () {
  4740. if(!this.elementIsHovered && !this.popoverIsHovered && this.popoverShown)
  4741. {
  4742. this.forceHide();
  4743. }
  4744. };
  4745. /**
  4746. * Hides the popover
  4747. */
  4748. JitsiPopover.prototype.forceHide = function () {
  4749. $(".jitsipopover").remove();
  4750. this.popoverShown = false;
  4751. };
  4752. /**
  4753. * Creates the popover html
  4754. */
  4755. JitsiPopover.prototype.createPopover = function () {
  4756. $("body").append(this.template);
  4757. $(".jitsipopover > .jitsipopover-content").html(this.options.content);
  4758. var self = this;
  4759. $(".jitsipopover").on("mouseenter", function () {
  4760. self.popoverIsHovered = true;
  4761. }).on("mouseleave", function () {
  4762. self.popoverIsHovered = false;
  4763. self.hide();
  4764. });
  4765. this.refreshPosition();
  4766. };
  4767. /**
  4768. * Refreshes the position of the popover
  4769. */
  4770. JitsiPopover.prototype.refreshPosition = function () {
  4771. $(".jitsipopover").position({
  4772. my: "bottom",
  4773. at: "top",
  4774. collision: "fit",
  4775. of: this.element,
  4776. using: function (position, elements) {
  4777. var calcLeft = elements.target.left - elements.element.left + elements.target.width/2;
  4778. $(".jitsipopover").css({top: position.top, left: position.left, display: "table"});
  4779. $(".jitsipopover > .arrow").css({left: calcLeft});
  4780. $(".jitsipopover > .jitsiPopupmenuPadding").css({left: calcLeft - 50});
  4781. }
  4782. });
  4783. };
  4784. /**
  4785. * Updates the content of popover.
  4786. * @param content new content
  4787. */
  4788. JitsiPopover.prototype.updateContent = function (content) {
  4789. this.options.content = content;
  4790. if(!this.popoverShown)
  4791. return;
  4792. $(".jitsipopover").remove();
  4793. this.createPopover();
  4794. };
  4795. return JitsiPopover;
  4796. })();
  4797. module.exports = JitsiPopover;
  4798. },{}],27:[function(require,module,exports){
  4799. /* global $, jQuery */
  4800. var messageHandler = (function(my) {
  4801. /**
  4802. * Shows a message to the user.
  4803. *
  4804. * @param titleString the title of the message
  4805. * @param messageString the text of the message
  4806. */
  4807. my.openMessageDialog = function(titleKey, messageKey) {
  4808. var title = null;
  4809. if(titleKey)
  4810. {
  4811. title = APP.translation.generateTranslatonHTML(titleKey);
  4812. }
  4813. var message = APP.translation.generateTranslatonHTML(messageKey);
  4814. $.prompt(message,
  4815. {
  4816. title: title,
  4817. persistent: false
  4818. }
  4819. );
  4820. };
  4821. /**
  4822. * Shows a message to the user with two buttons: first is given as a parameter and the second is Cancel.
  4823. *
  4824. * @param titleString the title of the message
  4825. * @param msgString the text of the message
  4826. * @param persistent boolean value which determines whether the message is persistent or not
  4827. * @param leftButton the fist button's text
  4828. * @param submitFunction function to be called on submit
  4829. * @param loadedFunction function to be called after the prompt is fully loaded
  4830. * @param closeFunction function to be called after the prompt is closed
  4831. */
  4832. my.openTwoButtonDialog = function(titleKey, titleString, msgKey, msgString,
  4833. persistent, leftButtonKey, submitFunction, loadedFunction,
  4834. closeFunction)
  4835. {
  4836. var leftButton = APP.translation.generateTranslatonHTML(leftButtonKey);
  4837. var buttons = {};
  4838. buttons.button1 = {title: leftButton, value: true};
  4839. var cancelButton = APP.translation.generateTranslatonHTML("dialog.Cancel");
  4840. buttons.button2 = {title: cancelButton, value: false};
  4841. var message = msgString, title = titleString;
  4842. if(titleKey)
  4843. {
  4844. title = APP.translation.generateTranslatonHTML(titleKey);
  4845. }
  4846. if(msgKey) {
  4847. message = APP.translation.generateTranslatonHTML(msgKey);
  4848. }
  4849. $.prompt(message, {
  4850. title: title,
  4851. persistent: false,
  4852. buttons: buttons,
  4853. defaultButton: 1,
  4854. loaded: loadedFunction,
  4855. submit: submitFunction,
  4856. close: closeFunction
  4857. });
  4858. };
  4859. /**
  4860. * Shows a message to the user with two buttons: first is given as a parameter and the second is Cancel.
  4861. *
  4862. * @param titleString the title of the message
  4863. * @param msgString the text of the message
  4864. * @param persistent boolean value which determines whether the message is persistent or not
  4865. * @param buttons object with the buttons. The keys must be the name of the button and value is the value
  4866. * that will be passed to submitFunction
  4867. * @param submitFunction function to be called on submit
  4868. * @param loadedFunction function to be called after the prompt is fully loaded
  4869. */
  4870. my.openDialog = function (titleString, msgString, persistent, buttons,
  4871. submitFunction, loadedFunction) {
  4872. var args = {
  4873. title: titleString,
  4874. persistent: persistent,
  4875. buttons: buttons,
  4876. defaultButton: 1,
  4877. loaded: loadedFunction,
  4878. submit: submitFunction
  4879. };
  4880. if (persistent) {
  4881. args.closeText = '';
  4882. }
  4883. return $.prompt(msgString, args);
  4884. };
  4885. /**
  4886. * Closes currently opened dialog.
  4887. */
  4888. my.closeDialog = function () {
  4889. $.prompt.close();
  4890. };
  4891. /**
  4892. * Shows a dialog with different states to the user.
  4893. *
  4894. * @param statesObject object containing all the states of the dialog
  4895. * @param loadedFunction function to be called after the prompt is fully loaded
  4896. * @param stateChangedFunction function to be called when the state of the dialog is changed
  4897. */
  4898. my.openDialogWithStates = function(statesObject, loadedFunction, stateChangedFunction) {
  4899. var myPrompt = $.prompt(statesObject);
  4900. myPrompt.on('impromptu:loaded', loadedFunction);
  4901. myPrompt.on('impromptu:statechanged', stateChangedFunction);
  4902. };
  4903. /**
  4904. * Opens new popup window for given <tt>url</tt> centered over current
  4905. * window.
  4906. *
  4907. * @param url the URL to be displayed in the popup window
  4908. * @param w the width of the popup window
  4909. * @param h the height of the popup window
  4910. * @param onPopupClosed optional callback function called when popup window
  4911. * has been closed.
  4912. *
  4913. * @returns popup window object if opened successfully or undefined
  4914. * in case we failed to open it(popup blocked)
  4915. */
  4916. my.openCenteredPopup = function (url, w, h, onPopupClosed) {
  4917. var l = window.screenX + (window.innerWidth / 2) - (w / 2);
  4918. var t = window.screenY + (window.innerHeight / 2) - (h / 2);
  4919. var popup = window.open(
  4920. url, '_blank',
  4921. 'top=' + t + ', left=' + l + ', width=' + w + ', height=' + h + '');
  4922. if (popup && onPopupClosed) {
  4923. var pollTimer = window.setInterval(function () {
  4924. if (popup.closed !== false) {
  4925. window.clearInterval(pollTimer);
  4926. onPopupClosed();
  4927. }
  4928. }, 200);
  4929. }
  4930. return popup;
  4931. };
  4932. /**
  4933. * Shows a dialog prompting the user to send an error report.
  4934. *
  4935. * @param titleString the title of the message
  4936. * @param msgString the text of the message
  4937. * @param error the error that is being reported
  4938. */
  4939. my.openReportDialog = function(titleKey, msgKey, error) {
  4940. my.openMessageDialog(titleKey, msgKey);
  4941. console.log(error);
  4942. //FIXME send the error to the server
  4943. };
  4944. /**
  4945. * Shows an error dialog to the user.
  4946. * @param title the title of the message
  4947. * @param message the text of the messafe
  4948. */
  4949. my.showError = function(titleKey, msgKey) {
  4950. if(!titleKey) {
  4951. titleKey = "dialog.oops";
  4952. }
  4953. if(!msgKey)
  4954. {
  4955. msgKey = "dialog.defaultError";
  4956. }
  4957. messageHandler.openMessageDialog(titleKey, msgKey);
  4958. };
  4959. my.notify = function(displayName, displayNameKey,
  4960. cls, messageKey, messageArguments) {
  4961. var displayNameSpan = '<span class="nickname" ';
  4962. if(displayName)
  4963. {
  4964. displayNameSpan += ">" + displayName;
  4965. }
  4966. else
  4967. {
  4968. displayNameSpan += "data-i18n='" + displayNameKey +
  4969. "'>" + APP.translation.translateString(displayNameKey);
  4970. }
  4971. displayNameSpan += "</span>";
  4972. toastr.info(
  4973. displayNameSpan + '<br>' +
  4974. '<span class=' + cls + ' data-i18n="' + messageKey + '"' +
  4975. (messageArguments?
  4976. " data-i18n-options='" + JSON.stringify(messageArguments) + "'"
  4977. : "") + ">" +
  4978. APP.translation.translateString(messageKey,
  4979. messageArguments) +
  4980. '</span>');
  4981. };
  4982. return my;
  4983. }(messageHandler || {}));
  4984. module.exports = messageHandler;
  4985. },{}],28:[function(require,module,exports){
  4986. var UIEvents = require("../../../service/UI/UIEvents");
  4987. var nickname = null;
  4988. var eventEmitter = null;
  4989. var NickanameHandler = {
  4990. init: function (emitter) {
  4991. eventEmitter = emitter;
  4992. var storedDisplayName = window.localStorage.displayname;
  4993. if (storedDisplayName) {
  4994. nickname = storedDisplayName;
  4995. }
  4996. },
  4997. setNickname: function (newNickname) {
  4998. if (!newNickname || nickname === newNickname)
  4999. return;
  5000. nickname = newNickname;
  5001. window.localStorage.displayname = nickname;
  5002. eventEmitter.emit(UIEvents.NICKNAME_CHANGED, newNickname);
  5003. },
  5004. getNickname: function () {
  5005. return nickname;
  5006. },
  5007. addListener: function (type, listener) {
  5008. eventEmitter.on(type, listener);
  5009. }
  5010. };
  5011. module.exports = NickanameHandler;
  5012. },{"../../../service/UI/UIEvents":91}],29:[function(require,module,exports){
  5013. /**
  5014. * Created by hristo on 12/22/14.
  5015. */
  5016. module.exports = {
  5017. /**
  5018. * Returns the available video width.
  5019. */
  5020. getAvailableVideoWidth: function () {
  5021. var PanelToggler = require("../side_pannels/SidePanelToggler");
  5022. var rightPanelWidth
  5023. = PanelToggler.isVisible() ? PanelToggler.getPanelSize()[0] : 0;
  5024. return window.innerWidth - rightPanelWidth;
  5025. },
  5026. /**
  5027. * Changes the style class of the element given by id.
  5028. */
  5029. buttonClick: function(id, classname) {
  5030. $(id).toggleClass(classname); // add the class to the clicked element
  5031. },
  5032. /**
  5033. * Returns the text width for the given element.
  5034. *
  5035. * @param el the element
  5036. */
  5037. getTextWidth: function (el) {
  5038. return (el.clientWidth + 1);
  5039. },
  5040. /**
  5041. * Returns the text height for the given element.
  5042. *
  5043. * @param el the element
  5044. */
  5045. getTextHeight: function (el) {
  5046. return (el.clientHeight + 1);
  5047. },
  5048. /**
  5049. * Plays the sound given by id.
  5050. *
  5051. * @param id the identifier of the audio element.
  5052. */
  5053. playSoundNotification: function (id) {
  5054. document.getElementById(id).play();
  5055. },
  5056. /**
  5057. * Escapes the given text.
  5058. */
  5059. escapeHtml: function (unsafeText) {
  5060. return $('<div/>').text(unsafeText).html();
  5061. },
  5062. imageToGrayScale: function (canvas) {
  5063. var context = canvas.getContext('2d');
  5064. var imgData = context.getImageData(0, 0, canvas.width, canvas.height);
  5065. var pixels = imgData.data;
  5066. for (var i = 0, n = pixels.length; i < n; i += 4) {
  5067. var grayscale
  5068. = pixels[i] * .3 + pixels[i+1] * .59 + pixels[i+2] * .11;
  5069. pixels[i ] = grayscale; // red
  5070. pixels[i+1] = grayscale; // green
  5071. pixels[i+2] = grayscale; // blue
  5072. // pixels[i+3] is alpha
  5073. }
  5074. // redraw the image in black & white
  5075. context.putImageData(imgData, 0, 0);
  5076. },
  5077. setTooltip: function (element, key, position) {
  5078. element.setAttribute("data-i18n", "[data-content]" + key);
  5079. element.setAttribute("data-toggle", "popover");
  5080. element.setAttribute("data-placement", position);
  5081. element.setAttribute("data-html", true);
  5082. element.setAttribute("data-container", "body");
  5083. }
  5084. };
  5085. },{"../side_pannels/SidePanelToggler":16}],30:[function(require,module,exports){
  5086. var JitsiPopover = require("../util/JitsiPopover");
  5087. /**
  5088. * Constructs new connection indicator.
  5089. * @param videoContainer the video container associated with the indicator.
  5090. * @constructor
  5091. */
  5092. function ConnectionIndicator(videoContainer, jid, VideoLayout)
  5093. {
  5094. this.videoContainer = videoContainer;
  5095. this.bandwidth = null;
  5096. this.packetLoss = null;
  5097. this.bitrate = null;
  5098. this.showMoreValue = false;
  5099. this.resolution = null;
  5100. this.transport = [];
  5101. this.popover = null;
  5102. this.jid = jid;
  5103. this.create();
  5104. this.videoLayout = VideoLayout;
  5105. }
  5106. /**
  5107. * Values for the connection quality
  5108. * @type {{98: string,
  5109. * 81: string,
  5110. * 64: string,
  5111. * 47: string,
  5112. * 30: string,
  5113. * 0: string}}
  5114. */
  5115. ConnectionIndicator.connectionQualityValues = {
  5116. 98: "18px", //full
  5117. 81: "15px",//4 bars
  5118. 64: "11px",//3 bars
  5119. 47: "7px",//2 bars
  5120. 30: "3px",//1 bar
  5121. 0: "0px"//empty
  5122. };
  5123. ConnectionIndicator.getIP = function(value)
  5124. {
  5125. return value.substring(0, value.lastIndexOf(":"));
  5126. };
  5127. ConnectionIndicator.getPort = function(value)
  5128. {
  5129. return value.substring(value.lastIndexOf(":") + 1, value.length);
  5130. };
  5131. ConnectionIndicator.getStringFromArray = function (array) {
  5132. var res = "";
  5133. for(var i = 0; i < array.length; i++)
  5134. {
  5135. res += (i === 0? "" : ", ") + array[i];
  5136. }
  5137. return res;
  5138. };
  5139. /**
  5140. * Generates the html content.
  5141. * @returns {string} the html content.
  5142. */
  5143. ConnectionIndicator.prototype.generateText = function () {
  5144. var downloadBitrate, uploadBitrate, packetLoss, resolution, i;
  5145. var translate = APP.translation.translateString;
  5146. if(this.bitrate === null)
  5147. {
  5148. downloadBitrate = "N/A";
  5149. uploadBitrate = "N/A";
  5150. }
  5151. else
  5152. {
  5153. downloadBitrate =
  5154. this.bitrate.download? this.bitrate.download + " Kbps" : "N/A";
  5155. uploadBitrate =
  5156. this.bitrate.upload? this.bitrate.upload + " Kbps" : "N/A";
  5157. }
  5158. if(this.packetLoss === null)
  5159. {
  5160. packetLoss = "N/A";
  5161. }
  5162. else
  5163. {
  5164. packetLoss = "<span class='jitsipopover_green'>&darr;</span>" +
  5165. (this.packetLoss.download !== null? this.packetLoss.download : "N/A") +
  5166. "% <span class='jitsipopover_orange'>&uarr;</span>" +
  5167. (this.packetLoss.upload !== null? this.packetLoss.upload : "N/A") + "%";
  5168. }
  5169. var resolutionValue = null;
  5170. if(this.resolution && this.jid != null)
  5171. {
  5172. var keys = Object.keys(this.resolution);
  5173. if(keys.length == 1)
  5174. {
  5175. for(var ssrc in this.resolution)
  5176. {
  5177. resolutionValue = this.resolution[ssrc];
  5178. }
  5179. }
  5180. else if(keys.length > 1)
  5181. {
  5182. var displayedSsrc = APP.simulcast.getReceivingSSRC(this.jid);
  5183. resolutionValue = this.resolution[displayedSsrc];
  5184. }
  5185. }
  5186. if(this.jid === null)
  5187. {
  5188. resolution = "";
  5189. if(this.resolution === null || !Object.keys(this.resolution) ||
  5190. Object.keys(this.resolution).length === 0)
  5191. {
  5192. resolution = "N/A";
  5193. }
  5194. else
  5195. for(i in this.resolution)
  5196. {
  5197. resolutionValue = this.resolution[i];
  5198. if(resolutionValue)
  5199. {
  5200. if(resolutionValue.height &&
  5201. resolutionValue.width)
  5202. {
  5203. resolution += (resolution === ""? "" : ", ") +
  5204. resolutionValue.width + "x" +
  5205. resolutionValue.height;
  5206. }
  5207. }
  5208. }
  5209. }
  5210. else if(!resolutionValue ||
  5211. !resolutionValue.height ||
  5212. !resolutionValue.width)
  5213. {
  5214. resolution = "N/A";
  5215. }
  5216. else
  5217. {
  5218. resolution = resolutionValue.width + "x" + resolutionValue.height;
  5219. }
  5220. var result = "<table style='width:100%'>" +
  5221. "<tr>" +
  5222. "<td><span class='jitsipopover_blue' data-i18n='connectionindicator.bitrate'>" +
  5223. translate("connectionindicator.bitrate") + "</span></td>" +
  5224. "<td><span class='jitsipopover_green'>&darr;</span>" +
  5225. downloadBitrate + " <span class='jitsipopover_orange'>&uarr;</span>" +
  5226. uploadBitrate + "</td>" +
  5227. "</tr><tr>" +
  5228. "<td><span class='jitsipopover_blue' data-i18n='connectionindicator.packetloss'>" +
  5229. translate("connectionindicator.packetloss") + "</span></td>" +
  5230. "<td>" + packetLoss + "</td>" +
  5231. "</tr><tr>" +
  5232. "<td><span class='jitsipopover_blue' data-i18n='connectionindicator.resolution'>" +
  5233. translate("connectionindicator.resolution") + "</span></td>" +
  5234. "<td>" + resolution + "</td></tr></table>";
  5235. if(this.videoContainer.id == "localVideoContainer") {
  5236. result += "<div class=\"jitsipopover_showmore\" " +
  5237. "onclick = \"APP.UI.connectionIndicatorShowMore('" +
  5238. this.videoContainer.id + "')\" data-i18n='connectionindicator." +
  5239. (this.showMoreValue ? "less" : "more") + "'>" +
  5240. translate("connectionindicator." + (this.showMoreValue ? "less" : "more")) +
  5241. "</div><br />";
  5242. }
  5243. if(this.showMoreValue)
  5244. {
  5245. var downloadBandwidth, uploadBandwidth, transport;
  5246. if(this.bandwidth === null)
  5247. {
  5248. downloadBandwidth = "N/A";
  5249. uploadBandwidth = "N/A";
  5250. }
  5251. else
  5252. {
  5253. downloadBandwidth = this.bandwidth.download?
  5254. this.bandwidth.download + " Kbps" :
  5255. "N/A";
  5256. uploadBandwidth = this.bandwidth.upload?
  5257. this.bandwidth.upload + " Kbps" :
  5258. "N/A";
  5259. }
  5260. if(!this.transport || this.transport.length === 0)
  5261. {
  5262. transport = "<tr>" +
  5263. "<td><span class='jitsipopover_blue' " +
  5264. "data-i18n='connectionindicator.address'>" +
  5265. translate("connectionindicator.address") + "</span></td>" +
  5266. "<td> N/A</td></tr>";
  5267. }
  5268. else
  5269. {
  5270. var data = {remoteIP: [], localIP:[], remotePort:[], localPort:[]};
  5271. for(i = 0; i < this.transport.length; i++)
  5272. {
  5273. var ip = ConnectionIndicator.getIP(this.transport[i].ip);
  5274. var port = ConnectionIndicator.getPort(this.transport[i].ip);
  5275. var localIP =
  5276. ConnectionIndicator.getIP(this.transport[i].localip);
  5277. var localPort =
  5278. ConnectionIndicator.getPort(this.transport[i].localip);
  5279. if(data.remoteIP.indexOf(ip) == -1)
  5280. {
  5281. data.remoteIP.push(ip);
  5282. }
  5283. if(data.remotePort.indexOf(port) == -1)
  5284. {
  5285. data.remotePort.push(port);
  5286. }
  5287. if(data.localIP.indexOf(localIP) == -1)
  5288. {
  5289. data.localIP.push(localIP);
  5290. }
  5291. if(data.localPort.indexOf(localPort) == -1)
  5292. {
  5293. data.localPort.push(localPort);
  5294. }
  5295. }
  5296. var local_address_key = "connectionindicator.localaddress";
  5297. var remote_address_key = "connectionindicator.remoteaddress";
  5298. var localTransport =
  5299. "<tr><td><span class='jitsipopover_blue' data-i18n='" +
  5300. local_address_key +"' data-i18n-options='" +
  5301. JSON.stringify({count: data.localIP.length}) + "'>" +
  5302. translate(local_address_key, {count: data.localIP.length}) +
  5303. "</span></td><td> " +
  5304. ConnectionIndicator.getStringFromArray(data.localIP) +
  5305. "</td></tr>";
  5306. transport =
  5307. "<tr><td><span class='jitsipopover_blue' data-i18n='" +
  5308. remote_address_key + "' data-i18n-options='" +
  5309. JSON.stringify({count: data.remoteIP.length}) + "'>" +
  5310. translate(remote_address_key,
  5311. {count: data.remoteIP.length}) +
  5312. "</span></td><td> " +
  5313. ConnectionIndicator.getStringFromArray(data.remoteIP) +
  5314. "</td></tr>";
  5315. var key_remote = "connectionindicator.remoteport",
  5316. key_local = "connectionindicator.localport";
  5317. transport += "<tr>" +
  5318. "<td>" +
  5319. "<span class='jitsipopover_blue' data-i18n='" + key_remote +
  5320. "' data-i18n-options='" +
  5321. JSON.stringify({count: this.transport.length}) + "'>" +
  5322. translate(key_remote, {count: this.transport.length}) +
  5323. "</span></td><td>";
  5324. localTransport += "<tr>" +
  5325. "<td>" +
  5326. "<span class='jitsipopover_blue' data-i18n='" + key_local +
  5327. "' data-i18n-options='" +
  5328. JSON.stringify({count: this.transport.length}) + "'>" +
  5329. translate(key_local, {count: this.transport.length}) +
  5330. "</span></td><td>";
  5331. transport +=
  5332. ConnectionIndicator.getStringFromArray(data.remotePort);
  5333. localTransport +=
  5334. ConnectionIndicator.getStringFromArray(data.localPort);
  5335. transport += "</td></tr>";
  5336. transport += localTransport + "</td></tr>";
  5337. transport +="<tr>" +
  5338. "<td><span class='jitsipopover_blue' data-i18n='connectionindicator.transport'>" +
  5339. translate("connectionindicator.transport") + "</span></td>" +
  5340. "<td>" + this.transport[0].type + "</td></tr>";
  5341. }
  5342. result += "<table style='width:100%'>" +
  5343. "<tr>" +
  5344. "<td>" +
  5345. "<span class='jitsipopover_blue' data-i18n='connectionindicator.bandwidth'>" +
  5346. translate("connectionindicator.bandwidth") + "</span>" +
  5347. "</td><td>" +
  5348. "<span class='jitsipopover_green'>&darr;</span>" +
  5349. downloadBandwidth +
  5350. " <span class='jitsipopover_orange'>&uarr;</span>" +
  5351. uploadBandwidth + "</td></tr>";
  5352. result += transport + "</table>";
  5353. }
  5354. return result;
  5355. };
  5356. /**
  5357. * Shows or hide the additional information.
  5358. */
  5359. ConnectionIndicator.prototype.showMore = function () {
  5360. this.showMoreValue = !this.showMoreValue;
  5361. this.updatePopoverData();
  5362. };
  5363. function createIcon(classes)
  5364. {
  5365. var icon = document.createElement("span");
  5366. for(var i in classes)
  5367. {
  5368. icon.classList.add(classes[i]);
  5369. }
  5370. icon.appendChild(
  5371. document.createElement("i")).classList.add("icon-connection");
  5372. return icon;
  5373. }
  5374. /**
  5375. * Creates the indicator
  5376. */
  5377. ConnectionIndicator.prototype.create = function () {
  5378. this.connectionIndicatorContainer = document.createElement("div");
  5379. this.connectionIndicatorContainer.className = "connectionindicator";
  5380. this.connectionIndicatorContainer.style.display = "none";
  5381. this.videoContainer.appendChild(this.connectionIndicatorContainer);
  5382. this.popover = new JitsiPopover(
  5383. $("#" + this.videoContainer.id + " > .connectionindicator"),
  5384. {content: "<div class=\"connection_info\" data-i18n='connectionindicator.na'>" +
  5385. APP.translation.translateString("connectionindicator.na") + "</div>",
  5386. skin: "black"});
  5387. this.emptyIcon = this.connectionIndicatorContainer.appendChild(
  5388. createIcon(["connection", "connection_empty"]));
  5389. this.fullIcon = this.connectionIndicatorContainer.appendChild(
  5390. createIcon(["connection", "connection_full"]));
  5391. };
  5392. /**
  5393. * Removes the indicator
  5394. */
  5395. ConnectionIndicator.prototype.remove = function()
  5396. {
  5397. this.connectionIndicatorContainer.remove();
  5398. this.popover.forceHide();
  5399. };
  5400. /**
  5401. * Updates the data of the indicator
  5402. * @param percent the percent of connection quality
  5403. * @param object the statistics data.
  5404. */
  5405. ConnectionIndicator.prototype.updateConnectionQuality =
  5406. function (percent, object) {
  5407. if(percent === null)
  5408. {
  5409. this.connectionIndicatorContainer.style.display = "none";
  5410. this.popover.forceHide();
  5411. return;
  5412. }
  5413. else
  5414. {
  5415. if(this.connectionIndicatorContainer.style.display == "none") {
  5416. this.connectionIndicatorContainer.style.display = "block";
  5417. this.videoLayout.updateMutePosition(this.videoContainer.id);
  5418. }
  5419. }
  5420. this.bandwidth = object.bandwidth;
  5421. this.bitrate = object.bitrate;
  5422. this.packetLoss = object.packetLoss;
  5423. this.transport = object.transport;
  5424. if(object.resolution)
  5425. {
  5426. this.resolution = object.resolution;
  5427. }
  5428. for(var quality in ConnectionIndicator.connectionQualityValues)
  5429. {
  5430. if(percent >= quality)
  5431. {
  5432. this.fullIcon.style.width =
  5433. ConnectionIndicator.connectionQualityValues[quality];
  5434. }
  5435. }
  5436. this.updatePopoverData();
  5437. };
  5438. /**
  5439. * Updates the resolution
  5440. * @param resolution the new resolution
  5441. */
  5442. ConnectionIndicator.prototype.updateResolution = function (resolution) {
  5443. this.resolution = resolution;
  5444. this.updatePopoverData();
  5445. };
  5446. /**
  5447. * Updates the content of the popover
  5448. */
  5449. ConnectionIndicator.prototype.updatePopoverData = function () {
  5450. this.popover.updateContent(
  5451. "<div class=\"connection_info\">" + this.generateText() + "</div>");
  5452. APP.translation.translateElement($(".connection_info"));
  5453. };
  5454. /**
  5455. * Hides the popover
  5456. */
  5457. ConnectionIndicator.prototype.hide = function () {
  5458. this.popover.forceHide();
  5459. };
  5460. /**
  5461. * Hides the indicator
  5462. */
  5463. ConnectionIndicator.prototype.hideIndicator = function () {
  5464. this.connectionIndicatorContainer.style.display = "none";
  5465. if(this.popover)
  5466. this.popover.forceHide();
  5467. };
  5468. module.exports = ConnectionIndicator;
  5469. },{"../util/JitsiPopover":26}],31:[function(require,module,exports){
  5470. var AudioLevels = require("../audio_levels/AudioLevels");
  5471. var Avatar = require("../avatar/Avatar");
  5472. var Chat = require("../side_pannels/chat/Chat");
  5473. var ContactList = require("../side_pannels/contactlist/ContactList");
  5474. var UIUtil = require("../util/UIUtil");
  5475. var ConnectionIndicator = require("./ConnectionIndicator");
  5476. var NicknameHandler = require("../util/NicknameHandler");
  5477. var MediaStreamType = require("../../../service/RTC/MediaStreamTypes");
  5478. var UIEvents = require("../../../service/UI/UIEvents");
  5479. var currentDominantSpeaker = null;
  5480. var lastNCount = config.channelLastN;
  5481. var localLastNCount = config.channelLastN;
  5482. var localLastNSet = [];
  5483. var lastNEndpointsCache = [];
  5484. var lastNPickupJid = null;
  5485. var largeVideoState = {
  5486. updateInProgress: false,
  5487. newSrc: ''
  5488. };
  5489. var eventEmitter = null;
  5490. /**
  5491. * Currently focused video "src"(displayed in large video).
  5492. * @type {String}
  5493. */
  5494. var focusedVideoInfo = null;
  5495. /**
  5496. * Indicates if we have muted our audio before the conference has started.
  5497. * @type {boolean}
  5498. */
  5499. var preMuted = false;
  5500. var mutedAudios = {};
  5501. var flipXLocalVideo = true;
  5502. var currentVideoWidth = null;
  5503. var currentVideoHeight = null;
  5504. var localVideoSrc = null;
  5505. function videoactive( videoelem) {
  5506. if (videoelem.attr('id').indexOf('mixedmslabel') === -1) {
  5507. // ignore mixedmslabela0 and v0
  5508. videoelem.show();
  5509. VideoLayout.resizeThumbnails();
  5510. var videoParent = videoelem.parent();
  5511. var parentResourceJid = null;
  5512. if (videoParent)
  5513. parentResourceJid
  5514. = VideoLayout.getPeerContainerResourceJid(videoParent[0]);
  5515. // Update the large video to the last added video only if there's no
  5516. // current dominant, focused speaker or prezi playing or update it to
  5517. // the current dominant speaker.
  5518. if ((!focusedVideoInfo &&
  5519. !VideoLayout.getDominantSpeakerResourceJid() &&
  5520. !require("../prezi/Prezi").isPresentationVisible()) ||
  5521. (parentResourceJid &&
  5522. VideoLayout.getDominantSpeakerResourceJid() === parentResourceJid)) {
  5523. VideoLayout.updateLargeVideo(
  5524. APP.RTC.getVideoSrc(videoelem[0]),
  5525. 1,
  5526. parentResourceJid);
  5527. }
  5528. VideoLayout.showModeratorIndicator();
  5529. }
  5530. }
  5531. function waitForRemoteVideo(selector, ssrc, stream, jid) {
  5532. // XXX(gp) so, every call to this function is *always* preceded by a call
  5533. // to the RTC.attachMediaStream() function but that call is *not* followed
  5534. // by an update to the videoSrcToSsrc map!
  5535. //
  5536. // The above way of doing things results in video SRCs that don't correspond
  5537. // to any SSRC for a short period of time (to be more precise, for as long
  5538. // the waitForRemoteVideo takes to complete). This causes problems (see
  5539. // bellow).
  5540. //
  5541. // I'm wondering why we need to do that; i.e. why call RTC.attachMediaStream()
  5542. // a second time in here and only then update the videoSrcToSsrc map? Why
  5543. // not simply update the videoSrcToSsrc map when the RTC.attachMediaStream()
  5544. // is called the first time? I actually do that in the lastN changed event
  5545. // handler because the "orphan" video SRC is causing troubles there. The
  5546. // purpose of this method would then be to fire the "videoactive.jingle".
  5547. //
  5548. // Food for though I guess :-)
  5549. if (selector.removed || !selector.parent().is(":visible")) {
  5550. console.warn("Media removed before had started", selector);
  5551. return;
  5552. }
  5553. if (stream.id === 'mixedmslabel') return;
  5554. if (selector[0].currentTime > 0) {
  5555. var videoStream = APP.simulcast.getReceivingVideoStream(stream);
  5556. APP.RTC.attachMediaStream(selector, videoStream); // FIXME: why do i have to do this for FF?
  5557. videoactive(selector);
  5558. } else {
  5559. setTimeout(function () {
  5560. waitForRemoteVideo(selector, ssrc, stream, jid);
  5561. }, 250);
  5562. }
  5563. }
  5564. /**
  5565. * Returns an array of the video horizontal and vertical indents,
  5566. * so that if fits its parent.
  5567. *
  5568. * @return an array with 2 elements, the horizontal indent and the vertical
  5569. * indent
  5570. */
  5571. function getCameraVideoPosition(videoWidth,
  5572. videoHeight,
  5573. videoSpaceWidth,
  5574. videoSpaceHeight) {
  5575. // Parent height isn't completely calculated when we position the video in
  5576. // full screen mode and this is why we use the screen height in this case.
  5577. // Need to think it further at some point and implement it properly.
  5578. var isFullScreen = document.fullScreen ||
  5579. document.mozFullScreen ||
  5580. document.webkitIsFullScreen;
  5581. if (isFullScreen)
  5582. videoSpaceHeight = window.innerHeight;
  5583. var horizontalIndent = (videoSpaceWidth - videoWidth) / 2;
  5584. var verticalIndent = (videoSpaceHeight - videoHeight) / 2;
  5585. return [horizontalIndent, verticalIndent];
  5586. }
  5587. /**
  5588. * Returns an array of the video horizontal and vertical indents.
  5589. * Centers horizontally and top aligns vertically.
  5590. *
  5591. * @return an array with 2 elements, the horizontal indent and the vertical
  5592. * indent
  5593. */
  5594. function getDesktopVideoPosition(videoWidth,
  5595. videoHeight,
  5596. videoSpaceWidth,
  5597. videoSpaceHeight) {
  5598. var horizontalIndent = (videoSpaceWidth - videoWidth) / 2;
  5599. var verticalIndent = 0;// Top aligned
  5600. return [horizontalIndent, verticalIndent];
  5601. }
  5602. /**
  5603. * Returns an array of the video dimensions, so that it covers the screen.
  5604. * It leaves no empty areas, but some parts of the video might not be visible.
  5605. *
  5606. * @return an array with 2 elements, the video width and the video height
  5607. */
  5608. function getCameraVideoSize(videoWidth,
  5609. videoHeight,
  5610. videoSpaceWidth,
  5611. videoSpaceHeight) {
  5612. if (!videoWidth)
  5613. videoWidth = currentVideoWidth;
  5614. if (!videoHeight)
  5615. videoHeight = currentVideoHeight;
  5616. var aspectRatio = videoWidth / videoHeight;
  5617. var availableWidth = Math.max(videoWidth, videoSpaceWidth);
  5618. var availableHeight = Math.max(videoHeight, videoSpaceHeight);
  5619. if (availableWidth / aspectRatio < videoSpaceHeight) {
  5620. availableHeight = videoSpaceHeight;
  5621. availableWidth = availableHeight * aspectRatio;
  5622. }
  5623. if (availableHeight * aspectRatio < videoSpaceWidth) {
  5624. availableWidth = videoSpaceWidth;
  5625. availableHeight = availableWidth / aspectRatio;
  5626. }
  5627. return [availableWidth, availableHeight];
  5628. }
  5629. /**
  5630. * Sets the display name for the given video span id.
  5631. */
  5632. function setDisplayName(videoSpanId, displayName, key) {
  5633. var nameSpan = $('#' + videoSpanId + '>span.displayname');
  5634. var defaultLocalDisplayName = APP.translation.generateTranslatonHTML(
  5635. interfaceConfig.DEFAULT_LOCAL_DISPLAY_NAME);
  5636. // If we already have a display name for this video.
  5637. if (nameSpan.length > 0) {
  5638. var nameSpanElement = nameSpan.get(0);
  5639. if (nameSpanElement.id === 'localDisplayName' &&
  5640. $('#localDisplayName').text() !== displayName) {
  5641. if (displayName && displayName.length > 0)
  5642. {
  5643. var meHTML = APP.translation.generateTranslatonHTML("me");
  5644. $('#localDisplayName').html(displayName + ' (' + meHTML + ')');
  5645. }
  5646. else
  5647. $('#localDisplayName').html(defaultLocalDisplayName);
  5648. } else {
  5649. if (displayName && displayName.length > 0)
  5650. {
  5651. $('#' + videoSpanId + '_name').html(displayName);
  5652. }
  5653. else if (key && key.length > 0)
  5654. {
  5655. var nameHtml = APP.translation.generateTranslatonHTML(key);
  5656. $('#' + videoSpanId + '_name').html(nameHtml);
  5657. }
  5658. else
  5659. $('#' + videoSpanId + '_name').text(
  5660. interfaceConfig.DEFAULT_REMOTE_DISPLAY_NAME);
  5661. }
  5662. } else {
  5663. var editButton = null;
  5664. nameSpan = document.createElement('span');
  5665. nameSpan.className = 'displayname';
  5666. $('#' + videoSpanId)[0].appendChild(nameSpan);
  5667. if (videoSpanId === 'localVideoContainer') {
  5668. editButton = createEditDisplayNameButton();
  5669. if (displayName && displayName.length > 0) {
  5670. var meHTML = APP.translation.generateTranslatonHTML("me");
  5671. nameSpan.innerHTML = displayName + meHTML;
  5672. }
  5673. else
  5674. nameSpan.innerHTML = defaultLocalDisplayName;
  5675. }
  5676. else {
  5677. if (displayName && displayName.length > 0) {
  5678. nameSpan.innerText = displayName;
  5679. }
  5680. else
  5681. nameSpan.innerText = interfaceConfig.DEFAULT_REMOTE_DISPLAY_NAME;
  5682. }
  5683. if (!editButton) {
  5684. nameSpan.id = videoSpanId + '_name';
  5685. } else {
  5686. nameSpan.id = 'localDisplayName';
  5687. $('#' + videoSpanId)[0].appendChild(editButton);
  5688. //translates popover of edit button
  5689. APP.translation.translateElement($("a.displayname"));
  5690. var editableText = document.createElement('input');
  5691. editableText.className = 'displayname';
  5692. editableText.type = 'text';
  5693. editableText.id = 'editDisplayName';
  5694. if (displayName && displayName.length) {
  5695. editableText.value
  5696. = displayName;
  5697. }
  5698. var defaultNickname = APP.translation.translateString(
  5699. "defaultNickname", {name: "Jane Pink"});
  5700. editableText.setAttribute('style', 'display:none;');
  5701. editableText.setAttribute('data-18n',
  5702. '[placeholder]defaultNickname');
  5703. editableText.setAttribute("data-i18n-options",
  5704. JSON.stringify({name: "Jane Pink"}));
  5705. editableText.setAttribute("placeholder", defaultNickname);
  5706. $('#' + videoSpanId)[0].appendChild(editableText);
  5707. $('#localVideoContainer .displayname')
  5708. .bind("click", function (e) {
  5709. e.preventDefault();
  5710. e.stopPropagation();
  5711. $('#localDisplayName').hide();
  5712. $('#editDisplayName').show();
  5713. $('#editDisplayName').focus();
  5714. $('#editDisplayName').select();
  5715. $('#editDisplayName').one("focusout", function (e) {
  5716. VideoLayout.inputDisplayNameHandler(this.value);
  5717. });
  5718. $('#editDisplayName').on('keydown', function (e) {
  5719. if (e.keyCode === 13) {
  5720. e.preventDefault();
  5721. VideoLayout.inputDisplayNameHandler(this.value);
  5722. }
  5723. });
  5724. });
  5725. }
  5726. }
  5727. }
  5728. /**
  5729. * Gets the selector of video thumbnail container for the user identified by
  5730. * given <tt>userJid</tt>
  5731. * @param resourceJid user's Jid for whom we want to get the video container.
  5732. */
  5733. function getParticipantContainer(resourceJid)
  5734. {
  5735. if (!resourceJid)
  5736. return null;
  5737. if (resourceJid === APP.xmpp.myResource())
  5738. return $("#localVideoContainer");
  5739. else
  5740. return $("#participant_" + resourceJid);
  5741. }
  5742. /**
  5743. * Sets the size and position of the given video element.
  5744. *
  5745. * @param video the video element to position
  5746. * @param width the desired video width
  5747. * @param height the desired video height
  5748. * @param horizontalIndent the left and right indent
  5749. * @param verticalIndent the top and bottom indent
  5750. */
  5751. function positionVideo(video,
  5752. width,
  5753. height,
  5754. horizontalIndent,
  5755. verticalIndent) {
  5756. video.width(width);
  5757. video.height(height);
  5758. video.css({ top: verticalIndent + 'px',
  5759. bottom: verticalIndent + 'px',
  5760. left: horizontalIndent + 'px',
  5761. right: horizontalIndent + 'px'});
  5762. }
  5763. /**
  5764. * Adds the remote video menu element for the given <tt>jid</tt> in the
  5765. * given <tt>parentElement</tt>.
  5766. *
  5767. * @param jid the jid indicating the video for which we're adding a menu.
  5768. * @param parentElement the parent element where this menu will be added
  5769. */
  5770. function addRemoteVideoMenu(jid, parentElement) {
  5771. var spanElement = document.createElement('span');
  5772. spanElement.className = 'remotevideomenu';
  5773. parentElement.appendChild(spanElement);
  5774. var menuElement = document.createElement('i');
  5775. menuElement.className = 'fa fa-angle-down';
  5776. menuElement.title = 'Remote user controls';
  5777. spanElement.appendChild(menuElement);
  5778. // <ul class="popupmenu">
  5779. // <li><a href="#">Mute</a></li>
  5780. // <li><a href="#">Eject</a></li>
  5781. // </ul>
  5782. var popupmenuElement = document.createElement('ul');
  5783. popupmenuElement.className = 'popupmenu';
  5784. popupmenuElement.id
  5785. = 'remote_popupmenu_' + Strophe.getResourceFromJid(jid);
  5786. spanElement.appendChild(popupmenuElement);
  5787. var muteMenuItem = document.createElement('li');
  5788. var muteLinkItem = document.createElement('a');
  5789. var mutedIndicator = "<i style='float:left;' class='icon-mic-disabled'></i>";
  5790. if (!mutedAudios[jid]) {
  5791. muteLinkItem.innerHTML = mutedIndicator +
  5792. " <div style='width: 90px;margin-left: 20px;' data-i18n='videothumbnail.domute'></div>";
  5793. muteLinkItem.className = 'mutelink';
  5794. }
  5795. else {
  5796. muteLinkItem.innerHTML = mutedIndicator +
  5797. " <div style='width: 90px;margin-left: 20px;' data-i18n='videothumbnail.muted'></div>";
  5798. muteLinkItem.className = 'mutelink disabled';
  5799. }
  5800. muteLinkItem.onclick = function(){
  5801. if ($(this).attr('disabled') != undefined) {
  5802. event.preventDefault();
  5803. }
  5804. var isMute = mutedAudios[jid] == true;
  5805. APP.xmpp.setMute(jid, !isMute);
  5806. popupmenuElement.setAttribute('style', 'display:none;');
  5807. if (isMute) {
  5808. this.innerHTML = mutedIndicator +
  5809. " <div style='width: 90px;margin-left: 20px;' data-i18n='videothumbnail.muted'></div>";
  5810. this.className = 'mutelink disabled';
  5811. }
  5812. else {
  5813. this.innerHTML = mutedIndicator +
  5814. " <div style='width: 90px;margin-left: 20px;' data-i18n='videothumbnail.domute'></div>";
  5815. this.className = 'mutelink';
  5816. }
  5817. };
  5818. muteMenuItem.appendChild(muteLinkItem);
  5819. popupmenuElement.appendChild(muteMenuItem);
  5820. var ejectIndicator = "<i style='float:left;' class='fa fa-eject'></i>";
  5821. var ejectMenuItem = document.createElement('li');
  5822. var ejectLinkItem = document.createElement('a');
  5823. var ejectText = "<div style='width: 90px;margin-left: 20px;' data-i18n='videothumbnail.kick'>&nbsp;</div>";
  5824. ejectLinkItem.innerHTML = ejectIndicator + ' ' + ejectText;
  5825. ejectLinkItem.onclick = function(){
  5826. APP.xmpp.eject(jid);
  5827. popupmenuElement.setAttribute('style', 'display:none;');
  5828. };
  5829. ejectMenuItem.appendChild(ejectLinkItem);
  5830. popupmenuElement.appendChild(ejectMenuItem);
  5831. var paddingSpan = document.createElement('span');
  5832. paddingSpan.className = 'popupmenuPadding';
  5833. popupmenuElement.appendChild(paddingSpan);
  5834. APP.translation.translateElement($("#" + popupmenuElement.id + " > li > a > div"));
  5835. }
  5836. /**
  5837. * Removes remote video menu element from video element identified by
  5838. * given <tt>videoElementId</tt>.
  5839. *
  5840. * @param videoElementId the id of local or remote video element.
  5841. */
  5842. function removeRemoteVideoMenu(videoElementId) {
  5843. var menuSpan = $('#' + videoElementId + '>span.remotevideomenu');
  5844. if (menuSpan.length) {
  5845. menuSpan.remove();
  5846. }
  5847. }
  5848. /**
  5849. * Updates the data for the indicator
  5850. * @param id the id of the indicator
  5851. * @param percent the percent for connection quality
  5852. * @param object the data
  5853. */
  5854. function updateStatsIndicator(id, percent, object) {
  5855. if(VideoLayout.connectionIndicators[id])
  5856. VideoLayout.connectionIndicators[id].updateConnectionQuality(percent, object);
  5857. }
  5858. /**
  5859. * Returns an array of the video dimensions, so that it keeps it's aspect
  5860. * ratio and fits available area with it's larger dimension. This method
  5861. * ensures that whole video will be visible and can leave empty areas.
  5862. *
  5863. * @return an array with 2 elements, the video width and the video height
  5864. */
  5865. function getDesktopVideoSize(videoWidth,
  5866. videoHeight,
  5867. videoSpaceWidth,
  5868. videoSpaceHeight) {
  5869. if (!videoWidth)
  5870. videoWidth = currentVideoWidth;
  5871. if (!videoHeight)
  5872. videoHeight = currentVideoHeight;
  5873. var aspectRatio = videoWidth / videoHeight;
  5874. var availableWidth = Math.max(videoWidth, videoSpaceWidth);
  5875. var availableHeight = Math.max(videoHeight, videoSpaceHeight);
  5876. videoSpaceHeight -= $('#remoteVideos').outerHeight();
  5877. if (availableWidth / aspectRatio >= videoSpaceHeight)
  5878. {
  5879. availableHeight = videoSpaceHeight;
  5880. availableWidth = availableHeight * aspectRatio;
  5881. }
  5882. if (availableHeight * aspectRatio >= videoSpaceWidth)
  5883. {
  5884. availableWidth = videoSpaceWidth;
  5885. availableHeight = availableWidth / aspectRatio;
  5886. }
  5887. return [availableWidth, availableHeight];
  5888. }
  5889. /**
  5890. * Creates the edit display name button.
  5891. *
  5892. * @returns the edit button
  5893. */
  5894. function createEditDisplayNameButton() {
  5895. var editButton = document.createElement('a');
  5896. editButton.className = 'displayname';
  5897. UIUtil.setTooltip(editButton,
  5898. "videothumbnail.editnickname",
  5899. "top");
  5900. editButton.innerHTML = '<i class="fa fa-pencil"></i>';
  5901. return editButton;
  5902. }
  5903. /**
  5904. * Creates the element indicating the moderator(owner) of the conference.
  5905. *
  5906. * @param parentElement the parent element where the owner indicator will
  5907. * be added
  5908. */
  5909. function createModeratorIndicatorElement(parentElement) {
  5910. var moderatorIndicator = document.createElement('i');
  5911. moderatorIndicator.className = 'fa fa-star';
  5912. parentElement.appendChild(moderatorIndicator);
  5913. UIUtil.setTooltip(parentElement,
  5914. "videothumbnail.moderator",
  5915. "top");
  5916. }
  5917. var VideoLayout = (function (my) {
  5918. my.connectionIndicators = {};
  5919. // By default we use camera
  5920. my.getVideoSize = getCameraVideoSize;
  5921. my.getVideoPosition = getCameraVideoPosition;
  5922. my.init = function (emitter) {
  5923. // Listen for large video size updates
  5924. document.getElementById('largeVideo')
  5925. .addEventListener('loadedmetadata', function (e) {
  5926. currentVideoWidth = this.videoWidth;
  5927. currentVideoHeight = this.videoHeight;
  5928. VideoLayout.positionLarge(currentVideoWidth, currentVideoHeight);
  5929. });
  5930. eventEmitter = emitter;
  5931. };
  5932. my.isInLastN = function(resource) {
  5933. return lastNCount < 0 // lastN is disabled, return true
  5934. || (lastNCount > 0 && lastNEndpointsCache.length == 0) // lastNEndpoints cache not built yet, return true
  5935. || (lastNEndpointsCache && lastNEndpointsCache.indexOf(resource) !== -1);
  5936. };
  5937. my.changeLocalStream = function (stream) {
  5938. VideoLayout.changeLocalVideo(stream);
  5939. };
  5940. my.changeLocalAudio = function(stream) {
  5941. APP.RTC.attachMediaStream($('#localAudio'), stream.getOriginalStream());
  5942. document.getElementById('localAudio').autoplay = true;
  5943. document.getElementById('localAudio').volume = 0;
  5944. if (preMuted) {
  5945. if(!APP.UI.setAudioMuted(true))
  5946. {
  5947. preMuted = mute;
  5948. }
  5949. preMuted = false;
  5950. }
  5951. };
  5952. my.changeLocalVideo = function(stream) {
  5953. var flipX = true;
  5954. if(stream.videoType == "screen")
  5955. flipX = false;
  5956. var localVideo = document.createElement('video');
  5957. localVideo.id = 'localVideo_' +
  5958. APP.RTC.getStreamID(stream.getOriginalStream());
  5959. localVideo.autoplay = true;
  5960. localVideo.volume = 0; // is it required if audio is separated ?
  5961. localVideo.oncontextmenu = function () { return false; };
  5962. var localVideoContainer = document.getElementById('localVideoWrapper');
  5963. localVideoContainer.appendChild(localVideo);
  5964. // Set default display name.
  5965. setDisplayName('localVideoContainer');
  5966. if(!VideoLayout.connectionIndicators["localVideoContainer"]) {
  5967. VideoLayout.connectionIndicators["localVideoContainer"]
  5968. = new ConnectionIndicator($("#localVideoContainer")[0], null, VideoLayout);
  5969. }
  5970. AudioLevels.updateAudioLevelCanvas(null, VideoLayout);
  5971. var localVideoSelector = $('#' + localVideo.id);
  5972. function localVideoClick(event) {
  5973. event.stopPropagation();
  5974. VideoLayout.handleVideoThumbClicked(
  5975. APP.RTC.getVideoSrc(localVideo),
  5976. false,
  5977. APP.xmpp.myResource());
  5978. }
  5979. // Add click handler to both video and video wrapper elements in case
  5980. // there's no video.
  5981. localVideoSelector.click(localVideoClick);
  5982. $('#localVideoContainer').click(localVideoClick);
  5983. // Add hover handler
  5984. $('#localVideoContainer').hover(
  5985. function() {
  5986. VideoLayout.showDisplayName('localVideoContainer', true);
  5987. },
  5988. function() {
  5989. if (!VideoLayout.isLargeVideoVisible()
  5990. || APP.RTC.getVideoSrc(localVideo) !== APP.RTC.getVideoSrc($('#largeVideo')[0]))
  5991. VideoLayout.showDisplayName('localVideoContainer', false);
  5992. }
  5993. );
  5994. // Add stream ended handler
  5995. stream.getOriginalStream().onended = function () {
  5996. localVideoContainer.removeChild(localVideo);
  5997. VideoLayout.updateRemovedVideo(APP.RTC.getVideoSrc(localVideo));
  5998. };
  5999. // Flip video x axis if needed
  6000. flipXLocalVideo = flipX;
  6001. if (flipX) {
  6002. localVideoSelector.addClass("flipVideoX");
  6003. }
  6004. // Attach WebRTC stream
  6005. var videoStream = APP.simulcast.getLocalVideoStream();
  6006. APP.RTC.attachMediaStream(localVideoSelector, videoStream);
  6007. localVideoSrc = APP.RTC.getVideoSrc(localVideo);
  6008. var myResourceJid = APP.xmpp.myResource();
  6009. VideoLayout.updateLargeVideo(localVideoSrc, 0,
  6010. myResourceJid);
  6011. };
  6012. /**
  6013. * Checks if removed video is currently displayed and tries to display
  6014. * another one instead.
  6015. * @param removedVideoSrc src stream identifier of the video.
  6016. */
  6017. my.updateRemovedVideo = function(removedVideoSrc) {
  6018. if (removedVideoSrc === APP.RTC.getVideoSrc($('#largeVideo')[0])) {
  6019. // this is currently displayed as large
  6020. // pick the last visible video in the row
  6021. // if nobody else is left, this picks the local video
  6022. var pick
  6023. = $('#remoteVideos>span[id!="mixedstream"]:visible:last>video')
  6024. .get(0);
  6025. if (!pick) {
  6026. console.info("Last visible video no longer exists");
  6027. pick = $('#remoteVideos>span[id!="mixedstream"]>video').get(0);
  6028. if (!pick || !APP.RTC.getVideoSrc(pick)) {
  6029. // Try local video
  6030. console.info("Fallback to local video...");
  6031. pick = $('#remoteVideos>span>span>video').get(0);
  6032. }
  6033. }
  6034. // mute if localvideo
  6035. if (pick) {
  6036. var container = pick.parentNode;
  6037. var jid = null;
  6038. if(container)
  6039. {
  6040. if(container.id == "localVideoWrapper")
  6041. {
  6042. jid = APP.xmpp.myResource();
  6043. }
  6044. else
  6045. {
  6046. jid = VideoLayout.getPeerContainerResourceJid(container);
  6047. }
  6048. }
  6049. VideoLayout.updateLargeVideo(APP.RTC.getVideoSrc(pick), pick.volume, jid);
  6050. } else {
  6051. console.warn("Failed to elect large video");
  6052. }
  6053. }
  6054. };
  6055. my.onRemoteStreamAdded = function (stream) {
  6056. var container;
  6057. var remotes = document.getElementById('remoteVideos');
  6058. if (stream.peerjid) {
  6059. VideoLayout.ensurePeerContainerExists(stream.peerjid);
  6060. container = document.getElementById(
  6061. 'participant_' + Strophe.getResourceFromJid(stream.peerjid));
  6062. } else {
  6063. var id = stream.getOriginalStream().id;
  6064. if (id !== 'mixedmslabel'
  6065. // FIXME: default stream is added always with new focus
  6066. // (to be investigated)
  6067. && id !== 'default') {
  6068. console.error('can not associate stream',
  6069. id,
  6070. 'with a participant');
  6071. // We don't want to add it here since it will cause troubles
  6072. return;
  6073. }
  6074. // FIXME: for the mixed ms we dont need a video -- currently
  6075. container = document.createElement('span');
  6076. container.id = 'mixedstream';
  6077. container.className = 'videocontainer';
  6078. remotes.appendChild(container);
  6079. UIUtil.playSoundNotification('userJoined');
  6080. }
  6081. if (container) {
  6082. VideoLayout.addRemoteStreamElement( container,
  6083. stream.sid,
  6084. stream.getOriginalStream(),
  6085. stream.peerjid,
  6086. stream.ssrc);
  6087. }
  6088. }
  6089. my.getLargeVideoState = function () {
  6090. return largeVideoState;
  6091. };
  6092. /**
  6093. * Updates the large video with the given new video source.
  6094. */
  6095. my.updateLargeVideo = function(newSrc, vol, resourceJid) {
  6096. console.log('hover in', newSrc);
  6097. if (APP.RTC.getVideoSrc($('#largeVideo')[0]) !== newSrc) {
  6098. $('#activeSpeaker').css('visibility', 'hidden');
  6099. // Due to the simulcast the localVideoSrc may have changed when the
  6100. // fadeOut event triggers. In that case the getJidFromVideoSrc and
  6101. // isVideoSrcDesktop methods will not function correctly.
  6102. //
  6103. // Also, again due to the simulcast, the updateLargeVideo method can
  6104. // be called multiple times almost simultaneously. Therefore, we
  6105. // store the state here and update only once.
  6106. largeVideoState.newSrc = newSrc;
  6107. largeVideoState.isVisible = $('#largeVideo').is(':visible');
  6108. largeVideoState.isDesktop = APP.RTC.isVideoSrcDesktop(resourceJid);
  6109. if(largeVideoState.userResourceJid) {
  6110. largeVideoState.oldResourceJid = largeVideoState.userResourceJid;
  6111. } else {
  6112. largeVideoState.oldResourceJid = null;
  6113. }
  6114. largeVideoState.userResourceJid = resourceJid;
  6115. // Screen stream is already rotated
  6116. largeVideoState.flipX = (newSrc === localVideoSrc) && flipXLocalVideo;
  6117. var userChanged = false;
  6118. if (largeVideoState.oldResourceJid !== largeVideoState.userResourceJid) {
  6119. userChanged = true;
  6120. // we want the notification to trigger even if userJid is undefined,
  6121. // or null.
  6122. eventEmitter.emit(UIEvents.SELECTED_ENDPOINT,
  6123. largeVideoState.userResourceJid);
  6124. }
  6125. if (!largeVideoState.updateInProgress) {
  6126. largeVideoState.updateInProgress = true;
  6127. var doUpdate = function () {
  6128. Avatar.updateActiveSpeakerAvatarSrc(
  6129. APP.xmpp.findJidFromResource(
  6130. largeVideoState.userResourceJid));
  6131. if (!userChanged && largeVideoState.preload &&
  6132. largeVideoState.preload !== null &&
  6133. APP.RTC.getVideoSrc($(largeVideoState.preload)[0]) === newSrc)
  6134. {
  6135. console.info('Switching to preloaded video');
  6136. var attributes = $('#largeVideo').prop("attributes");
  6137. // loop through largeVideo attributes and apply them on
  6138. // preload.
  6139. $.each(attributes, function () {
  6140. if (this.name !== 'id' && this.name !== 'src') {
  6141. largeVideoState.preload.attr(this.name, this.value);
  6142. }
  6143. });
  6144. largeVideoState.preload.appendTo($('#largeVideoContainer'));
  6145. $('#largeVideo').attr('id', 'previousLargeVideo');
  6146. largeVideoState.preload.attr('id', 'largeVideo');
  6147. $('#previousLargeVideo').remove();
  6148. largeVideoState.preload.on('loadedmetadata', function (e) {
  6149. currentVideoWidth = this.videoWidth;
  6150. currentVideoHeight = this.videoHeight;
  6151. VideoLayout.positionLarge(currentVideoWidth, currentVideoHeight);
  6152. });
  6153. largeVideoState.preload = null;
  6154. largeVideoState.preload_ssrc = 0;
  6155. } else {
  6156. APP.RTC.setVideoSrc($('#largeVideo')[0], largeVideoState.newSrc);
  6157. }
  6158. var videoTransform = document.getElementById('largeVideo')
  6159. .style.webkitTransform;
  6160. if (largeVideoState.flipX && videoTransform !== 'scaleX(-1)') {
  6161. document.getElementById('largeVideo').style.webkitTransform
  6162. = "scaleX(-1)";
  6163. }
  6164. else if (!largeVideoState.flipX && videoTransform === 'scaleX(-1)') {
  6165. document.getElementById('largeVideo').style.webkitTransform
  6166. = "none";
  6167. }
  6168. // Change the way we'll be measuring and positioning large video
  6169. VideoLayout.getVideoSize = largeVideoState.isDesktop
  6170. ? getDesktopVideoSize
  6171. : getCameraVideoSize;
  6172. VideoLayout.getVideoPosition = largeVideoState.isDesktop
  6173. ? getDesktopVideoPosition
  6174. : getCameraVideoPosition;
  6175. // Only if the large video is currently visible.
  6176. // Disable previous dominant speaker video.
  6177. if (largeVideoState.oldResourceJid) {
  6178. VideoLayout.enableDominantSpeaker(
  6179. largeVideoState.oldResourceJid,
  6180. false);
  6181. }
  6182. // Enable new dominant speaker in the remote videos section.
  6183. if (largeVideoState.userResourceJid) {
  6184. VideoLayout.enableDominantSpeaker(
  6185. largeVideoState.userResourceJid,
  6186. true);
  6187. }
  6188. if (userChanged && largeVideoState.isVisible) {
  6189. // using "this" should be ok because we're called
  6190. // from within the fadeOut event.
  6191. $(this).fadeIn(300);
  6192. }
  6193. if(userChanged) {
  6194. Avatar.showUserAvatar(
  6195. APP.xmpp.findJidFromResource(
  6196. largeVideoState.oldResourceJid));
  6197. }
  6198. largeVideoState.updateInProgress = false;
  6199. };
  6200. if (userChanged) {
  6201. $('#largeVideo').fadeOut(300, doUpdate);
  6202. } else {
  6203. doUpdate();
  6204. }
  6205. }
  6206. } else {
  6207. Avatar.showUserAvatar(
  6208. APP.xmpp.findJidFromResource(
  6209. largeVideoState.userResourceJid));
  6210. }
  6211. };
  6212. my.handleVideoThumbClicked = function(videoSrc,
  6213. noPinnedEndpointChangedEvent,
  6214. resourceJid) {
  6215. // Restore style for previously focused video
  6216. var oldContainer = null;
  6217. if(focusedVideoInfo) {
  6218. var focusResourceJid = focusedVideoInfo.resourceJid;
  6219. oldContainer = getParticipantContainer(focusResourceJid);
  6220. }
  6221. if (oldContainer) {
  6222. oldContainer.removeClass("videoContainerFocused");
  6223. }
  6224. // Unlock current focused.
  6225. if (focusedVideoInfo && focusedVideoInfo.src === videoSrc)
  6226. {
  6227. focusedVideoInfo = null;
  6228. var dominantSpeakerVideo = null;
  6229. // Enable the currently set dominant speaker.
  6230. if (currentDominantSpeaker) {
  6231. dominantSpeakerVideo
  6232. = $('#participant_' + currentDominantSpeaker + '>video')
  6233. .get(0);
  6234. if (dominantSpeakerVideo) {
  6235. VideoLayout.updateLargeVideo(
  6236. APP.RTC.getVideoSrc(dominantSpeakerVideo),
  6237. 1,
  6238. currentDominantSpeaker);
  6239. }
  6240. }
  6241. if (!noPinnedEndpointChangedEvent) {
  6242. eventEmitter.emit(UIEvents.PINNED_ENDPOINT);
  6243. }
  6244. return;
  6245. }
  6246. // Lock new video
  6247. focusedVideoInfo = {
  6248. src: videoSrc,
  6249. resourceJid: resourceJid
  6250. };
  6251. // Update focused/pinned interface.
  6252. if (resourceJid)
  6253. {
  6254. var container = getParticipantContainer(resourceJid);
  6255. container.addClass("videoContainerFocused");
  6256. if (!noPinnedEndpointChangedEvent) {
  6257. eventEmitter.emit(UIEvents.PINNED_ENDPOINT, resourceJid);
  6258. }
  6259. }
  6260. if ($('#largeVideo').attr('src') === videoSrc &&
  6261. VideoLayout.isLargeVideoOnTop()) {
  6262. return;
  6263. }
  6264. // Triggers a "video.selected" event. The "false" parameter indicates
  6265. // this isn't a prezi.
  6266. $(document).trigger("video.selected", [false]);
  6267. VideoLayout.updateLargeVideo(videoSrc, 1, resourceJid);
  6268. $('audio').each(function (idx, el) {
  6269. if (el.id.indexOf('mixedmslabel') !== -1) {
  6270. el.volume = 0;
  6271. el.volume = 1;
  6272. }
  6273. });
  6274. };
  6275. /**
  6276. * Positions the large video.
  6277. *
  6278. * @param videoWidth the stream video width
  6279. * @param videoHeight the stream video height
  6280. */
  6281. my.positionLarge = function (videoWidth, videoHeight) {
  6282. var videoSpaceWidth = $('#videospace').width();
  6283. var videoSpaceHeight = window.innerHeight;
  6284. var videoSize = VideoLayout.getVideoSize(videoWidth,
  6285. videoHeight,
  6286. videoSpaceWidth,
  6287. videoSpaceHeight);
  6288. var largeVideoWidth = videoSize[0];
  6289. var largeVideoHeight = videoSize[1];
  6290. var videoPosition = VideoLayout.getVideoPosition(largeVideoWidth,
  6291. largeVideoHeight,
  6292. videoSpaceWidth,
  6293. videoSpaceHeight);
  6294. var horizontalIndent = videoPosition[0];
  6295. var verticalIndent = videoPosition[1];
  6296. positionVideo($('#largeVideo'),
  6297. largeVideoWidth,
  6298. largeVideoHeight,
  6299. horizontalIndent, verticalIndent);
  6300. };
  6301. /**
  6302. * Shows/hides the large video.
  6303. */
  6304. my.setLargeVideoVisible = function(isVisible) {
  6305. var resourceJid = largeVideoState.userResourceJid;
  6306. if (isVisible) {
  6307. $('#largeVideo').css({visibility: 'visible'});
  6308. $('.watermark').css({visibility: 'visible'});
  6309. VideoLayout.enableDominantSpeaker(resourceJid, true);
  6310. }
  6311. else {
  6312. $('#largeVideo').css({visibility: 'hidden'});
  6313. $('#activeSpeaker').css('visibility', 'hidden');
  6314. $('.watermark').css({visibility: 'hidden'});
  6315. VideoLayout.enableDominantSpeaker(resourceJid, false);
  6316. if(focusedVideoInfo) {
  6317. var focusResourceJid = focusedVideoInfo.resourceJid;
  6318. var oldContainer = getParticipantContainer(focusResourceJid);
  6319. if (oldContainer && oldContainer.length > 0) {
  6320. oldContainer.removeClass("videoContainerFocused");
  6321. }
  6322. focusedVideoInfo = null;
  6323. if(focusResourceJid) {
  6324. Avatar.showUserAvatar(
  6325. APP.xmpp.findJidFromResource(focusResourceJid));
  6326. }
  6327. }
  6328. }
  6329. };
  6330. /**
  6331. * Indicates if the large video is currently visible.
  6332. *
  6333. * @return <tt>true</tt> if visible, <tt>false</tt> - otherwise
  6334. */
  6335. my.isLargeVideoVisible = function() {
  6336. return $('#largeVideo').is(':visible');
  6337. };
  6338. my.isLargeVideoOnTop = function () {
  6339. var Etherpad = require("../etherpad/Etherpad");
  6340. var Prezi = require("../prezi/Prezi");
  6341. return !Prezi.isPresentationVisible() && !Etherpad.isVisible();
  6342. };
  6343. /**
  6344. * Checks if container for participant identified by given peerJid exists
  6345. * in the document and creates it eventually.
  6346. *
  6347. * @param peerJid peer Jid to check.
  6348. * @param userId user email or id for setting the avatar
  6349. *
  6350. * @return Returns <tt>true</tt> if the peer container exists,
  6351. * <tt>false</tt> - otherwise
  6352. */
  6353. my.ensurePeerContainerExists = function(peerJid, userId) {
  6354. ContactList.ensureAddContact(peerJid, userId);
  6355. var resourceJid = Strophe.getResourceFromJid(peerJid);
  6356. var videoSpanId = 'participant_' + resourceJid;
  6357. if (!$('#' + videoSpanId).length) {
  6358. var container =
  6359. VideoLayout.addRemoteVideoContainer(peerJid, videoSpanId, userId);
  6360. Avatar.setUserAvatar(peerJid, userId);
  6361. // Set default display name.
  6362. setDisplayName(videoSpanId);
  6363. VideoLayout.connectionIndicators[videoSpanId] =
  6364. new ConnectionIndicator(container, peerJid, VideoLayout);
  6365. var nickfield = document.createElement('span');
  6366. nickfield.className = "nick";
  6367. nickfield.appendChild(document.createTextNode(resourceJid));
  6368. container.appendChild(nickfield);
  6369. // In case this is not currently in the last n we don't show it.
  6370. if (localLastNCount
  6371. && localLastNCount > 0
  6372. && $('#remoteVideos>span').length >= localLastNCount + 2) {
  6373. showPeerContainer(resourceJid, 'hide');
  6374. }
  6375. else
  6376. VideoLayout.resizeThumbnails();
  6377. }
  6378. };
  6379. my.addRemoteVideoContainer = function(peerJid, spanId) {
  6380. var container = document.createElement('span');
  6381. container.id = spanId;
  6382. container.className = 'videocontainer';
  6383. var remotes = document.getElementById('remoteVideos');
  6384. remotes.appendChild(container);
  6385. // If the peerJid is null then this video span couldn't be directly
  6386. // associated with a participant (this could happen in the case of prezi).
  6387. if (APP.xmpp.isModerator() && peerJid !== null)
  6388. addRemoteVideoMenu(peerJid, container);
  6389. AudioLevels.updateAudioLevelCanvas(peerJid, VideoLayout);
  6390. return container;
  6391. };
  6392. /**
  6393. * Creates an audio or video stream element.
  6394. */
  6395. my.createStreamElement = function (sid, stream) {
  6396. var isVideo = stream.getVideoTracks().length > 0;
  6397. var element = isVideo
  6398. ? document.createElement('video')
  6399. : document.createElement('audio');
  6400. var id = (isVideo ? 'remoteVideo_' : 'remoteAudio_')
  6401. + sid + '_' + APP.RTC.getStreamID(stream);
  6402. element.id = id;
  6403. element.autoplay = true;
  6404. element.oncontextmenu = function () { return false; };
  6405. return element;
  6406. };
  6407. my.addRemoteStreamElement
  6408. = function (container, sid, stream, peerJid, thessrc) {
  6409. var newElementId = null;
  6410. var isVideo = stream.getVideoTracks().length > 0;
  6411. if (container) {
  6412. var streamElement = VideoLayout.createStreamElement(sid, stream);
  6413. newElementId = streamElement.id;
  6414. container.appendChild(streamElement);
  6415. var sel = $('#' + newElementId);
  6416. sel.hide();
  6417. // If the container is currently visible we attach the stream.
  6418. if (!isVideo
  6419. || (container.offsetParent !== null && isVideo)) {
  6420. var videoStream = APP.simulcast.getReceivingVideoStream(stream);
  6421. APP.RTC.attachMediaStream(sel, videoStream);
  6422. if (isVideo)
  6423. waitForRemoteVideo(sel, thessrc, stream, peerJid);
  6424. }
  6425. stream.onended = function () {
  6426. console.log('stream ended', this);
  6427. VideoLayout.removeRemoteStreamElement(
  6428. stream, isVideo, container);
  6429. // NOTE(gp) it seems that under certain circumstances, the
  6430. // onended event is not fired and thus the contact list is not
  6431. // updated.
  6432. //
  6433. // The onended event of a stream should be fired when the SSRCs
  6434. // corresponding to that stream are removed from the SDP; but
  6435. // this doesn't seem to always be the case, resulting in ghost
  6436. // contacts.
  6437. //
  6438. // In an attempt to fix the ghost contacts problem, I'm moving
  6439. // the removeContact() method call in app.js, inside the
  6440. // 'muc.left' event handler.
  6441. //if (peerJid)
  6442. // ContactList.removeContact(peerJid);
  6443. };
  6444. // Add click handler.
  6445. container.onclick = function (event) {
  6446. /*
  6447. * FIXME It turns out that videoThumb may not exist (if there is
  6448. * no actual video).
  6449. */
  6450. var videoThumb = $('#' + container.id + '>video').get(0);
  6451. if (videoThumb) {
  6452. VideoLayout.handleVideoThumbClicked(
  6453. APP.RTC.getVideoSrc(videoThumb),
  6454. false,
  6455. Strophe.getResourceFromJid(peerJid));
  6456. }
  6457. event.stopPropagation();
  6458. event.preventDefault();
  6459. return false;
  6460. };
  6461. // Add hover handler
  6462. $(container).hover(
  6463. function() {
  6464. VideoLayout.showDisplayName(container.id, true);
  6465. },
  6466. function() {
  6467. var videoSrc = null;
  6468. if ($('#' + container.id + '>video')
  6469. && $('#' + container.id + '>video').length > 0) {
  6470. videoSrc = APP.RTC.getVideoSrc($('#' + container.id + '>video').get(0));
  6471. }
  6472. // If the video has been "pinned" by the user we want to
  6473. // keep the display name on place.
  6474. if (!VideoLayout.isLargeVideoVisible()
  6475. || videoSrc !== APP.RTC.getVideoSrc($('#largeVideo')[0]))
  6476. VideoLayout.showDisplayName(container.id, false);
  6477. }
  6478. );
  6479. }
  6480. return newElementId;
  6481. };
  6482. /**
  6483. * Removes the remote stream element corresponding to the given stream and
  6484. * parent container.
  6485. *
  6486. * @param stream the stream
  6487. * @param isVideo <tt>true</tt> if given <tt>stream</tt> is a video one.
  6488. * @param container
  6489. */
  6490. my.removeRemoteStreamElement = function (stream, isVideo, container) {
  6491. if (!container)
  6492. return;
  6493. var select = null;
  6494. var removedVideoSrc = null;
  6495. if (isVideo) {
  6496. select = $('#' + container.id + '>video');
  6497. removedVideoSrc = APP.RTC.getVideoSrc(select.get(0));
  6498. }
  6499. else
  6500. select = $('#' + container.id + '>audio');
  6501. // Mark video as removed to cancel waiting loop(if video is removed
  6502. // before has started)
  6503. select.removed = true;
  6504. select.remove();
  6505. var audioCount = $('#' + container.id + '>audio').length;
  6506. var videoCount = $('#' + container.id + '>video').length;
  6507. if (!audioCount && !videoCount) {
  6508. console.log("Remove whole user", container.id);
  6509. if(VideoLayout.connectionIndicators[container.id])
  6510. VideoLayout.connectionIndicators[container.id].remove();
  6511. // Remove whole container
  6512. container.remove();
  6513. UIUtil.playSoundNotification('userLeft');
  6514. VideoLayout.resizeThumbnails();
  6515. }
  6516. if (removedVideoSrc)
  6517. VideoLayout.updateRemovedVideo(removedVideoSrc);
  6518. };
  6519. /**
  6520. * Show/hide peer container for the given resourceJid.
  6521. */
  6522. function showPeerContainer(resourceJid, state) {
  6523. var peerContainer = $('#participant_' + resourceJid);
  6524. if (!peerContainer)
  6525. return;
  6526. var isHide = state === 'hide';
  6527. var resizeThumbnails = false;
  6528. if (!isHide) {
  6529. if (!peerContainer.is(':visible')) {
  6530. resizeThumbnails = true;
  6531. peerContainer.show();
  6532. }
  6533. var jid = APP.xmpp.findJidFromResource(resourceJid);
  6534. if (state == 'show')
  6535. {
  6536. // peerContainer.css('-webkit-filter', '');
  6537. Avatar.showUserAvatar(jid, false);
  6538. }
  6539. else // if (state == 'avatar')
  6540. {
  6541. // peerContainer.css('-webkit-filter', 'grayscale(100%)');
  6542. Avatar.showUserAvatar(jid, true);
  6543. }
  6544. }
  6545. else if (peerContainer.is(':visible') && isHide)
  6546. {
  6547. resizeThumbnails = true;
  6548. peerContainer.hide();
  6549. if(VideoLayout.connectionIndicators['participant_' + resourceJid])
  6550. VideoLayout.connectionIndicators['participant_' + resourceJid].hide();
  6551. }
  6552. if (resizeThumbnails) {
  6553. VideoLayout.resizeThumbnails();
  6554. }
  6555. // We want to be able to pin a participant from the contact list, even
  6556. // if he's not in the lastN set!
  6557. // ContactList.setClickable(resourceJid, !isHide);
  6558. };
  6559. my.inputDisplayNameHandler = function (name) {
  6560. NicknameHandler.setNickname(name);
  6561. if (!$('#localDisplayName').is(":visible")) {
  6562. if (NicknameHandler.getNickname())
  6563. {
  6564. var meHTML = APP.translation.generateTranslatonHTML("me");
  6565. $('#localDisplayName').html(NicknameHandler.getNickname() + " (" + meHTML + ")");
  6566. }
  6567. else
  6568. {
  6569. var defaultHTML = APP.translation.generateTranslatonHTML(
  6570. interfaceConfig.DEFAULT_LOCAL_DISPLAY_NAME);
  6571. $('#localDisplayName')
  6572. .html(defaultHTML);
  6573. }
  6574. $('#localDisplayName').show();
  6575. }
  6576. $('#editDisplayName').hide();
  6577. };
  6578. /**
  6579. * Shows/hides the display name on the remote video.
  6580. * @param videoSpanId the identifier of the video span element
  6581. * @param isShow indicates if the display name should be shown or hidden
  6582. */
  6583. my.showDisplayName = function(videoSpanId, isShow) {
  6584. var nameSpan = $('#' + videoSpanId + '>span.displayname').get(0);
  6585. if (isShow) {
  6586. if (nameSpan && nameSpan.innerHTML && nameSpan.innerHTML.length)
  6587. nameSpan.setAttribute("style", "display:inline-block;");
  6588. }
  6589. else {
  6590. if (nameSpan)
  6591. nameSpan.setAttribute("style", "display:none;");
  6592. }
  6593. };
  6594. /**
  6595. * Shows the presence status message for the given video.
  6596. */
  6597. my.setPresenceStatus = function (videoSpanId, statusMsg) {
  6598. if (!$('#' + videoSpanId).length) {
  6599. // No container
  6600. return;
  6601. }
  6602. var statusSpan = $('#' + videoSpanId + '>span.status');
  6603. if (!statusSpan.length) {
  6604. //Add status span
  6605. statusSpan = document.createElement('span');
  6606. statusSpan.className = 'status';
  6607. statusSpan.id = videoSpanId + '_status';
  6608. $('#' + videoSpanId)[0].appendChild(statusSpan);
  6609. statusSpan = $('#' + videoSpanId + '>span.status');
  6610. }
  6611. // Display status
  6612. if (statusMsg && statusMsg.length) {
  6613. $('#' + videoSpanId + '_status').text(statusMsg);
  6614. statusSpan.get(0).setAttribute("style", "display:inline-block;");
  6615. }
  6616. else {
  6617. // Hide
  6618. statusSpan.get(0).setAttribute("style", "display:none;");
  6619. }
  6620. };
  6621. /**
  6622. * Shows a visual indicator for the moderator of the conference.
  6623. */
  6624. my.showModeratorIndicator = function () {
  6625. var isModerator = APP.xmpp.isModerator();
  6626. if (isModerator) {
  6627. var indicatorSpan = $('#localVideoContainer .focusindicator');
  6628. if (indicatorSpan.children().length === 0)
  6629. {
  6630. createModeratorIndicatorElement(indicatorSpan[0]);
  6631. //translates text in focus indicator
  6632. APP.translation.translateElement($('#localVideoContainer .focusindicator'));
  6633. }
  6634. }
  6635. var members = APP.xmpp.getMembers();
  6636. Object.keys(members).forEach(function (jid) {
  6637. if (Strophe.getResourceFromJid(jid) === 'focus') {
  6638. // Skip server side focus
  6639. return;
  6640. }
  6641. var resourceJid = Strophe.getResourceFromJid(jid);
  6642. var videoSpanId = 'participant_' + resourceJid;
  6643. var videoContainer = document.getElementById(videoSpanId);
  6644. if (!videoContainer) {
  6645. console.error("No video container for " + jid);
  6646. return;
  6647. }
  6648. var member = members[jid];
  6649. if (member.role === 'moderator') {
  6650. // Remove menu if peer is moderator
  6651. var menuSpan = $('#' + videoSpanId + '>span.remotevideomenu');
  6652. if (menuSpan.length) {
  6653. removeRemoteVideoMenu(videoSpanId);
  6654. }
  6655. // Show moderator indicator
  6656. var indicatorSpan
  6657. = $('#' + videoSpanId + ' .focusindicator');
  6658. if (!indicatorSpan || indicatorSpan.length === 0) {
  6659. indicatorSpan = document.createElement('span');
  6660. indicatorSpan.className = 'focusindicator';
  6661. videoContainer.appendChild(indicatorSpan);
  6662. createModeratorIndicatorElement(indicatorSpan);
  6663. //translates text in focus indicators
  6664. APP.translation.translateElement($('#' + videoSpanId + ' .focusindicator'));
  6665. }
  6666. } else if (isModerator) {
  6667. // We are moderator, but user is not - add menu
  6668. if ($('#remote_popupmenu_' + resourceJid).length <= 0) {
  6669. addRemoteVideoMenu(
  6670. jid,
  6671. document.getElementById('participant_' + resourceJid));
  6672. }
  6673. }
  6674. });
  6675. };
  6676. /**
  6677. * Shows video muted indicator over small videos.
  6678. */
  6679. my.showVideoIndicator = function(videoSpanId, isMuted) {
  6680. var videoMutedSpan = $('#' + videoSpanId + '>span.videoMuted');
  6681. if (isMuted === 'false') {
  6682. if (videoMutedSpan.length > 0) {
  6683. videoMutedSpan.remove();
  6684. }
  6685. }
  6686. else {
  6687. if(videoMutedSpan.length == 0) {
  6688. videoMutedSpan = document.createElement('span');
  6689. videoMutedSpan.className = 'videoMuted';
  6690. $('#' + videoSpanId)[0].appendChild(videoMutedSpan);
  6691. var mutedIndicator = document.createElement('i');
  6692. mutedIndicator.className = 'icon-camera-disabled';
  6693. UIUtil.setTooltip(mutedIndicator,
  6694. "videothumbnail.videomute",
  6695. "top");
  6696. videoMutedSpan.appendChild(mutedIndicator);
  6697. //translate texts for muted indicator
  6698. APP.translation.translateElement($('#' + videoSpanId + " > span > i"));
  6699. }
  6700. VideoLayout.updateMutePosition(videoSpanId);
  6701. }
  6702. };
  6703. my.updateMutePosition = function (videoSpanId) {
  6704. var audioMutedSpan = $('#' + videoSpanId + '>span.audioMuted');
  6705. var connectionIndicator = $('#' + videoSpanId + '>div.connectionindicator');
  6706. var videoMutedSpan = $('#' + videoSpanId + '>span.videoMuted');
  6707. if(connectionIndicator.length > 0
  6708. && connectionIndicator[0].style.display != "none") {
  6709. audioMutedSpan.css({right: "23px"});
  6710. videoMutedSpan.css({right: ((audioMutedSpan.length > 0? 23 : 0) + 30) + "px"});
  6711. }
  6712. else
  6713. {
  6714. audioMutedSpan.css({right: "0px"});
  6715. videoMutedSpan.css({right: (audioMutedSpan.length > 0? 30 : 0) + "px"});
  6716. }
  6717. }
  6718. /**
  6719. * Shows audio muted indicator over small videos.
  6720. * @param {string} isMuted
  6721. */
  6722. my.showAudioIndicator = function(videoSpanId, isMuted) {
  6723. var audioMutedSpan = $('#' + videoSpanId + '>span.audioMuted');
  6724. if (isMuted === 'false') {
  6725. if (audioMutedSpan.length > 0) {
  6726. audioMutedSpan.popover('hide');
  6727. audioMutedSpan.remove();
  6728. }
  6729. }
  6730. else {
  6731. if(audioMutedSpan.length == 0 ) {
  6732. audioMutedSpan = document.createElement('span');
  6733. audioMutedSpan.className = 'audioMuted';
  6734. UIUtil.setTooltip(audioMutedSpan,
  6735. "videothumbnail.mute",
  6736. "top");
  6737. $('#' + videoSpanId)[0].appendChild(audioMutedSpan);
  6738. APP.translation.translateElement($('#' + videoSpanId + " > span"));
  6739. var mutedIndicator = document.createElement('i');
  6740. mutedIndicator.className = 'icon-mic-disabled';
  6741. audioMutedSpan.appendChild(mutedIndicator);
  6742. }
  6743. VideoLayout.updateMutePosition(videoSpanId);
  6744. }
  6745. };
  6746. /*
  6747. * Shows or hides the audio muted indicator over the local thumbnail video.
  6748. * @param {boolean} isMuted
  6749. */
  6750. my.showLocalAudioIndicator = function(isMuted) {
  6751. VideoLayout.showAudioIndicator('localVideoContainer', isMuted.toString());
  6752. };
  6753. /**
  6754. * Resizes the large video container.
  6755. */
  6756. my.resizeLargeVideoContainer = function () {
  6757. Chat.resizeChat();
  6758. var availableHeight = window.innerHeight;
  6759. var availableWidth = UIUtil.getAvailableVideoWidth();
  6760. if (availableWidth < 0 || availableHeight < 0) return;
  6761. $('#videospace').width(availableWidth);
  6762. $('#videospace').height(availableHeight);
  6763. $('#largeVideoContainer').width(availableWidth);
  6764. $('#largeVideoContainer').height(availableHeight);
  6765. var avatarSize = interfaceConfig.ACTIVE_SPEAKER_AVATAR_SIZE;
  6766. var top = availableHeight / 2 - avatarSize / 4 * 3;
  6767. $('#activeSpeaker').css('top', top);
  6768. VideoLayout.resizeThumbnails();
  6769. };
  6770. /**
  6771. * Resizes thumbnails.
  6772. */
  6773. my.resizeThumbnails = function() {
  6774. var videoSpaceWidth = $('#remoteVideos').width();
  6775. var thumbnailSize = VideoLayout.calculateThumbnailSize(videoSpaceWidth);
  6776. var width = thumbnailSize[0];
  6777. var height = thumbnailSize[1];
  6778. // size videos so that while keeping AR and max height, we have a
  6779. // nice fit
  6780. $('#remoteVideos').height(height);
  6781. $('#remoteVideos>span').width(width);
  6782. $('#remoteVideos>span').height(height);
  6783. $('.userAvatar').css('left', (width - height) / 2);
  6784. $(document).trigger("remotevideo.resized", [width, height]);
  6785. };
  6786. /**
  6787. * Enables the dominant speaker UI.
  6788. *
  6789. * @param resourceJid the jid indicating the video element to
  6790. * activate/deactivate
  6791. * @param isEnable indicates if the dominant speaker should be enabled or
  6792. * disabled
  6793. */
  6794. my.enableDominantSpeaker = function(resourceJid, isEnable) {
  6795. var videoSpanId = null;
  6796. var videoContainerId = null;
  6797. if (resourceJid
  6798. === APP.xmpp.myResource()) {
  6799. videoSpanId = 'localVideoWrapper';
  6800. videoContainerId = 'localVideoContainer';
  6801. }
  6802. else {
  6803. videoSpanId = 'participant_' + resourceJid;
  6804. videoContainerId = videoSpanId;
  6805. }
  6806. var displayName = resourceJid;
  6807. var nameSpan = $('#' + videoContainerId + '>span.displayname');
  6808. if (nameSpan.length > 0)
  6809. displayName = nameSpan.html();
  6810. console.log("UI enable dominant speaker",
  6811. displayName,
  6812. resourceJid,
  6813. isEnable);
  6814. videoSpan = document.getElementById(videoContainerId);
  6815. if (!videoSpan) {
  6816. return;
  6817. }
  6818. var video = $('#' + videoSpanId + '>video');
  6819. if (video && video.length > 0) {
  6820. if (isEnable) {
  6821. var isLargeVideoVisible = VideoLayout.isLargeVideoOnTop();
  6822. VideoLayout.showDisplayName(videoContainerId, isLargeVideoVisible);
  6823. if (!videoSpan.classList.contains("dominantspeaker"))
  6824. videoSpan.classList.add("dominantspeaker");
  6825. }
  6826. else {
  6827. VideoLayout.showDisplayName(videoContainerId, false);
  6828. if (videoSpan.classList.contains("dominantspeaker"))
  6829. videoSpan.classList.remove("dominantspeaker");
  6830. }
  6831. Avatar.showUserAvatar(
  6832. APP.xmpp.findJidFromResource(resourceJid));
  6833. }
  6834. };
  6835. /**
  6836. * Calculates the thumbnail size.
  6837. *
  6838. * @param videoSpaceWidth the width of the video space
  6839. */
  6840. my.calculateThumbnailSize = function (videoSpaceWidth) {
  6841. // Calculate the available height, which is the inner window height minus
  6842. // 39px for the header minus 2px for the delimiter lines on the top and
  6843. // bottom of the large video, minus the 36px space inside the remoteVideos
  6844. // container used for highlighting shadow.
  6845. var availableHeight = 100;
  6846. var numvids = $('#remoteVideos>span:visible').length;
  6847. if (localLastNCount && localLastNCount > 0) {
  6848. numvids = Math.min(localLastNCount + 1, numvids);
  6849. }
  6850. // Remove the 3px borders arround videos and border around the remote
  6851. // videos area and the 4 pixels between the local video and the others
  6852. //TODO: Find out where the 4 pixels come from and remove them
  6853. var availableWinWidth = videoSpaceWidth - 2 * 3 * numvids - 70 - 4;
  6854. var availableWidth = availableWinWidth / numvids;
  6855. var aspectRatio = 16.0 / 9.0;
  6856. var maxHeight = Math.min(160, availableHeight);
  6857. availableHeight = Math.min(maxHeight, availableWidth / aspectRatio);
  6858. if (availableHeight < availableWidth / aspectRatio) {
  6859. availableWidth = Math.floor(availableHeight * aspectRatio);
  6860. }
  6861. return [availableWidth, availableHeight];
  6862. };
  6863. /**
  6864. * Updates the remote video menu.
  6865. *
  6866. * @param jid the jid indicating the video for which we're adding a menu.
  6867. * @param isMuted indicates the current mute state
  6868. */
  6869. my.updateRemoteVideoMenu = function(jid, isMuted) {
  6870. var muteMenuItem
  6871. = $('#remote_popupmenu_'
  6872. + Strophe.getResourceFromJid(jid)
  6873. + '>li>a.mutelink');
  6874. var mutedIndicator = "<i class='icon-mic-disabled'></i>";
  6875. if (muteMenuItem.length) {
  6876. var muteLink = muteMenuItem.get(0);
  6877. if (isMuted === 'true') {
  6878. muteLink.innerHTML = mutedIndicator + ' Muted';
  6879. muteLink.className = 'mutelink disabled';
  6880. }
  6881. else {
  6882. muteLink.innerHTML = mutedIndicator + ' Mute';
  6883. muteLink.className = 'mutelink';
  6884. }
  6885. }
  6886. };
  6887. /**
  6888. * Returns the current dominant speaker resource jid.
  6889. */
  6890. my.getDominantSpeakerResourceJid = function () {
  6891. return currentDominantSpeaker;
  6892. };
  6893. /**
  6894. * Returns the corresponding resource jid to the given peer container
  6895. * DOM element.
  6896. *
  6897. * @return the corresponding resource jid to the given peer container
  6898. * DOM element
  6899. */
  6900. my.getPeerContainerResourceJid = function (containerElement) {
  6901. var i = containerElement.id.indexOf('participant_');
  6902. if (i >= 0)
  6903. return containerElement.id.substring(i + 12);
  6904. };
  6905. /**
  6906. * On contact list item clicked.
  6907. */
  6908. $(ContactList).bind('contactclicked', function(event, jid) {
  6909. if (!jid) {
  6910. return;
  6911. }
  6912. var resource = Strophe.getResourceFromJid(jid);
  6913. var videoContainer = $("#participant_" + resource);
  6914. if (videoContainer.length > 0) {
  6915. var videoThumb = $('video', videoContainer).get(0);
  6916. // It is not always the case that a videoThumb exists (if there is
  6917. // no actual video).
  6918. if (videoThumb) {
  6919. if (videoThumb.src && videoThumb.src != '') {
  6920. // We have a video src, great! Let's update the large video
  6921. // now.
  6922. VideoLayout.handleVideoThumbClicked(
  6923. videoThumb.src,
  6924. false,
  6925. Strophe.getResourceFromJid(jid));
  6926. } else {
  6927. // If we don't have a video src for jid, there's absolutely
  6928. // no point in calling handleVideoThumbClicked; Quite
  6929. // simply, it won't work because it needs an src to attach
  6930. // to the large video.
  6931. //
  6932. // Instead, we trigger the pinned endpoint changed event to
  6933. // let the bridge adjust its lastN set for myjid and store
  6934. // the pinned user in the lastNPickupJid variable to be
  6935. // picked up later by the lastN changed event handler.
  6936. lastNPickupJid = jid;
  6937. eventEmitter.emit(UIEvents.PINNED_ENDPOINT,
  6938. Strophe.getResourceFromJid(jid));
  6939. }
  6940. } else if (jid == APP.xmpp.myJid()) {
  6941. $("#localVideoContainer").click();
  6942. }
  6943. }
  6944. });
  6945. /**
  6946. * On audio muted event.
  6947. */
  6948. $(document).bind('audiomuted.muc', function (event, jid, isMuted) {
  6949. /*
  6950. // FIXME: but focus can not mute in this case ? - check
  6951. if (jid === xmpp.myJid()) {
  6952. // The local mute indicator is controlled locally
  6953. return;
  6954. }*/
  6955. var videoSpanId = null;
  6956. if (jid === APP.xmpp.myJid()) {
  6957. videoSpanId = 'localVideoContainer';
  6958. } else {
  6959. VideoLayout.ensurePeerContainerExists(jid);
  6960. videoSpanId = 'participant_' + Strophe.getResourceFromJid(jid);
  6961. }
  6962. mutedAudios[jid] = isMuted;
  6963. if (APP.xmpp.isModerator()) {
  6964. VideoLayout.updateRemoteVideoMenu(jid, isMuted);
  6965. }
  6966. if (videoSpanId)
  6967. VideoLayout.showAudioIndicator(videoSpanId, isMuted);
  6968. });
  6969. /**
  6970. * On video muted event.
  6971. */
  6972. $(document).bind('videomuted.muc', function (event, jid, value) {
  6973. var isMuted = (value === "true");
  6974. if(!APP.RTC.muteRemoteVideoStream(jid, isMuted))
  6975. return;
  6976. Avatar.showUserAvatar(jid, isMuted);
  6977. var videoSpanId = null;
  6978. if (jid === APP.xmpp.myJid()) {
  6979. videoSpanId = 'localVideoContainer';
  6980. } else {
  6981. VideoLayout.ensurePeerContainerExists(jid);
  6982. videoSpanId = 'participant_' + Strophe.getResourceFromJid(jid);
  6983. }
  6984. if (videoSpanId)
  6985. VideoLayout.showVideoIndicator(videoSpanId, value);
  6986. });
  6987. /**
  6988. * Display name changed.
  6989. */
  6990. my.onDisplayNameChanged =
  6991. function (jid, displayName, status) {
  6992. if (jid === 'localVideoContainer'
  6993. || jid === APP.xmpp.myJid()) {
  6994. setDisplayName('localVideoContainer',
  6995. displayName);
  6996. } else {
  6997. VideoLayout.ensurePeerContainerExists(jid);
  6998. setDisplayName(
  6999. 'participant_' + Strophe.getResourceFromJid(jid),
  7000. displayName,
  7001. status);
  7002. }
  7003. };
  7004. /**
  7005. * On dominant speaker changed event.
  7006. */
  7007. my.onDominantSpeakerChanged = function (resourceJid) {
  7008. // We ignore local user events.
  7009. if (resourceJid
  7010. === APP.xmpp.myResource())
  7011. return;
  7012. var members = APP.xmpp.getMembers();
  7013. // Update the current dominant speaker.
  7014. if (resourceJid !== currentDominantSpeaker) {
  7015. var oldSpeakerVideoSpanId = "participant_" + currentDominantSpeaker,
  7016. newSpeakerVideoSpanId = "participant_" + resourceJid;
  7017. var currentJID = APP.xmpp.findJidFromResource(currentDominantSpeaker);
  7018. var newJID = APP.xmpp.findJidFromResource(resourceJid);
  7019. if(currentDominantSpeaker && (!members || !members[currentJID] ||
  7020. !members[currentJID].displayName)) {
  7021. setDisplayName(oldSpeakerVideoSpanId, null);
  7022. }
  7023. if(resourceJid && (!members || !members[newJID] ||
  7024. !members[newJID].displayName)) {
  7025. setDisplayName(newSpeakerVideoSpanId, null,
  7026. interfaceConfig.DEFAULT_DOMINANT_SPEAKER_DISPLAY_NAME);
  7027. }
  7028. currentDominantSpeaker = resourceJid;
  7029. } else {
  7030. return;
  7031. }
  7032. // Obtain container for new dominant speaker.
  7033. var container = document.getElementById(
  7034. 'participant_' + resourceJid);
  7035. // Local video will not have container found, but that's ok
  7036. // since we don't want to switch to local video.
  7037. if (container && !focusedVideoInfo)
  7038. {
  7039. var video = container.getElementsByTagName("video");
  7040. // Update the large video if the video source is already available,
  7041. // otherwise wait for the "videoactive.jingle" event.
  7042. if (video.length && video[0].currentTime > 0)
  7043. VideoLayout.updateLargeVideo(APP.RTC.getVideoSrc(video[0]), resourceJid);
  7044. }
  7045. };
  7046. /**
  7047. * On last N change event.
  7048. *
  7049. * @param lastNEndpoints the list of last N endpoints
  7050. * @param endpointsEnteringLastN the list currently entering last N
  7051. * endpoints
  7052. */
  7053. my.onLastNEndpointsChanged = function ( lastNEndpoints,
  7054. endpointsEnteringLastN,
  7055. stream) {
  7056. if (lastNCount !== lastNEndpoints.length)
  7057. lastNCount = lastNEndpoints.length;
  7058. lastNEndpointsCache = lastNEndpoints;
  7059. // Say A, B, C, D, E, and F are in a conference and LastN = 3.
  7060. //
  7061. // If LastN drops to, say, 2, because of adaptivity, then E should see
  7062. // thumbnails for A, B and C. A and B are in E's server side LastN set,
  7063. // so E sees them. C is only in E's local LastN set.
  7064. //
  7065. // If F starts talking and LastN = 3, then E should see thumbnails for
  7066. // F, A, B. B gets "ejected" from E's server side LastN set, but it
  7067. // enters E's local LastN ejecting C.
  7068. // Increase the local LastN set size, if necessary.
  7069. if (lastNCount > localLastNCount) {
  7070. localLastNCount = lastNCount;
  7071. }
  7072. // Update the local LastN set preserving the order in which the
  7073. // endpoints appeared in the LastN/local LastN set.
  7074. var nextLocalLastNSet = lastNEndpoints.slice(0);
  7075. for (var i = 0; i < localLastNSet.length; i++) {
  7076. if (nextLocalLastNSet.length >= localLastNCount) {
  7077. break;
  7078. }
  7079. var resourceJid = localLastNSet[i];
  7080. if (nextLocalLastNSet.indexOf(resourceJid) === -1) {
  7081. nextLocalLastNSet.push(resourceJid);
  7082. }
  7083. }
  7084. localLastNSet = nextLocalLastNSet;
  7085. var updateLargeVideo = false;
  7086. // Handle LastN/local LastN changes.
  7087. $('#remoteVideos>span').each(function( index, element ) {
  7088. var resourceJid = VideoLayout.getPeerContainerResourceJid(element);
  7089. var isReceived = true;
  7090. if (resourceJid
  7091. && lastNEndpoints.indexOf(resourceJid) < 0
  7092. && localLastNSet.indexOf(resourceJid) < 0) {
  7093. console.log("Remove from last N", resourceJid);
  7094. showPeerContainer(resourceJid, 'hide');
  7095. isReceived = false;
  7096. } else if (resourceJid
  7097. && $('#participant_' + resourceJid).is(':visible')
  7098. && lastNEndpoints.indexOf(resourceJid) < 0
  7099. && localLastNSet.indexOf(resourceJid) >= 0) {
  7100. showPeerContainer(resourceJid, 'avatar');
  7101. isReceived = false;
  7102. }
  7103. if (!isReceived) {
  7104. // resourceJid has dropped out of the server side lastN set, so
  7105. // it is no longer being received. If resourceJid was being
  7106. // displayed in the large video we have to switch to another
  7107. // user.
  7108. var largeVideoResource = largeVideoState.userResourceJid;
  7109. if (!updateLargeVideo && resourceJid === largeVideoResource) {
  7110. updateLargeVideo = true;
  7111. }
  7112. }
  7113. });
  7114. if (!endpointsEnteringLastN || endpointsEnteringLastN.length < 0)
  7115. endpointsEnteringLastN = lastNEndpoints;
  7116. if (endpointsEnteringLastN && endpointsEnteringLastN.length > 0) {
  7117. endpointsEnteringLastN.forEach(function (resourceJid) {
  7118. var isVisible = $('#participant_' + resourceJid).is(':visible');
  7119. showPeerContainer(resourceJid, 'show');
  7120. if (!isVisible) {
  7121. console.log("Add to last N", resourceJid);
  7122. var jid = APP.xmpp.findJidFromResource(resourceJid);
  7123. var mediaStream = APP.RTC.remoteStreams[jid][MediaStreamType.VIDEO_TYPE];
  7124. var sel = $('#participant_' + resourceJid + '>video');
  7125. var videoStream = APP.simulcast.getReceivingVideoStream(
  7126. mediaStream.stream);
  7127. APP.RTC.attachMediaStream(sel, videoStream);
  7128. if (lastNPickupJid == mediaStream.peerjid) {
  7129. // Clean up the lastN pickup jid.
  7130. lastNPickupJid = null;
  7131. // Don't fire the events again, they've already
  7132. // been fired in the contact list click handler.
  7133. VideoLayout.handleVideoThumbClicked(
  7134. $(sel).attr('src'),
  7135. false,
  7136. Strophe.getResourceFromJid(mediaStream.peerjid));
  7137. updateLargeVideo = false;
  7138. }
  7139. waitForRemoteVideo(sel, mediaStream.ssrc, mediaStream.stream, resourceJid);
  7140. }
  7141. })
  7142. }
  7143. // The endpoint that was being shown in the large video has dropped out
  7144. // of the lastN set and there was no lastN pickup jid. We need to update
  7145. // the large video now.
  7146. if (updateLargeVideo) {
  7147. var resource, container, src;
  7148. var myResource
  7149. = APP.xmpp.myResource();
  7150. // Find out which endpoint to show in the large video.
  7151. for (var i = 0; i < lastNEndpoints.length; i++) {
  7152. resource = lastNEndpoints[i];
  7153. if (!resource || resource === myResource)
  7154. continue;
  7155. container = $("#participant_" + resource);
  7156. if (container.length == 0)
  7157. continue;
  7158. src = $('video', container).attr('src');
  7159. if (!src)
  7160. continue;
  7161. // videoSrcToSsrc needs to be update for this call to succeed.
  7162. VideoLayout.updateLargeVideo(src);
  7163. break;
  7164. }
  7165. }
  7166. };
  7167. my.onSimulcastLayersChanging = function (endpointSimulcastLayers) {
  7168. endpointSimulcastLayers.forEach(function (esl) {
  7169. var resource = esl.endpoint;
  7170. // if lastN is enabled *and* the endpoint is *not* in the lastN set,
  7171. // then ignore the event (= do not preload anything).
  7172. //
  7173. // The bridge could probably stop sending this message if it's for
  7174. // an endpoint that's not in lastN.
  7175. if (lastNCount != -1
  7176. && (lastNCount < 1 || lastNEndpointsCache.indexOf(resource) === -1)) {
  7177. return;
  7178. }
  7179. var primarySSRC = esl.simulcastLayer.primarySSRC;
  7180. // Get session and stream from primary ssrc.
  7181. var res = APP.simulcast.getReceivingVideoStreamBySSRC(primarySSRC);
  7182. var sid = res.sid;
  7183. var electedStream = res.stream;
  7184. if (sid && electedStream) {
  7185. var msid = APP.simulcast.getRemoteVideoStreamIdBySSRC(primarySSRC);
  7186. console.info([esl, primarySSRC, msid, sid, electedStream]);
  7187. var preload = (Strophe.getResourceFromJid(APP.xmpp.getJidFromSSRC(primarySSRC)) == largeVideoState.userResourceJid);
  7188. if (preload) {
  7189. if (largeVideoState.preload)
  7190. {
  7191. $(largeVideoState.preload).remove();
  7192. }
  7193. console.info('Preloading remote video');
  7194. largeVideoState.preload = $('<video autoplay></video>');
  7195. // ssrcs are unique in an rtp session
  7196. largeVideoState.preload_ssrc = primarySSRC;
  7197. APP.RTC.attachMediaStream(largeVideoState.preload, electedStream)
  7198. }
  7199. } else {
  7200. console.error('Could not find a stream or a session.', sid, electedStream);
  7201. }
  7202. });
  7203. };
  7204. /**
  7205. * On simulcast layers changed event.
  7206. */
  7207. my.onSimulcastLayersChanged = function (endpointSimulcastLayers) {
  7208. endpointSimulcastLayers.forEach(function (esl) {
  7209. var resource = esl.endpoint;
  7210. // if lastN is enabled *and* the endpoint is *not* in the lastN set,
  7211. // then ignore the event (= do not change large video/thumbnail
  7212. // SRCs).
  7213. //
  7214. // Note that even if we ignore the "changed" event in this event
  7215. // handler, the bridge must continue sending these events because
  7216. // the simulcast code in simulcast.js uses it to know what's going
  7217. // to be streamed by the bridge when/if the endpoint gets back into
  7218. // the lastN set.
  7219. if (lastNCount != -1
  7220. && (lastNCount < 1 || lastNEndpointsCache.indexOf(resource) === -1)) {
  7221. return;
  7222. }
  7223. var primarySSRC = esl.simulcastLayer.primarySSRC;
  7224. // Get session and stream from primary ssrc.
  7225. var res = APP.simulcast.getReceivingVideoStreamBySSRC(primarySSRC);
  7226. var sid = res.sid;
  7227. var electedStream = res.stream;
  7228. if (sid && electedStream) {
  7229. var msid = APP.simulcast.getRemoteVideoStreamIdBySSRC(primarySSRC);
  7230. console.info('Switching simulcast substream.');
  7231. console.info([esl, primarySSRC, msid, sid, electedStream]);
  7232. var msidParts = msid.split(' ');
  7233. var selRemoteVideo = $(['#', 'remoteVideo_', sid, '_', msidParts[0]].join(''));
  7234. var updateLargeVideo = (Strophe.getResourceFromJid(APP.xmpp.getJidFromSSRC(primarySSRC))
  7235. == largeVideoState.userResourceJid);
  7236. var updateFocusedVideoSrc = (focusedVideoInfo && focusedVideoInfo.src && focusedVideoInfo.src != '' &&
  7237. (APP.RTC.getVideoSrc(selRemoteVideo[0]) == focusedVideoInfo.src));
  7238. var electedStreamUrl;
  7239. if (largeVideoState.preload_ssrc == primarySSRC)
  7240. {
  7241. APP.RTC.setVideoSrc(selRemoteVideo[0], APP.RTC.getVideoSrc(largeVideoState.preload[0]));
  7242. }
  7243. else
  7244. {
  7245. if (largeVideoState.preload
  7246. && largeVideoState.preload != null) {
  7247. $(largeVideoState.preload).remove();
  7248. }
  7249. largeVideoState.preload_ssrc = 0;
  7250. APP.RTC.attachMediaStream(selRemoteVideo, electedStream);
  7251. }
  7252. var jid = APP.xmpp.getJidFromSSRC(primarySSRC);
  7253. if (updateLargeVideo) {
  7254. VideoLayout.updateLargeVideo(APP.RTC.getVideoSrc(selRemoteVideo[0]), null,
  7255. Strophe.getResourceFromJid(jid));
  7256. }
  7257. if (updateFocusedVideoSrc) {
  7258. focusedVideoInfo.src = APP.RTC.getVideoSrc(selRemoteVideo[0]);
  7259. }
  7260. var videoId;
  7261. if(resource == APP.xmpp.myResource())
  7262. {
  7263. videoId = "localVideoContainer";
  7264. }
  7265. else
  7266. {
  7267. videoId = "participant_" + resource;
  7268. }
  7269. var connectionIndicator = VideoLayout.connectionIndicators[videoId];
  7270. if(connectionIndicator)
  7271. connectionIndicator.updatePopoverData();
  7272. } else {
  7273. console.error('Could not find a stream or a sid.', sid, electedStream);
  7274. }
  7275. });
  7276. };
  7277. /**
  7278. * Updates local stats
  7279. * @param percent
  7280. * @param object
  7281. */
  7282. my.updateLocalConnectionStats = function (percent, object) {
  7283. var resolution = null;
  7284. if(object.resolution !== null)
  7285. {
  7286. resolution = object.resolution;
  7287. object.resolution = resolution[APP.xmpp.myJid()];
  7288. delete resolution[APP.xmpp.myJid()];
  7289. }
  7290. updateStatsIndicator("localVideoContainer", percent, object);
  7291. for(var jid in resolution)
  7292. {
  7293. if(resolution[jid] === null)
  7294. continue;
  7295. var id = 'participant_' + Strophe.getResourceFromJid(jid);
  7296. if(VideoLayout.connectionIndicators[id])
  7297. {
  7298. VideoLayout.connectionIndicators[id].updateResolution(resolution[jid]);
  7299. }
  7300. }
  7301. };
  7302. /**
  7303. * Updates remote stats.
  7304. * @param jid the jid associated with the stats
  7305. * @param percent the connection quality percent
  7306. * @param object the stats data
  7307. */
  7308. my.updateConnectionStats = function (jid, percent, object) {
  7309. var resourceJid = Strophe.getResourceFromJid(jid);
  7310. var videoSpanId = 'participant_' + resourceJid;
  7311. updateStatsIndicator(videoSpanId, percent, object);
  7312. };
  7313. /**
  7314. * Removes the connection
  7315. * @param jid
  7316. */
  7317. my.removeConnectionIndicator = function (jid) {
  7318. if(VideoLayout.connectionIndicators['participant_' + Strophe.getResourceFromJid(jid)])
  7319. VideoLayout.connectionIndicators['participant_' + Strophe.getResourceFromJid(jid)].remove();
  7320. };
  7321. /**
  7322. * Hides the connection indicator
  7323. * @param jid
  7324. */
  7325. my.hideConnectionIndicator = function (jid) {
  7326. if(VideoLayout.connectionIndicators['participant_' + Strophe.getResourceFromJid(jid)])
  7327. VideoLayout.connectionIndicators['participant_' + Strophe.getResourceFromJid(jid)].hide();
  7328. };
  7329. /**
  7330. * Hides all the indicators
  7331. */
  7332. my.onStatsStop = function () {
  7333. for(var indicator in VideoLayout.connectionIndicators)
  7334. {
  7335. VideoLayout.connectionIndicators[indicator].hideIndicator();
  7336. }
  7337. };
  7338. my.participantLeft = function (jid) {
  7339. // Unlock large video
  7340. if (focusedVideoInfo && focusedVideoInfo.jid === jid)
  7341. {
  7342. console.info("Focused video owner has left the conference");
  7343. focusedVideoInfo = null;
  7344. }
  7345. }
  7346. return my;
  7347. }(VideoLayout || {}));
  7348. module.exports = VideoLayout;
  7349. },{"../../../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){
  7350. //var nouns = [
  7351. //];
  7352. var pluralNouns = [
  7353. "Aliens", "Animals", "Antelopes", "Ants", "Apes", "Apples", "Baboons", "Bacteria", "Badgers", "Bananas", "Bats",
  7354. "Bears", "Birds", "Bonobos", "Brides", "Bugs", "Bulls", "Butterflies", "Cheetahs",
  7355. "Cherries", "Chicken", "Children", "Chimps", "Clowns", "Cows", "Creatures", "Dinosaurs", "Dogs", "Dolphins",
  7356. "Donkeys", "Dragons", "Ducks", "Dwarfs", "Eagles", "Elephants", "Elves", "FAIL", "Fathers",
  7357. "Fish", "Flowers", "Frogs", "Fruit", "Fungi", "Galaxies", "Geese", "Goats",
  7358. "Gorillas", "Hedgehogs", "Hippos", "Horses", "Hunters", "Insects", "Kids", "Knights",
  7359. "Lemons", "Lemurs", "Leopards", "LifeForms", "Lions", "Lizards", "Mice", "Monkeys", "Monsters",
  7360. "Mushrooms", "Octopodes", "Oranges", "Orangutans", "Organisms", "Pants", "Parrots", "Penguins",
  7361. "People", "Pigeons", "Pigs", "Pineapples", "Plants", "Potatoes", "Priests", "Rats", "Reptiles", "Reptilians",
  7362. "Rhinos", "Seagulls", "Sheep", "Siblings", "Snakes", "Spaghetti", "Spiders", "Squid", "Squirrels",
  7363. "Stars", "Students", "Teachers", "Tigers", "Tomatoes", "Trees", "Vampires", "Vegetables", "Viruses", "Vulcans",
  7364. "Warewolves", "Weasels", "Whales", "Witches", "Wizards", "Wolves", "Workers", "Worms", "Zebras"
  7365. ];
  7366. //var places = [
  7367. //"Pub", "University", "Airport", "Library", "Mall", "Theater", "Stadium", "Office", "Show", "Gallows", "Beach",
  7368. // "Cemetery", "Hospital", "Reception", "Restaurant", "Bar", "Church", "House", "School", "Square", "Village",
  7369. // "Cinema", "Movies", "Party", "Restroom", "End", "Jail", "PostOffice", "Station", "Circus", "Gates", "Entrance",
  7370. // "Bridge"
  7371. //];
  7372. var verbs = [
  7373. "Abandon", "Adapt", "Advertise", "Answer", "Anticipate", "Appreciate",
  7374. "Approach", "Argue", "Ask", "Bite", "Blossom", "Blush", "Breathe", "Breed", "Bribe", "Burn", "Calculate",
  7375. "Clean", "Code", "Communicate", "Compute", "Confess", "Confiscate", "Conjugate", "Conjure", "Consume",
  7376. "Contemplate", "Crawl", "Dance", "Delegate", "Devour", "Develop", "Differ", "Discuss",
  7377. "Dissolve", "Drink", "Eat", "Elaborate", "Emancipate", "Estimate", "Expire", "Extinguish",
  7378. "Extract", "FAIL", "Facilitate", "Fall", "Feed", "Finish", "Floss", "Fly", "Follow", "Fragment", "Freeze",
  7379. "Gather", "Glow", "Grow", "Hex", "Hide", "Hug", "Hurry", "Improve", "Intersect", "Investigate", "Jinx",
  7380. "Joke", "Jubilate", "Kiss", "Laugh", "Manage", "Meet", "Merge", "Move", "Object", "Observe", "Offer",
  7381. "Paint", "Participate", "Party", "Perform", "Plan", "Pursue", "Pierce", "Play", "Postpone", "Pray", "Proclaim",
  7382. "Question", "Read", "Reckon", "Rejoice", "Represent", "Resize", "Rhyme", "Scream", "Search", "Select", "Share", "Shoot",
  7383. "Shout", "Signal", "Sing", "Skate", "Sleep", "Smile", "Smoke", "Solve", "Spell", "Steer", "Stink",
  7384. "Substitute", "Swim", "Taste", "Teach", "Terminate", "Think", "Type", "Unite", "Vanish", "Worship"
  7385. ];
  7386. var adverbs = [
  7387. "Absently", "Accurately", "Accusingly", "Adorably", "AllTheTime", "Alone", "Always", "Amazingly", "Angrily",
  7388. "Anxiously", "Anywhere", "Appallingly", "Apparently", "Articulately", "Astonishingly", "Badly", "Barely",
  7389. "Beautifully", "Blindly", "Bravely", "Brightly", "Briskly", "Brutally", "Calmly", "Carefully", "Casually",
  7390. "Cautiously", "Cleverly", "Constantly", "Correctly", "Crazily", "Curiously", "Cynically", "Daily",
  7391. "Dangerously", "Deliberately", "Delicately", "Desperately", "Discreetly", "Eagerly", "Easily", "Euphoricly",
  7392. "Evenly", "Everywhere", "Exactly", "Expectantly", "Extensively", "FAIL", "Ferociously", "Fiercely", "Finely",
  7393. "Flatly", "Frequently", "Frighteningly", "Gently", "Gloriously", "Grimly", "Guiltily", "Happily",
  7394. "Hard", "Hastily", "Heroically", "High", "Highly", "Hourly", "Humbly", "Hysterically", "Immensely",
  7395. "Impartially", "Impolitely", "Indifferently", "Intensely", "Jealously", "Jovially", "Kindly", "Lazily",
  7396. "Lightly", "Loudly", "Lovingly", "Loyally", "Magnificently", "Malevolently", "Merrily", "Mightily", "Miserably",
  7397. "Mysteriously", "NOT", "Nervously", "Nicely", "Nowhere", "Objectively", "Obnoxiously", "Obsessively",
  7398. "Obviously", "Often", "Painfully", "Patiently", "Playfully", "Politely", "Poorly", "Precisely", "Promptly",
  7399. "Quickly", "Quietly", "Randomly", "Rapidly", "Rarely", "Recklessly", "Regularly", "Remorsefully", "Responsibly",
  7400. "Rudely", "Ruthlessly", "Sadly", "Scornfully", "Seamlessly", "Seldom", "Selfishly", "Seriously", "Shakily",
  7401. "Sharply", "Sideways", "Silently", "Sleepily", "Slightly", "Slowly", "Slyly", "Smoothly", "Softly", "Solemnly", "Steadily", "Sternly", "Strangely", "Strongly", "Stunningly", "Surely", "Tenderly", "Thoughtfully",
  7402. "Tightly", "Uneasily", "Vanishingly", "Violently", "Warmly", "Weakly", "Wearily", "Weekly", "Weirdly", "Well",
  7403. "Well", "Wickedly", "Wildly", "Wisely", "Wonderfully", "Yearly"
  7404. ];
  7405. var adjectives = [
  7406. "Abominable", "Accurate", "Adorable", "All", "Alleged", "Ancient", "Angry", "Angry", "Anxious", "Appalling",
  7407. "Apparent", "Astonishing", "Attractive", "Awesome", "Baby", "Bad", "Beautiful", "Benign", "Big", "Bitter",
  7408. "Blind", "Blue", "Bold", "Brave", "Bright", "Brisk", "Calm", "Camouflaged", "Casual", "Cautious",
  7409. "Choppy", "Chosen", "Clever", "Cold", "Cool", "Crawly", "Crazy", "Creepy", "Cruel", "Curious", "Cynical",
  7410. "Dangerous", "Dark", "Delicate", "Desperate", "Difficult", "Discreet", "Disguised", "Dizzy",
  7411. "Dumb", "Eager", "Easy", "Edgy", "Electric", "Elegant", "Emancipated", "Enormous", "Euphoric", "Evil",
  7412. "FAIL", "Fast", "Ferocious", "Fierce", "Fine", "Flawed", "Flying", "Foolish", "Foxy",
  7413. "Freezing", "Funny", "Furious", "Gentle", "Glorious", "Golden", "Good", "Green", "Green", "Guilty",
  7414. "Hairy", "Happy", "Hard", "Hasty", "Hazy", "Heroic", "Hostile", "Hot", "Humble", "Humongous",
  7415. "Humorous", "Hysterical", "Idealistic", "Ignorant", "Immense", "Impartial", "Impolite", "Indifferent",
  7416. "Infuriated", "Insightful", "Intense", "Interesting", "Intimidated", "Intriguing", "Jealous", "Jolly", "Jovial",
  7417. "Jumpy", "Kind", "Laughing", "Lazy", "Liquid", "Lonely", "Longing", "Loud", "Loving", "Loyal", "Macabre", "Mad",
  7418. "Magical", "Magnificent", "Malevolent", "Medieval", "Memorable", "Mere", "Merry", "Mighty",
  7419. "Mischievous", "Miserable", "Modified", "Moody", "Most", "Mysterious", "Mystical", "Needy",
  7420. "Nervous", "Nice", "Objective", "Obnoxious", "Obsessive", "Obvious", "Opinionated", "Orange",
  7421. "Painful", "Passionate", "Perfect", "Pink", "Playful", "Poisonous", "Polite", "Poor", "Popular", "Powerful",
  7422. "Precise", "Preserved", "Pretty", "Purple", "Quick", "Quiet", "Random", "Rapid", "Rare", "Real",
  7423. "Reassuring", "Reckless", "Red", "Regular", "Remorseful", "Responsible", "Rich", "Rude", "Ruthless",
  7424. "Sad", "Scared", "Scary", "Scornful", "Screaming", "Selfish", "Serious", "Shady", "Shaky", "Sharp",
  7425. "Shiny", "Shy", "Simple", "Sleepy", "Slow", "Sly", "Small", "Smart", "Smelly", "Smiling", "Smooth",
  7426. "Smug", "Sober", "Soft", "Solemn", "Square", "Square", "Steady", "Strange", "Strong",
  7427. "Stunning", "Subjective", "Successful", "Surly", "Sweet", "Tactful", "Tense",
  7428. "Thoughtful", "Tight", "Tiny", "Tolerant", "Uneasy", "Unique", "Unseen", "Warm", "Weak",
  7429. "Weird", "WellCooked", "Wild", "Wise", "Witty", "Wonderful", "Worried", "Yellow", "Young",
  7430. "Zealous"
  7431. ];
  7432. //var pronouns = [
  7433. //];
  7434. //var conjunctions = [
  7435. //"And", "Or", "For", "Above", "Before", "Against", "Between"
  7436. //];
  7437. /*
  7438. * Maps a string (category name) to the array of words from that category.
  7439. */
  7440. var CATEGORIES =
  7441. {
  7442. //"_NOUN_": nouns,
  7443. "_PLURALNOUN_": pluralNouns,
  7444. //"_PLACE_": places,
  7445. "_VERB_": verbs,
  7446. "_ADVERB_": adverbs,
  7447. "_ADJECTIVE_": adjectives
  7448. //"_PRONOUN_": pronouns,
  7449. //"_CONJUNCTION_": conjunctions,
  7450. };
  7451. var PATTERNS = [
  7452. "_ADJECTIVE__PLURALNOUN__VERB__ADVERB_"
  7453. // BeautifulFungiOrSpaghetti
  7454. //"_ADJECTIVE__PLURALNOUN__CONJUNCTION__PLURALNOUN_",
  7455. // AmazinglyScaryToy
  7456. //"_ADVERB__ADJECTIVE__NOUN_",
  7457. // NeitherTrashNorRifle
  7458. //"Neither_NOUN_Nor_NOUN_",
  7459. //"Either_NOUN_Or_NOUN_",
  7460. // EitherCopulateOrInvestigate
  7461. //"Either_VERB_Or_VERB_",
  7462. //"Neither_VERB_Nor_VERB_",
  7463. //"The_ADJECTIVE__ADJECTIVE__NOUN_",
  7464. //"The_ADVERB__ADJECTIVE__NOUN_",
  7465. //"The_ADVERB__ADJECTIVE__NOUN_s",
  7466. //"The_ADVERB__ADJECTIVE__PLURALNOUN__VERB_",
  7467. // WolvesComputeBadly
  7468. //"_PLURALNOUN__VERB__ADVERB_",
  7469. // UniteFacilitateAndMerge
  7470. //"_VERB__VERB_And_VERB_",
  7471. //NastyWitchesAtThePub
  7472. //"_ADJECTIVE__PLURALNOUN_AtThe_PLACE_",
  7473. ];
  7474. /*
  7475. * Returns a random element from the array 'arr'
  7476. */
  7477. function randomElement(arr)
  7478. {
  7479. return arr[Math.floor(Math.random() * arr.length)];
  7480. }
  7481. /*
  7482. * Returns true if the string 's' contains one of the
  7483. * template strings.
  7484. */
  7485. function hasTemplate(s)
  7486. {
  7487. for (var template in CATEGORIES){
  7488. if (s.indexOf(template) >= 0){
  7489. return true;
  7490. }
  7491. }
  7492. }
  7493. /**
  7494. * Generates new room name.
  7495. */
  7496. var RoomNameGenerator = {
  7497. generateRoomWithoutSeparator: function()
  7498. {
  7499. // Note that if more than one pattern is available, the choice of 'name' won't be random (names from patterns
  7500. // with fewer options will have higher probability of being chosen that names from patterns with more options).
  7501. var name = randomElement(PATTERNS);
  7502. var word;
  7503. while (hasTemplate(name)){
  7504. for (var template in CATEGORIES){
  7505. word = randomElement(CATEGORIES[template]);
  7506. name = name.replace(template, word);
  7507. }
  7508. }
  7509. return name;
  7510. }
  7511. }
  7512. module.exports = RoomNameGenerator;
  7513. },{}],33:[function(require,module,exports){
  7514. var animateTimeout, updateTimeout;
  7515. var RoomNameGenerator = require("./RoomnameGenerator");
  7516. function enter_room()
  7517. {
  7518. var val = $("#enter_room_field").val();
  7519. if(!val) {
  7520. val = $("#enter_room_field").attr("room_name");
  7521. }
  7522. if (val) {
  7523. window.location.pathname = "/" + val;
  7524. }
  7525. }
  7526. function animate(word) {
  7527. var currentVal = $("#enter_room_field").attr("placeholder");
  7528. $("#enter_room_field").attr("placeholder", currentVal + word.substr(0, 1));
  7529. animateTimeout = setTimeout(function() {
  7530. animate(word.substring(1, word.length))
  7531. }, 70);
  7532. }
  7533. function update_roomname()
  7534. {
  7535. var word = RoomNameGenerator.generateRoomWithoutSeparator();
  7536. $("#enter_room_field").attr("room_name", word);
  7537. $("#enter_room_field").attr("placeholder", "");
  7538. clearTimeout(animateTimeout);
  7539. animate(word);
  7540. updateTimeout = setTimeout(update_roomname, 10000);
  7541. }
  7542. function setupWelcomePage()
  7543. {
  7544. $("#videoconference_page").hide();
  7545. $("#domain_name").text(
  7546. window.location.protocol + "//" + window.location.host + "/");
  7547. if (interfaceConfig.SHOW_JITSI_WATERMARK) {
  7548. var leftWatermarkDiv
  7549. = $("#welcome_page_header div[class='watermark leftwatermark']");
  7550. if(leftWatermarkDiv && leftWatermarkDiv.length > 0)
  7551. {
  7552. leftWatermarkDiv.css({display: 'block'});
  7553. leftWatermarkDiv.parent().get(0).href
  7554. = interfaceConfig.JITSI_WATERMARK_LINK;
  7555. }
  7556. }
  7557. if (interfaceConfig.SHOW_BRAND_WATERMARK) {
  7558. var rightWatermarkDiv
  7559. = $("#welcome_page_header div[class='watermark rightwatermark']");
  7560. if(rightWatermarkDiv && rightWatermarkDiv.length > 0) {
  7561. rightWatermarkDiv.css({display: 'block'});
  7562. rightWatermarkDiv.parent().get(0).href
  7563. = interfaceConfig.BRAND_WATERMARK_LINK;
  7564. rightWatermarkDiv.get(0).style.backgroundImage
  7565. = "url(images/rightwatermark.png)";
  7566. }
  7567. }
  7568. if (interfaceConfig.SHOW_POWERED_BY) {
  7569. $("#welcome_page_header>a[class='poweredby']")
  7570. .css({display: 'block'});
  7571. }
  7572. $("#enter_room_button").click(function()
  7573. {
  7574. enter_room();
  7575. });
  7576. $("#enter_room_field").keydown(function (event) {
  7577. if (event.keyCode === 13 /* enter */) {
  7578. enter_room();
  7579. }
  7580. });
  7581. if (!(interfaceConfig.GENERATE_ROOMNAMES_ON_WELCOME_PAGE === false)){
  7582. var updateTimeout;
  7583. var animateTimeout;
  7584. $("#reload_roomname").click(function () {
  7585. clearTimeout(updateTimeout);
  7586. clearTimeout(animateTimeout);
  7587. update_roomname();
  7588. });
  7589. $("#reload_roomname").show();
  7590. update_roomname();
  7591. }
  7592. $("#disable_welcome").click(function () {
  7593. window.localStorage.welcomePageDisabled
  7594. = $("#disable_welcome").is(":checked");
  7595. });
  7596. }
  7597. module.exports = setupWelcomePage;
  7598. },{"./RoomnameGenerator":32}],34:[function(require,module,exports){
  7599. var EventEmitter = require("events");
  7600. var eventEmitter = new EventEmitter();
  7601. var CQEvents = require("../../service/connectionquality/CQEvents");
  7602. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  7603. /**
  7604. * local stats
  7605. * @type {{}}
  7606. */
  7607. var stats = {};
  7608. /**
  7609. * remote stats
  7610. * @type {{}}
  7611. */
  7612. var remoteStats = {};
  7613. /**
  7614. * Interval for sending statistics to other participants
  7615. * @type {null}
  7616. */
  7617. var sendIntervalId = null;
  7618. /**
  7619. * Start statistics sending.
  7620. */
  7621. function startSendingStats() {
  7622. sendStats();
  7623. sendIntervalId = setInterval(sendStats, 10000);
  7624. }
  7625. /**
  7626. * Sends statistics to other participants
  7627. */
  7628. function sendStats() {
  7629. APP.xmpp.addToPresence("connectionQuality", convertToMUCStats(stats));
  7630. }
  7631. /**
  7632. * Converts statistics to format for sending through XMPP
  7633. * @param stats the statistics
  7634. * @returns {{bitrate_donwload: *, bitrate_uplpoad: *, packetLoss_total: *, packetLoss_download: *, packetLoss_upload: *}}
  7635. */
  7636. function convertToMUCStats(stats) {
  7637. return {
  7638. "bitrate_download": stats.bitrate.download,
  7639. "bitrate_upload": stats.bitrate.upload,
  7640. "packetLoss_total": stats.packetLoss.total,
  7641. "packetLoss_download": stats.packetLoss.download,
  7642. "packetLoss_upload": stats.packetLoss.upload
  7643. };
  7644. }
  7645. /**
  7646. * Converts statitistics to format used by VideoLayout
  7647. * @param stats
  7648. * @returns {{bitrate: {download: *, upload: *}, packetLoss: {total: *, download: *, upload: *}}}
  7649. */
  7650. function parseMUCStats(stats) {
  7651. return {
  7652. bitrate: {
  7653. download: stats.bitrate_download,
  7654. upload: stats.bitrate_upload
  7655. },
  7656. packetLoss: {
  7657. total: stats.packetLoss_total,
  7658. download: stats.packetLoss_download,
  7659. upload: stats.packetLoss_upload
  7660. }
  7661. };
  7662. }
  7663. var ConnectionQuality = {
  7664. init: function () {
  7665. APP.xmpp.addListener(XMPPEvents.REMOTE_STATS, this.updateRemoteStats);
  7666. APP.statistics.addConnectionStatsListener(this.updateLocalStats);
  7667. APP.statistics.addRemoteStatsStopListener(this.stopSendingStats);
  7668. },
  7669. /**
  7670. * Updates the local statistics
  7671. * @param data new statistics
  7672. */
  7673. updateLocalStats: function (data) {
  7674. stats = data;
  7675. eventEmitter.emit(CQEvents.LOCALSTATS_UPDATED, 100 - stats.packetLoss.total, stats);
  7676. if (sendIntervalId == null) {
  7677. startSendingStats();
  7678. }
  7679. },
  7680. /**
  7681. * Updates remote statistics
  7682. * @param jid the jid associated with the statistics
  7683. * @param data the statistics
  7684. */
  7685. updateRemoteStats: function (jid, data) {
  7686. if (data == null || data.packetLoss_total == null) {
  7687. eventEmitter.emit(CQEvents.REMOTESTATS_UPDATED, jid, null, null);
  7688. return;
  7689. }
  7690. remoteStats[jid] = parseMUCStats(data);
  7691. eventEmitter.emit(CQEvents.REMOTESTATS_UPDATED,
  7692. jid, 100 - data.packetLoss_total, remoteStats[jid]);
  7693. },
  7694. /**
  7695. * Stops statistics sending.
  7696. */
  7697. stopSendingStats: function () {
  7698. clearInterval(sendIntervalId);
  7699. sendIntervalId = null;
  7700. //notify UI about stopping statistics gathering
  7701. eventEmitter.emit(CQEvents.STOP);
  7702. },
  7703. /**
  7704. * Returns the local statistics.
  7705. */
  7706. getStats: function () {
  7707. return stats;
  7708. },
  7709. addListener: function (type, listener) {
  7710. eventEmitter.on(type, listener);
  7711. }
  7712. };
  7713. module.exports = ConnectionQuality;
  7714. },{"../../service/connectionquality/CQEvents":93,"../../service/xmpp/XMPPEvents":96,"events":97}],35:[function(require,module,exports){
  7715. /* global $, alert, changeLocalVideo, chrome, config, getConferenceHandler, getUserMediaWithConstraints */
  7716. /**
  7717. * Indicates that desktop stream is currently in use(for toggle purpose).
  7718. * @type {boolean}
  7719. */
  7720. var isUsingScreenStream = false;
  7721. /**
  7722. * Indicates that switch stream operation is in progress and prevent from triggering new events.
  7723. * @type {boolean}
  7724. */
  7725. var switchInProgress = false;
  7726. /**
  7727. * Method used to get screen sharing stream.
  7728. *
  7729. * @type {function (stream_callback, failure_callback}
  7730. */
  7731. var obtainDesktopStream = null;
  7732. /**
  7733. * Flag used to cache desktop sharing enabled state. Do not use directly as it can be <tt>null</tt>.
  7734. * @type {null|boolean}
  7735. */
  7736. var _desktopSharingEnabled = null;
  7737. var EventEmitter = require("events");
  7738. var eventEmitter = new EventEmitter();
  7739. var DesktopSharingEventTypes = require("../../service/desktopsharing/DesktopSharingEventTypes");
  7740. /**
  7741. * Method obtains desktop stream from WebRTC 'screen' source.
  7742. * Flag 'chrome://flags/#enable-usermedia-screen-capture' must be enabled.
  7743. */
  7744. function obtainWebRTCScreen(streamCallback, failCallback) {
  7745. APP.RTC.getUserMediaWithConstraints(
  7746. ['screen'],
  7747. streamCallback,
  7748. failCallback
  7749. );
  7750. }
  7751. /**
  7752. * Constructs inline install URL for Chrome desktop streaming extension.
  7753. * The 'chromeExtensionId' must be defined in config.js.
  7754. * @returns {string}
  7755. */
  7756. function getWebStoreInstallUrl()
  7757. {
  7758. return "https://chrome.google.com/webstore/detail/" + config.chromeExtensionId;
  7759. }
  7760. /**
  7761. * Checks whether extension update is required.
  7762. * @param minVersion minimal required version
  7763. * @param extVersion current extension version
  7764. * @returns {boolean}
  7765. */
  7766. function isUpdateRequired(minVersion, extVersion)
  7767. {
  7768. try
  7769. {
  7770. var s1 = minVersion.split('.');
  7771. var s2 = extVersion.split('.');
  7772. var len = Math.max(s1.length, s2.length);
  7773. for (var i = 0; i < len; i++)
  7774. {
  7775. var n1 = 0,
  7776. n2 = 0;
  7777. if (i < s1.length)
  7778. n1 = parseInt(s1[i]);
  7779. if (i < s2.length)
  7780. n2 = parseInt(s2[i]);
  7781. if (isNaN(n1) || isNaN(n2))
  7782. {
  7783. return true;
  7784. }
  7785. else if (n1 !== n2)
  7786. {
  7787. return n1 > n2;
  7788. }
  7789. }
  7790. // will happen if boths version has identical numbers in
  7791. // their components (even if one of them is longer, has more components)
  7792. return false;
  7793. }
  7794. catch (e)
  7795. {
  7796. console.error("Failed to parse extension version", e);
  7797. APP.UI.messageHandler.showError("dialog.error",
  7798. "dialog.detectext");
  7799. return true;
  7800. }
  7801. }
  7802. function checkExtInstalled(isInstalledCallback) {
  7803. if (!chrome.runtime) {
  7804. // No API, so no extension for sure
  7805. isInstalledCallback(false);
  7806. return;
  7807. }
  7808. chrome.runtime.sendMessage(
  7809. config.chromeExtensionId,
  7810. { getVersion: true },
  7811. function (response) {
  7812. if (!response || !response.version) {
  7813. // Communication failure - assume that no endpoint exists
  7814. console.warn("Extension not installed?: " + chrome.runtime.lastError);
  7815. isInstalledCallback(false);
  7816. } else {
  7817. // Check installed extension version
  7818. var extVersion = response.version;
  7819. console.log('Extension version is: ' + extVersion);
  7820. var updateRequired = isUpdateRequired(config.minChromeExtVersion, extVersion);
  7821. if (updateRequired) {
  7822. alert(
  7823. 'Jitsi Desktop Streamer requires update. ' +
  7824. 'Changes will take effect after next Chrome restart.');
  7825. }
  7826. isInstalledCallback(!updateRequired);
  7827. }
  7828. }
  7829. );
  7830. }
  7831. function doGetStreamFromExtension(streamCallback, failCallback) {
  7832. // Sends 'getStream' msg to the extension. Extension id must be defined in the config.
  7833. chrome.runtime.sendMessage(
  7834. config.chromeExtensionId,
  7835. { getStream: true, sources: config.desktopSharingSources },
  7836. function (response) {
  7837. if (!response) {
  7838. failCallback(chrome.runtime.lastError);
  7839. return;
  7840. }
  7841. console.log("Response from extension: " + response);
  7842. if (response.streamId) {
  7843. APP.RTC.getUserMediaWithConstraints(
  7844. ['desktop'],
  7845. function (stream) {
  7846. streamCallback(stream);
  7847. },
  7848. failCallback,
  7849. null, null, null,
  7850. response.streamId);
  7851. } else {
  7852. failCallback("Extension failed to get the stream");
  7853. }
  7854. }
  7855. );
  7856. }
  7857. /**
  7858. * Asks Chrome extension to call chooseDesktopMedia and gets chrome 'desktop' stream for returned stream token.
  7859. */
  7860. function obtainScreenFromExtension(streamCallback, failCallback) {
  7861. checkExtInstalled(
  7862. function (isInstalled) {
  7863. if (isInstalled) {
  7864. doGetStreamFromExtension(streamCallback, failCallback);
  7865. } else {
  7866. chrome.webstore.install(
  7867. getWebStoreInstallUrl(),
  7868. function (arg) {
  7869. console.log("Extension installed successfully", arg);
  7870. // We need to reload the page in order to get the access to chrome.runtime
  7871. window.location.reload(false);
  7872. },
  7873. function (arg) {
  7874. console.log("Failed to install the extension", arg);
  7875. failCallback(arg);
  7876. APP.UI.messageHandler.showError("dialog.error",
  7877. "dialog.failtoinstall");
  7878. }
  7879. );
  7880. }
  7881. }
  7882. );
  7883. }
  7884. /**
  7885. * Call this method to toggle desktop sharing feature.
  7886. * @param method pass "ext" to use chrome extension for desktop capture(chrome extension required),
  7887. * pass "webrtc" to use WebRTC "screen" desktop source('chrome://flags/#enable-usermedia-screen-capture'
  7888. * must be enabled), pass any other string or nothing in order to disable this feature completely.
  7889. */
  7890. function setDesktopSharing(method) {
  7891. // Check if we are running chrome
  7892. if (!navigator.webkitGetUserMedia) {
  7893. obtainDesktopStream = null;
  7894. console.info("Desktop sharing disabled");
  7895. } else if (method == "ext") {
  7896. obtainDesktopStream = obtainScreenFromExtension;
  7897. console.info("Using Chrome extension for desktop sharing");
  7898. } else if (method == "webrtc") {
  7899. obtainDesktopStream = obtainWebRTCScreen;
  7900. console.info("Using Chrome WebRTC for desktop sharing");
  7901. }
  7902. // Reset enabled cache
  7903. _desktopSharingEnabled = null;
  7904. }
  7905. /**
  7906. * Initializes <link rel=chrome-webstore-item /> with extension id set in config.js to support inline installs.
  7907. * Host site must be selected as main website of published extension.
  7908. */
  7909. function initInlineInstalls()
  7910. {
  7911. $("link[rel=chrome-webstore-item]").attr("href", getWebStoreInstallUrl());
  7912. }
  7913. function getSwitchStreamFailed(error) {
  7914. console.error("Failed to obtain the stream to switch to", error);
  7915. switchInProgress = false;
  7916. }
  7917. function streamSwitchDone() {
  7918. switchInProgress = false;
  7919. eventEmitter.emit(
  7920. DesktopSharingEventTypes.SWITCHING_DONE,
  7921. isUsingScreenStream);
  7922. }
  7923. function newStreamCreated(stream)
  7924. {
  7925. eventEmitter.emit(DesktopSharingEventTypes.NEW_STREAM_CREATED,
  7926. stream, isUsingScreenStream, streamSwitchDone);
  7927. }
  7928. module.exports = {
  7929. isUsingScreenStream: function () {
  7930. return isUsingScreenStream;
  7931. },
  7932. /**
  7933. * @returns {boolean} <tt>true</tt> if desktop sharing feature is available and enabled.
  7934. */
  7935. isDesktopSharingEnabled: function () {
  7936. if (_desktopSharingEnabled === null) {
  7937. if (obtainDesktopStream === obtainScreenFromExtension) {
  7938. // Parse chrome version
  7939. var userAgent = navigator.userAgent.toLowerCase();
  7940. // We can assume that user agent is chrome, because it's enforced when 'ext' streaming method is set
  7941. var ver = parseInt(userAgent.match(/chrome\/(\d+)\./)[1], 10);
  7942. console.log("Chrome version" + userAgent, ver);
  7943. _desktopSharingEnabled = ver >= 34;
  7944. } else {
  7945. _desktopSharingEnabled = obtainDesktopStream === obtainWebRTCScreen;
  7946. }
  7947. }
  7948. return _desktopSharingEnabled;
  7949. },
  7950. init: function () {
  7951. setDesktopSharing(config.desktopSharing);
  7952. // Initialize Chrome extension inline installs
  7953. if (config.chromeExtensionId) {
  7954. initInlineInstalls();
  7955. }
  7956. eventEmitter.emit(DesktopSharingEventTypes.INIT);
  7957. },
  7958. addListener: function(listener, type)
  7959. {
  7960. eventEmitter.on(type, listener);
  7961. },
  7962. removeListener: function (listener,type) {
  7963. eventEmitter.removeListener(type, listener);
  7964. },
  7965. /*
  7966. * Toggles screen sharing.
  7967. */
  7968. toggleScreenSharing: function () {
  7969. if (switchInProgress || !obtainDesktopStream) {
  7970. console.warn("Switch in progress or no method defined");
  7971. return;
  7972. }
  7973. switchInProgress = true;
  7974. if (!isUsingScreenStream)
  7975. {
  7976. // Switch to desktop stream
  7977. obtainDesktopStream(
  7978. function (stream) {
  7979. // We now use screen stream
  7980. isUsingScreenStream = true;
  7981. // Hook 'ended' event to restore camera when screen stream stops
  7982. stream.addEventListener('ended',
  7983. function (e) {
  7984. if (!switchInProgress && isUsingScreenStream) {
  7985. toggleScreenSharing();
  7986. }
  7987. }
  7988. );
  7989. newStreamCreated(stream);
  7990. },
  7991. getSwitchStreamFailed);
  7992. } else {
  7993. // Disable screen stream
  7994. APP.RTC.getUserMediaWithConstraints(
  7995. ['video'],
  7996. function (stream) {
  7997. // We are now using camera stream
  7998. isUsingScreenStream = false;
  7999. newStreamCreated(stream);
  8000. },
  8001. getSwitchStreamFailed, config.resolution || '360'
  8002. );
  8003. }
  8004. }
  8005. };
  8006. },{"../../service/desktopsharing/DesktopSharingEventTypes":94,"events":97}],36:[function(require,module,exports){
  8007. //maps keycode to character, id of popover for given function and function
  8008. var shortcuts = {
  8009. 67: {
  8010. character: "C",
  8011. id: "toggleChatPopover",
  8012. function: APP.UI.toggleChat
  8013. },
  8014. 70: {
  8015. character: "F",
  8016. id: "filmstripPopover",
  8017. function: APP.UI.toggleFilmStrip
  8018. },
  8019. 77: {
  8020. character: "M",
  8021. id: "mutePopover",
  8022. function: APP.UI.toggleAudio
  8023. },
  8024. 84: {
  8025. character: "T",
  8026. function: function() {
  8027. if(!APP.RTC.localAudio.isMuted()) {
  8028. APP.UI.toggleAudio();
  8029. }
  8030. }
  8031. },
  8032. 86: {
  8033. character: "V",
  8034. id: "toggleVideoPopover",
  8035. function: APP.UI.toggleVideo
  8036. }
  8037. };
  8038. var KeyboardShortcut = {
  8039. init: function () {
  8040. window.onkeyup = function(e) {
  8041. var keycode = e.which;
  8042. if(!($(":focus").is("input[type=text]") ||
  8043. $(":focus").is("input[type=password]") ||
  8044. $(":focus").is("textarea"))) {
  8045. if (typeof shortcuts[keycode] === "object") {
  8046. shortcuts[keycode].function();
  8047. }
  8048. else if (keycode >= "0".charCodeAt(0) &&
  8049. keycode <= "9".charCodeAt(0)) {
  8050. APP.UI.clickOnVideo(keycode - "0".charCodeAt(0) + 1);
  8051. }
  8052. //esc while the smileys are visible hides them
  8053. } else if (keycode === 27 && $('#smileysContainer').is(':visible')) {
  8054. APP.UI.toggleSmileys();
  8055. }
  8056. };
  8057. window.onkeydown = function(e) {
  8058. if(!($(":focus").is("input[type=text]") ||
  8059. $(":focus").is("input[type=password]") ||
  8060. $(":focus").is("textarea"))) {
  8061. if(e.which === "T".charCodeAt(0)) {
  8062. if(APP.RTC.localAudio.isMuted()) {
  8063. APP.UI.toggleAudio();
  8064. }
  8065. }
  8066. }
  8067. };
  8068. var self = this;
  8069. $('body').popover({ selector: '[data-toggle=popover]',
  8070. trigger: 'click hover',
  8071. content: function() {
  8072. return this.getAttribute("content") +
  8073. self.getShortcut(this.getAttribute("shortcut"));
  8074. }
  8075. });
  8076. },
  8077. /**
  8078. *
  8079. * @param id indicates the popover associated with the shortcut
  8080. * @returns {string} the keyboard shortcut used for the id given
  8081. */
  8082. getShortcut: function (id) {
  8083. for (var keycode in shortcuts) {
  8084. if (shortcuts.hasOwnProperty(keycode)) {
  8085. if (shortcuts[keycode].id === id) {
  8086. return " (" + shortcuts[keycode].character + ")";
  8087. }
  8088. }
  8089. }
  8090. return "";
  8091. }
  8092. };
  8093. module.exports = KeyboardShortcut;
  8094. },{}],37:[function(require,module,exports){
  8095. var email = '';
  8096. var displayName = '';
  8097. var userId;
  8098. var language = null;
  8099. function supportsLocalStorage() {
  8100. try {
  8101. return 'localStorage' in window && window.localStorage !== null;
  8102. } catch (e) {
  8103. console.log("localstorage is not supported");
  8104. return false;
  8105. }
  8106. }
  8107. function generateUniqueId() {
  8108. function _p8() {
  8109. return (Math.random().toString(16) + "000000000").substr(2, 8);
  8110. }
  8111. return _p8() + _p8() + _p8() + _p8();
  8112. }
  8113. if (supportsLocalStorage()) {
  8114. if (!window.localStorage.jitsiMeetId) {
  8115. window.localStorage.jitsiMeetId = generateUniqueId();
  8116. console.log("generated id", window.localStorage.jitsiMeetId);
  8117. }
  8118. userId = window.localStorage.jitsiMeetId || '';
  8119. email = window.localStorage.email || '';
  8120. displayName = window.localStorage.displayname || '';
  8121. language = window.localStorage.language;
  8122. } else {
  8123. console.log("local storage is not supported");
  8124. userId = generateUniqueId();
  8125. }
  8126. var Settings =
  8127. {
  8128. setDisplayName: function (newDisplayName) {
  8129. displayName = newDisplayName;
  8130. window.localStorage.displayname = displayName;
  8131. return displayName;
  8132. },
  8133. setEmail: function (newEmail)
  8134. {
  8135. email = newEmail;
  8136. window.localStorage.email = newEmail;
  8137. return email;
  8138. },
  8139. getSettings: function () {
  8140. return {
  8141. email: email,
  8142. displayName: displayName,
  8143. uid: userId,
  8144. language: language
  8145. };
  8146. },
  8147. setLanguage: function (lang) {
  8148. language = lang;
  8149. window.localStorage.language = lang;
  8150. }
  8151. };
  8152. module.exports = Settings;
  8153. },{}],38:[function(require,module,exports){
  8154. /**
  8155. *
  8156. * @constructor
  8157. */
  8158. function SimulcastLogger(name, lvl) {
  8159. this.name = name;
  8160. this.lvl = lvl;
  8161. }
  8162. SimulcastLogger.prototype.log = function (text) {
  8163. if (this.lvl) {
  8164. console.log(text);
  8165. }
  8166. };
  8167. SimulcastLogger.prototype.info = function (text) {
  8168. if (this.lvl > 1) {
  8169. console.info(text);
  8170. }
  8171. };
  8172. SimulcastLogger.prototype.fine = function (text) {
  8173. if (this.lvl > 2) {
  8174. console.log(text);
  8175. }
  8176. };
  8177. SimulcastLogger.prototype.error = function (text) {
  8178. console.error(text);
  8179. };
  8180. module.exports = SimulcastLogger;
  8181. },{}],39:[function(require,module,exports){
  8182. var SimulcastLogger = require("./SimulcastLogger");
  8183. var SimulcastUtils = require("./SimulcastUtils");
  8184. var MediaStreamType = require("../../service/RTC/MediaStreamTypes");
  8185. function SimulcastReceiver() {
  8186. this.simulcastUtils = new SimulcastUtils();
  8187. this.logger = new SimulcastLogger('SimulcastReceiver', 1);
  8188. }
  8189. SimulcastReceiver.prototype._remoteVideoSourceCache = '';
  8190. SimulcastReceiver.prototype._remoteMaps = {
  8191. msid2Quality: {},
  8192. ssrc2Msid: {},
  8193. msid2ssrc: {},
  8194. receivingVideoStreams: {}
  8195. };
  8196. SimulcastReceiver.prototype._cacheRemoteVideoSources = function (lines) {
  8197. this._remoteVideoSourceCache = this.simulcastUtils._getVideoSources(lines);
  8198. };
  8199. SimulcastReceiver.prototype._restoreRemoteVideoSources = function (lines) {
  8200. this.simulcastUtils._replaceVideoSources(lines, this._remoteVideoSourceCache);
  8201. };
  8202. SimulcastReceiver.prototype._ensureGoogConference = function (lines) {
  8203. var sb;
  8204. this.logger.info('Ensuring x-google-conference flag...')
  8205. if (this.simulcastUtils._indexOfArray('a=x-google-flag:conference', lines) === this.simulcastUtils._emptyCompoundIndex) {
  8206. // TODO(gp) do that for the audio as well as suggested by fippo.
  8207. // Add the google conference flag
  8208. sb = this.simulcastUtils._getVideoSources(lines);
  8209. sb = ['a=x-google-flag:conference'].concat(sb);
  8210. this.simulcastUtils._replaceVideoSources(lines, sb);
  8211. }
  8212. };
  8213. SimulcastReceiver.prototype._restoreSimulcastGroups = function (sb) {
  8214. this._restoreRemoteVideoSources(sb);
  8215. };
  8216. /**
  8217. * Restores the simulcast groups of the remote description. In
  8218. * transformRemoteDescription we remove those in order for the set remote
  8219. * description to succeed. The focus needs the signal the groups to new
  8220. * participants.
  8221. *
  8222. * @param desc
  8223. * @returns {*}
  8224. */
  8225. SimulcastReceiver.prototype.reverseTransformRemoteDescription = function (desc) {
  8226. var sb;
  8227. if (!this.simulcastUtils.isValidDescription(desc)) {
  8228. return desc;
  8229. }
  8230. if (config.enableSimulcast) {
  8231. sb = desc.sdp.split('\r\n');
  8232. this._restoreSimulcastGroups(sb);
  8233. desc = new RTCSessionDescription({
  8234. type: desc.type,
  8235. sdp: sb.join('\r\n')
  8236. });
  8237. }
  8238. return desc;
  8239. };
  8240. SimulcastUtils.prototype._ensureOrder = function (lines) {
  8241. var videoSources, sb;
  8242. videoSources = this.parseMedia(lines, ['video'])[0];
  8243. sb = this._compileVideoSources(videoSources);
  8244. this._replaceVideoSources(lines, sb);
  8245. };
  8246. SimulcastReceiver.prototype._updateRemoteMaps = function (lines) {
  8247. var remoteVideoSources = this.simulcastUtils.parseMedia(lines, ['video'])[0],
  8248. videoSource, quality;
  8249. // (re) initialize the remote maps.
  8250. this._remoteMaps.msid2Quality = {};
  8251. this._remoteMaps.ssrc2Msid = {};
  8252. this._remoteMaps.msid2ssrc = {};
  8253. var self = this;
  8254. if (remoteVideoSources.groups && remoteVideoSources.groups.length !== 0) {
  8255. remoteVideoSources.groups.forEach(function (group) {
  8256. if (group.semantics === 'SIM' && group.ssrcs && group.ssrcs.length !== 0) {
  8257. quality = 0;
  8258. group.ssrcs.forEach(function (ssrc) {
  8259. videoSource = remoteVideoSources.sources[ssrc];
  8260. self._remoteMaps.msid2Quality[videoSource.msid] = quality++;
  8261. self._remoteMaps.ssrc2Msid[videoSource.ssrc] = videoSource.msid;
  8262. self._remoteMaps.msid2ssrc[videoSource.msid] = videoSource.ssrc;
  8263. });
  8264. }
  8265. });
  8266. }
  8267. };
  8268. SimulcastReceiver.prototype._setReceivingVideoStream = function (resource, ssrc) {
  8269. this._remoteMaps.receivingVideoStreams[resource] = ssrc;
  8270. };
  8271. /**
  8272. * Returns a stream with single video track, the one currently being
  8273. * received by this endpoint.
  8274. *
  8275. * @param stream the remote simulcast stream.
  8276. * @returns {webkitMediaStream}
  8277. */
  8278. SimulcastReceiver.prototype.getReceivingVideoStream = function (stream) {
  8279. var tracks, i, electedTrack, msid, quality = 0, receivingTrackId;
  8280. var self = this;
  8281. if (config.enableSimulcast) {
  8282. stream.getVideoTracks().some(function (track) {
  8283. return Object.keys(self._remoteMaps.receivingVideoStreams).some(function (resource) {
  8284. var ssrc = self._remoteMaps.receivingVideoStreams[resource];
  8285. var msid = self._remoteMaps.ssrc2Msid[ssrc];
  8286. if (msid == [stream.id, track.id].join(' ')) {
  8287. electedTrack = track;
  8288. return true;
  8289. }
  8290. });
  8291. });
  8292. if (!electedTrack) {
  8293. // we don't have an elected track, choose by initial quality.
  8294. tracks = stream.getVideoTracks();
  8295. for (i = 0; i < tracks.length; i++) {
  8296. msid = [stream.id, tracks[i].id].join(' ');
  8297. if (this._remoteMaps.msid2Quality[msid] === quality) {
  8298. electedTrack = tracks[i];
  8299. break;
  8300. }
  8301. }
  8302. // TODO(gp) if the initialQuality could not be satisfied, lower
  8303. // the requirement and try again.
  8304. }
  8305. }
  8306. return (electedTrack)
  8307. ? new webkitMediaStream([electedTrack])
  8308. : stream;
  8309. };
  8310. SimulcastReceiver.prototype.getReceivingSSRC = function (jid) {
  8311. var resource = Strophe.getResourceFromJid(jid);
  8312. var ssrc = this._remoteMaps.receivingVideoStreams[resource];
  8313. // If we haven't receiving a "changed" event yet, then we must be receiving
  8314. // low quality (that the sender always streams).
  8315. if(!ssrc)
  8316. {
  8317. var remoteStreamObject = APP.RTC.remoteStreams[jid][MediaStreamType.VIDEO_TYPE];
  8318. var remoteStream = remoteStreamObject.getOriginalStream();
  8319. var tracks = remoteStream.getVideoTracks();
  8320. if (tracks) {
  8321. for (var k = 0; k < tracks.length; k++) {
  8322. var track = tracks[k];
  8323. var msid = [remoteStream.id, track.id].join(' ');
  8324. var _ssrc = this._remoteMaps.msid2ssrc[msid];
  8325. var quality = this._remoteMaps.msid2Quality[msid];
  8326. if (quality == 0) {
  8327. ssrc = _ssrc;
  8328. }
  8329. }
  8330. }
  8331. }
  8332. return ssrc;
  8333. };
  8334. SimulcastReceiver.prototype.getReceivingVideoStreamBySSRC = function (ssrc)
  8335. {
  8336. var sid, electedStream;
  8337. var i, j, k;
  8338. var jid = APP.xmpp.getJidFromSSRC(ssrc);
  8339. if(jid && APP.RTC.remoteStreams[jid])
  8340. {
  8341. var remoteStreamObject = APP.RTC.remoteStreams[jid][MediaStreamType.VIDEO_TYPE];
  8342. var remoteStream = remoteStreamObject.getOriginalStream();
  8343. var tracks = remoteStream.getVideoTracks();
  8344. if (tracks) {
  8345. for (k = 0; k < tracks.length; k++) {
  8346. var track = tracks[k];
  8347. var msid = [remoteStream.id, track.id].join(' ');
  8348. var tmp = this._remoteMaps.msid2ssrc[msid];
  8349. if (tmp == ssrc) {
  8350. electedStream = new webkitMediaStream([track]);
  8351. sid = remoteStreamObject.sid;
  8352. // stream found, stop.
  8353. break;
  8354. }
  8355. }
  8356. }
  8357. }
  8358. else
  8359. {
  8360. console.debug(APP.RTC.remoteStreams, jid, ssrc);
  8361. }
  8362. return {
  8363. sid: sid,
  8364. stream: electedStream
  8365. };
  8366. };
  8367. /**
  8368. * Gets the fully qualified msid (stream.id + track.id) associated to the
  8369. * SSRC.
  8370. *
  8371. * @param ssrc
  8372. * @returns {*}
  8373. */
  8374. SimulcastReceiver.prototype.getRemoteVideoStreamIdBySSRC = function (ssrc) {
  8375. return this._remoteMaps.ssrc2Msid[ssrc];
  8376. };
  8377. /**
  8378. * Removes the ssrc-group:SIM from the remote description bacause Chrome
  8379. * either gets confused and thinks this is an FID group or, if an FID group
  8380. * is already present, it fails to set the remote description.
  8381. *
  8382. * @param desc
  8383. * @returns {*}
  8384. */
  8385. SimulcastReceiver.prototype.transformRemoteDescription = function (desc) {
  8386. if (desc && desc.sdp) {
  8387. var sb = desc.sdp.split('\r\n');
  8388. this._updateRemoteMaps(sb);
  8389. this._cacheRemoteVideoSources(sb);
  8390. // NOTE(gp) this needs to be called after updateRemoteMaps because we
  8391. // need the simulcast group in the _updateRemoteMaps() method.
  8392. this.simulcastUtils._removeSimulcastGroup(sb);
  8393. if (desc.sdp.indexOf('a=ssrc-group:SIM') !== -1) {
  8394. // We don't need the goog conference flag if we're not doing
  8395. // simulcast.
  8396. this._ensureGoogConference(sb);
  8397. }
  8398. desc = new RTCSessionDescription({
  8399. type: desc.type,
  8400. sdp: sb.join('\r\n')
  8401. });
  8402. this.logger.fine(['Transformed remote description', desc.sdp].join(' '));
  8403. }
  8404. return desc;
  8405. };
  8406. module.exports = SimulcastReceiver;
  8407. },{"../../service/RTC/MediaStreamTypes":86,"./SimulcastLogger":38,"./SimulcastUtils":41}],40:[function(require,module,exports){
  8408. var SimulcastLogger = require("./SimulcastLogger");
  8409. var SimulcastUtils = require("./SimulcastUtils");
  8410. function SimulcastSender() {
  8411. this.simulcastUtils = new SimulcastUtils();
  8412. this.logger = new SimulcastLogger('SimulcastSender', 1);
  8413. }
  8414. SimulcastSender.prototype.displayedLocalVideoStream = null;
  8415. SimulcastSender.prototype._generateGuid = (function () {
  8416. function s4() {
  8417. return Math.floor((1 + Math.random()) * 0x10000)
  8418. .toString(16)
  8419. .substring(1);
  8420. }
  8421. return function () {
  8422. return s4() + s4() + '-' + s4() + '-' + s4() + '-' +
  8423. s4() + '-' + s4() + s4() + s4();
  8424. };
  8425. }());
  8426. // Returns a random integer between min (included) and max (excluded)
  8427. // Using Math.round() gives a non-uniform distribution!
  8428. SimulcastSender.prototype._generateRandomSSRC = function () {
  8429. var min = 0, max = 0xffffffff;
  8430. return Math.floor(Math.random() * (max - min)) + min;
  8431. };
  8432. SimulcastSender.prototype.getLocalVideoStream = function () {
  8433. return (this.displayedLocalVideoStream != null)
  8434. ? this.displayedLocalVideoStream
  8435. // in case we have no simulcast at all, i.e. we didn't perform the GUM
  8436. : APP.RTC.localVideo.getOriginalStream();
  8437. };
  8438. function NativeSimulcastSender() {
  8439. SimulcastSender.call(this); // call the super constructor.
  8440. }
  8441. NativeSimulcastSender.prototype = Object.create(SimulcastSender.prototype);
  8442. NativeSimulcastSender.prototype._localExplosionMap = {};
  8443. NativeSimulcastSender.prototype._isUsingScreenStream = false;
  8444. NativeSimulcastSender.prototype._localVideoSourceCache = '';
  8445. NativeSimulcastSender.prototype.reset = function () {
  8446. this._localExplosionMap = {};
  8447. this._isUsingScreenStream = APP.desktopsharing.isUsingScreenStream();
  8448. };
  8449. NativeSimulcastSender.prototype._cacheLocalVideoSources = function (lines) {
  8450. this._localVideoSourceCache = this.simulcastUtils._getVideoSources(lines);
  8451. };
  8452. NativeSimulcastSender.prototype._restoreLocalVideoSources = function (lines) {
  8453. this.simulcastUtils._replaceVideoSources(lines, this._localVideoSourceCache);
  8454. };
  8455. NativeSimulcastSender.prototype._appendSimulcastGroup = function (lines) {
  8456. var videoSources, ssrcGroup, simSSRC, numOfSubs = 2, i, sb, msid;
  8457. this.logger.info('Appending simulcast group...');
  8458. // Get the primary SSRC information.
  8459. videoSources = this.simulcastUtils.parseMedia(lines, ['video'])[0];
  8460. // Start building the SIM SSRC group.
  8461. ssrcGroup = ['a=ssrc-group:SIM'];
  8462. // The video source buffer.
  8463. sb = [];
  8464. // Create the simulcast sub-streams.
  8465. for (i = 0; i < numOfSubs; i++) {
  8466. // TODO(gp) prevent SSRC collision.
  8467. simSSRC = this._generateRandomSSRC();
  8468. ssrcGroup.push(simSSRC);
  8469. if (videoSources.base) {
  8470. sb.splice.apply(sb, [sb.length, 0].concat(
  8471. [["a=ssrc:", simSSRC, " cname:", videoSources.base.cname].join(''),
  8472. ["a=ssrc:", simSSRC, " msid:", videoSources.base.msid].join('')]
  8473. ));
  8474. }
  8475. this.logger.info(['Generated substream ', i, ' with SSRC ', simSSRC, '.'].join(''));
  8476. }
  8477. // Add the group sim layers.
  8478. sb.splice(0, 0, ssrcGroup.join(' '))
  8479. this.simulcastUtils._replaceVideoSources(lines, sb);
  8480. };
  8481. // Does the actual patching.
  8482. NativeSimulcastSender.prototype._ensureSimulcastGroup = function (lines) {
  8483. this.logger.info('Ensuring simulcast group...');
  8484. if (this.simulcastUtils._indexOfArray('a=ssrc-group:SIM', lines) === this.simulcastUtils._emptyCompoundIndex) {
  8485. this._appendSimulcastGroup(lines);
  8486. this._cacheLocalVideoSources(lines);
  8487. } else {
  8488. // verify that the ssrcs participating in the SIM group are present
  8489. // in the SDP (needed for presence).
  8490. this._restoreLocalVideoSources(lines);
  8491. }
  8492. };
  8493. /**
  8494. * Produces a single stream with multiple tracks for local video sources.
  8495. *
  8496. * @param lines
  8497. * @private
  8498. */
  8499. NativeSimulcastSender.prototype._explodeSimulcastSenderSources = function (lines) {
  8500. var sb, msid, sid, tid, videoSources, self;
  8501. this.logger.info('Exploding local video sources...');
  8502. videoSources = this.simulcastUtils.parseMedia(lines, ['video'])[0];
  8503. self = this;
  8504. if (videoSources.groups && videoSources.groups.length !== 0) {
  8505. videoSources.groups.forEach(function (group) {
  8506. if (group.semantics === 'SIM') {
  8507. group.ssrcs.forEach(function (ssrc) {
  8508. // Get the msid for this ssrc..
  8509. if (self._localExplosionMap[ssrc]) {
  8510. // .. either from the explosion map..
  8511. msid = self._localExplosionMap[ssrc];
  8512. } else {
  8513. // .. or generate a new one (msid).
  8514. sid = videoSources.sources[ssrc].msid
  8515. .substring(0, videoSources.sources[ssrc].msid.indexOf(' '));
  8516. tid = self._generateGuid();
  8517. msid = [sid, tid].join(' ');
  8518. self._localExplosionMap[ssrc] = msid;
  8519. }
  8520. // Assign it to the source object.
  8521. videoSources.sources[ssrc].msid = msid;
  8522. // TODO(gp) Change the msid of associated sources.
  8523. });
  8524. }
  8525. });
  8526. }
  8527. sb = this.simulcastUtils._compileVideoSources(videoSources);
  8528. this.simulcastUtils._replaceVideoSources(lines, sb);
  8529. };
  8530. /**
  8531. * GUM for simulcast.
  8532. *
  8533. * @param constraints
  8534. * @param success
  8535. * @param err
  8536. */
  8537. NativeSimulcastSender.prototype.getUserMedia = function (constraints, success, err) {
  8538. // There's nothing special to do for native simulcast, so just do a normal GUM.
  8539. navigator.webkitGetUserMedia(constraints, function (hqStream) {
  8540. success(hqStream);
  8541. }, err);
  8542. };
  8543. /**
  8544. * Prepares the local description for public usage (i.e. to be signaled
  8545. * through Jingle to the focus).
  8546. *
  8547. * @param desc
  8548. * @returns {RTCSessionDescription}
  8549. */
  8550. NativeSimulcastSender.prototype.reverseTransformLocalDescription = function (desc) {
  8551. var sb;
  8552. if (!this.simulcastUtils.isValidDescription(desc) || this._isUsingScreenStream) {
  8553. return desc;
  8554. }
  8555. sb = desc.sdp.split('\r\n');
  8556. this._explodeSimulcastSenderSources(sb);
  8557. desc = new RTCSessionDescription({
  8558. type: desc.type,
  8559. sdp: sb.join('\r\n')
  8560. });
  8561. this.logger.fine(['Exploded local video sources', desc.sdp].join(' '));
  8562. return desc;
  8563. };
  8564. /**
  8565. * Ensures that the simulcast group is present in the answer, _if_ native
  8566. * simulcast is enabled,
  8567. *
  8568. * @param desc
  8569. * @returns {*}
  8570. */
  8571. NativeSimulcastSender.prototype.transformAnswer = function (desc) {
  8572. if (!this.simulcastUtils.isValidDescription(desc) || this._isUsingScreenStream) {
  8573. return desc;
  8574. }
  8575. var sb = desc.sdp.split('\r\n');
  8576. // Even if we have enabled native simulcasting previously
  8577. // (with a call to SLD with an appropriate SDP, for example),
  8578. // createAnswer seems to consistently generate incomplete SDP
  8579. // with missing SSRCS.
  8580. //
  8581. // So, subsequent calls to SLD will have missing SSRCS and presence
  8582. // won't have the complete list of SRCs.
  8583. this._ensureSimulcastGroup(sb);
  8584. desc = new RTCSessionDescription({
  8585. type: desc.type,
  8586. sdp: sb.join('\r\n')
  8587. });
  8588. this.logger.fine(['Transformed answer', desc.sdp].join(' '));
  8589. return desc;
  8590. };
  8591. /**
  8592. *
  8593. *
  8594. * @param desc
  8595. * @returns {*}
  8596. */
  8597. NativeSimulcastSender.prototype.transformLocalDescription = function (desc) {
  8598. return desc;
  8599. };
  8600. NativeSimulcastSender.prototype._setLocalVideoStreamEnabled = function (ssrc, enabled) {
  8601. // Nothing to do here, native simulcast does that auto-magically.
  8602. };
  8603. NativeSimulcastSender.prototype.constructor = NativeSimulcastSender;
  8604. function SimpleSimulcastSender() {
  8605. SimulcastSender.call(this);
  8606. }
  8607. SimpleSimulcastSender.prototype = Object.create(SimulcastSender.prototype);
  8608. SimpleSimulcastSender.prototype.localStream = null;
  8609. SimpleSimulcastSender.prototype._localMaps = {
  8610. msids: [],
  8611. msid2ssrc: {}
  8612. };
  8613. /**
  8614. * Groups local video sources together in the ssrc-group:SIM group.
  8615. *
  8616. * @param lines
  8617. * @private
  8618. */
  8619. SimpleSimulcastSender.prototype._groupLocalVideoSources = function (lines) {
  8620. var sb, videoSources, ssrcs = [], ssrc;
  8621. this.logger.info('Grouping local video sources...');
  8622. videoSources = this.simulcastUtils.parseMedia(lines, ['video'])[0];
  8623. for (ssrc in videoSources.sources) {
  8624. // jitsi-meet destroys/creates streams at various places causing
  8625. // the original local stream ids to change. The only thing that
  8626. // remains unchanged is the trackid.
  8627. this._localMaps.msid2ssrc[videoSources.sources[ssrc].msid.split(' ')[1]] = ssrc;
  8628. }
  8629. var self = this;
  8630. // TODO(gp) add only "free" sources.
  8631. this._localMaps.msids.forEach(function (msid) {
  8632. ssrcs.push(self._localMaps.msid2ssrc[msid]);
  8633. });
  8634. if (!videoSources.groups) {
  8635. videoSources.groups = [];
  8636. }
  8637. videoSources.groups.push({
  8638. 'semantics': 'SIM',
  8639. 'ssrcs': ssrcs
  8640. });
  8641. sb = this.simulcastUtils._compileVideoSources(videoSources);
  8642. this.simulcastUtils._replaceVideoSources(lines, sb);
  8643. };
  8644. /**
  8645. * GUM for simulcast.
  8646. *
  8647. * @param constraints
  8648. * @param success
  8649. * @param err
  8650. */
  8651. SimpleSimulcastSender.prototype.getUserMedia = function (constraints, success, err) {
  8652. // TODO(gp) what if we request a resolution not supported by the hardware?
  8653. // TODO(gp) make the lq stream configurable; although this wouldn't work with native simulcast
  8654. var lqConstraints = {
  8655. audio: false,
  8656. video: {
  8657. mandatory: {
  8658. maxWidth: 320,
  8659. maxHeight: 180,
  8660. maxFrameRate: 15
  8661. }
  8662. }
  8663. };
  8664. this.logger.info('HQ constraints: ', constraints);
  8665. this.logger.info('LQ constraints: ', lqConstraints);
  8666. // NOTE(gp) if we request the lq stream first webkitGetUserMedia
  8667. // fails randomly. Tested with Chrome 37. As fippo suggested, the
  8668. // reason appears to be that Chrome only acquires the cam once and
  8669. // then downscales the picture (https://code.google.com/p/chromium/issues/detail?id=346616#c11)
  8670. var self = this;
  8671. navigator.webkitGetUserMedia(constraints, function (hqStream) {
  8672. self.localStream = hqStream;
  8673. // reset local maps.
  8674. self._localMaps.msids = [];
  8675. self._localMaps.msid2ssrc = {};
  8676. // add hq trackid to local map
  8677. self._localMaps.msids.push(hqStream.getVideoTracks()[0].id);
  8678. navigator.webkitGetUserMedia(lqConstraints, function (lqStream) {
  8679. self.displayedLocalVideoStream = lqStream;
  8680. // NOTE(gp) The specification says Array.forEach() will visit
  8681. // the array elements in numeric order, and that it doesn't
  8682. // visit elements that don't exist.
  8683. // add lq trackid to local map
  8684. self._localMaps.msids.splice(0, 0, lqStream.getVideoTracks()[0].id);
  8685. self.localStream.addTrack(lqStream.getVideoTracks()[0]);
  8686. success(self.localStream);
  8687. }, err);
  8688. }, err);
  8689. };
  8690. /**
  8691. * Prepares the local description for public usage (i.e. to be signaled
  8692. * through Jingle to the focus).
  8693. *
  8694. * @param desc
  8695. * @returns {RTCSessionDescription}
  8696. */
  8697. SimpleSimulcastSender.prototype.reverseTransformLocalDescription = function (desc) {
  8698. var sb;
  8699. if (!this.simulcastUtils.isValidDescription(desc)) {
  8700. return desc;
  8701. }
  8702. sb = desc.sdp.split('\r\n');
  8703. this._groupLocalVideoSources(sb);
  8704. desc = new RTCSessionDescription({
  8705. type: desc.type,
  8706. sdp: sb.join('\r\n')
  8707. });
  8708. this.logger.fine('Grouped local video sources');
  8709. this.logger.fine(desc.sdp);
  8710. return desc;
  8711. };
  8712. /**
  8713. * Ensures that the simulcast group is present in the answer, _if_ native
  8714. * simulcast is enabled,
  8715. *
  8716. * @param desc
  8717. * @returns {*}
  8718. */
  8719. SimpleSimulcastSender.prototype.transformAnswer = function (desc) {
  8720. return desc;
  8721. };
  8722. /**
  8723. *
  8724. *
  8725. * @param desc
  8726. * @returns {*}
  8727. */
  8728. SimpleSimulcastSender.prototype.transformLocalDescription = function (desc) {
  8729. var sb = desc.sdp.split('\r\n');
  8730. this.simulcastUtils._removeSimulcastGroup(sb);
  8731. desc = new RTCSessionDescription({
  8732. type: desc.type,
  8733. sdp: sb.join('\r\n')
  8734. });
  8735. this.logger.fine('Transformed local description');
  8736. this.logger.fine(desc.sdp);
  8737. return desc;
  8738. };
  8739. SimpleSimulcastSender.prototype._setLocalVideoStreamEnabled = function (ssrc, enabled) {
  8740. var trackid;
  8741. var self = this;
  8742. this.logger.log(['Requested to', enabled ? 'enable' : 'disable', ssrc].join(' '));
  8743. if (Object.keys(this._localMaps.msid2ssrc).some(function (tid) {
  8744. // Search for the track id that corresponds to the ssrc
  8745. if (self._localMaps.msid2ssrc[tid] == ssrc) {
  8746. trackid = tid;
  8747. return true;
  8748. }
  8749. }) && self.localStream.getVideoTracks().some(function (track) {
  8750. // Start/stop the track that corresponds to the track id
  8751. if (track.id === trackid) {
  8752. track.enabled = enabled;
  8753. return true;
  8754. }
  8755. })) {
  8756. this.logger.log([trackid, enabled ? 'enabled' : 'disabled'].join(' '));
  8757. $(document).trigger(enabled
  8758. ? 'simulcastlayerstarted'
  8759. : 'simulcastlayerstopped');
  8760. } else {
  8761. this.logger.error("I don't have a local stream with SSRC " + ssrc);
  8762. }
  8763. };
  8764. SimpleSimulcastSender.prototype.constructor = SimpleSimulcastSender;
  8765. function NoSimulcastSender() {
  8766. SimulcastSender.call(this);
  8767. }
  8768. NoSimulcastSender.prototype = Object.create(SimulcastSender.prototype);
  8769. /**
  8770. * GUM for simulcast.
  8771. *
  8772. * @param constraints
  8773. * @param success
  8774. * @param err
  8775. */
  8776. NoSimulcastSender.prototype.getUserMedia = function (constraints, success, err) {
  8777. navigator.webkitGetUserMedia(constraints, function (hqStream) {
  8778. success(hqStream);
  8779. }, err);
  8780. };
  8781. /**
  8782. * Prepares the local description for public usage (i.e. to be signaled
  8783. * through Jingle to the focus).
  8784. *
  8785. * @param desc
  8786. * @returns {RTCSessionDescription}
  8787. */
  8788. NoSimulcastSender.prototype.reverseTransformLocalDescription = function (desc) {
  8789. return desc;
  8790. };
  8791. /**
  8792. * Ensures that the simulcast group is present in the answer, _if_ native
  8793. * simulcast is enabled,
  8794. *
  8795. * @param desc
  8796. * @returns {*}
  8797. */
  8798. NoSimulcastSender.prototype.transformAnswer = function (desc) {
  8799. return desc;
  8800. };
  8801. /**
  8802. *
  8803. *
  8804. * @param desc
  8805. * @returns {*}
  8806. */
  8807. NoSimulcastSender.prototype.transformLocalDescription = function (desc) {
  8808. return desc;
  8809. };
  8810. NoSimulcastSender.prototype._setLocalVideoStreamEnabled = function (ssrc, enabled) {
  8811. };
  8812. NoSimulcastSender.prototype.constructor = NoSimulcastSender;
  8813. module.exports = {
  8814. "native": NativeSimulcastSender,
  8815. "no": NoSimulcastSender
  8816. }
  8817. },{"./SimulcastLogger":38,"./SimulcastUtils":41}],41:[function(require,module,exports){
  8818. var SimulcastLogger = require("./SimulcastLogger");
  8819. /**
  8820. *
  8821. * @constructor
  8822. */
  8823. function SimulcastUtils() {
  8824. this.logger = new SimulcastLogger("SimulcastUtils", 1);
  8825. }
  8826. /**
  8827. *
  8828. * @type {{}}
  8829. * @private
  8830. */
  8831. SimulcastUtils.prototype._emptyCompoundIndex = {};
  8832. /**
  8833. *
  8834. * @param lines
  8835. * @param videoSources
  8836. * @private
  8837. */
  8838. SimulcastUtils.prototype._replaceVideoSources = function (lines, videoSources) {
  8839. var i, inVideo = false, index = -1, howMany = 0;
  8840. this.logger.info('Replacing video sources...');
  8841. for (i = 0; i < lines.length; i++) {
  8842. if (inVideo && lines[i].substring(0, 'm='.length) === 'm=') {
  8843. // Out of video.
  8844. break;
  8845. }
  8846. if (!inVideo && lines[i].substring(0, 'm=video '.length) === 'm=video ') {
  8847. // In video.
  8848. inVideo = true;
  8849. }
  8850. if (inVideo && (lines[i].substring(0, 'a=ssrc:'.length) === 'a=ssrc:'
  8851. || lines[i].substring(0, 'a=ssrc-group:'.length) === 'a=ssrc-group:')) {
  8852. if (index === -1) {
  8853. index = i;
  8854. }
  8855. howMany++;
  8856. }
  8857. }
  8858. // efficiency baby ;)
  8859. lines.splice.apply(lines,
  8860. [index, howMany].concat(videoSources));
  8861. };
  8862. SimulcastUtils.prototype.isValidDescription = function (desc)
  8863. {
  8864. return desc && desc != null
  8865. && desc.type && desc.type != ''
  8866. && desc.sdp && desc.sdp != '';
  8867. };
  8868. SimulcastUtils.prototype._getVideoSources = function (lines) {
  8869. var i, inVideo = false, sb = [];
  8870. this.logger.info('Getting video sources...');
  8871. for (i = 0; i < lines.length; i++) {
  8872. if (inVideo && lines[i].substring(0, 'm='.length) === 'm=') {
  8873. // Out of video.
  8874. break;
  8875. }
  8876. if (!inVideo && lines[i].substring(0, 'm=video '.length) === 'm=video ') {
  8877. // In video.
  8878. inVideo = true;
  8879. }
  8880. if (inVideo && lines[i].substring(0, 'a=ssrc:'.length) === 'a=ssrc:') {
  8881. // In SSRC.
  8882. sb.push(lines[i]);
  8883. }
  8884. if (inVideo && lines[i].substring(0, 'a=ssrc-group:'.length) === 'a=ssrc-group:') {
  8885. sb.push(lines[i]);
  8886. }
  8887. }
  8888. return sb;
  8889. };
  8890. SimulcastUtils.prototype.parseMedia = function (lines, mediatypes) {
  8891. var i, res = [], type, cur_media, idx, ssrcs, cur_ssrc, ssrc,
  8892. ssrc_attribute, group, semantics, skip = true;
  8893. this.logger.info('Parsing media sources...');
  8894. for (i = 0; i < lines.length; i++) {
  8895. if (lines[i].substring(0, 'm='.length) === 'm=') {
  8896. type = lines[i]
  8897. .substr('m='.length, lines[i].indexOf(' ') - 'm='.length);
  8898. skip = mediatypes !== undefined && mediatypes.indexOf(type) === -1;
  8899. if (!skip) {
  8900. cur_media = {
  8901. 'type': type,
  8902. 'sources': {},
  8903. 'groups': []
  8904. };
  8905. res.push(cur_media);
  8906. }
  8907. } else if (!skip && lines[i].substring(0, 'a=ssrc:'.length) === 'a=ssrc:') {
  8908. idx = lines[i].indexOf(' ');
  8909. ssrc = lines[i].substring('a=ssrc:'.length, idx);
  8910. if (cur_media.sources[ssrc] === undefined) {
  8911. cur_ssrc = {'ssrc': ssrc};
  8912. cur_media.sources[ssrc] = cur_ssrc;
  8913. }
  8914. ssrc_attribute = lines[i].substr(idx + 1).split(':', 2)[0];
  8915. cur_ssrc[ssrc_attribute] = lines[i].substr(idx + 1).split(':', 2)[1];
  8916. if (cur_media.base === undefined) {
  8917. cur_media.base = cur_ssrc;
  8918. }
  8919. } else if (!skip && lines[i].substring(0, 'a=ssrc-group:'.length) === 'a=ssrc-group:') {
  8920. idx = lines[i].indexOf(' ');
  8921. semantics = lines[i].substr(0, idx).substr('a=ssrc-group:'.length);
  8922. ssrcs = lines[i].substr(idx).trim().split(' ');
  8923. group = {
  8924. 'semantics': semantics,
  8925. 'ssrcs': ssrcs
  8926. };
  8927. cur_media.groups.push(group);
  8928. } else if (!skip && (lines[i].substring(0, 'a=sendrecv'.length) === 'a=sendrecv' ||
  8929. lines[i].substring(0, 'a=recvonly'.length) === 'a=recvonly' ||
  8930. lines[i].substring(0, 'a=sendonly'.length) === 'a=sendonly' ||
  8931. lines[i].substring(0, 'a=inactive'.length) === 'a=inactive')) {
  8932. cur_media.direction = lines[i].substring('a='.length);
  8933. }
  8934. }
  8935. return res;
  8936. };
  8937. /**
  8938. * The _indexOfArray() method returns the first a CompoundIndex at which a
  8939. * given element can be found in the array, or _emptyCompoundIndex if it is
  8940. * not present.
  8941. *
  8942. * Example:
  8943. *
  8944. * _indexOfArray('3', [ 'this is line 1', 'this is line 2', 'this is line 3' ])
  8945. *
  8946. * returns {row: 2, column: 14}
  8947. *
  8948. * @param needle
  8949. * @param haystack
  8950. * @param start
  8951. * @returns {}
  8952. * @private
  8953. */
  8954. SimulcastUtils.prototype._indexOfArray = function (needle, haystack, start) {
  8955. var length = haystack.length, idx, i;
  8956. if (!start) {
  8957. start = 0;
  8958. }
  8959. for (i = start; i < length; i++) {
  8960. idx = haystack[i].indexOf(needle);
  8961. if (idx !== -1) {
  8962. return {row: i, column: idx};
  8963. }
  8964. }
  8965. return this._emptyCompoundIndex;
  8966. };
  8967. SimulcastUtils.prototype._removeSimulcastGroup = function (lines) {
  8968. var i;
  8969. for (i = lines.length - 1; i >= 0; i--) {
  8970. if (lines[i].indexOf('a=ssrc-group:SIM') !== -1) {
  8971. lines.splice(i, 1);
  8972. }
  8973. }
  8974. };
  8975. SimulcastUtils.prototype._compileVideoSources = function (videoSources) {
  8976. var sb = [], ssrc, addedSSRCs = [];
  8977. this.logger.info('Compiling video sources...');
  8978. // Add the groups
  8979. if (videoSources.groups && videoSources.groups.length !== 0) {
  8980. videoSources.groups.forEach(function (group) {
  8981. if (group.ssrcs && group.ssrcs.length !== 0) {
  8982. sb.push([['a=ssrc-group:', group.semantics].join(''), group.ssrcs.join(' ')].join(' '));
  8983. // if (group.semantics !== 'SIM') {
  8984. group.ssrcs.forEach(function (ssrc) {
  8985. addedSSRCs.push(ssrc);
  8986. sb.splice.apply(sb, [sb.length, 0].concat([
  8987. ["a=ssrc:", ssrc, " cname:", videoSources.sources[ssrc].cname].join(''),
  8988. ["a=ssrc:", ssrc, " msid:", videoSources.sources[ssrc].msid].join('')]));
  8989. });
  8990. //}
  8991. }
  8992. });
  8993. }
  8994. // Then add any free sources.
  8995. if (videoSources.sources) {
  8996. for (ssrc in videoSources.sources) {
  8997. if (addedSSRCs.indexOf(ssrc) === -1) {
  8998. sb.splice.apply(sb, [sb.length, 0].concat([
  8999. ["a=ssrc:", ssrc, " cname:", videoSources.sources[ssrc].cname].join(''),
  9000. ["a=ssrc:", ssrc, " msid:", videoSources.sources[ssrc].msid].join('')]));
  9001. }
  9002. }
  9003. }
  9004. return sb;
  9005. };
  9006. module.exports = SimulcastUtils;
  9007. },{"./SimulcastLogger":38}],42:[function(require,module,exports){
  9008. /*jslint plusplus: true */
  9009. /*jslint nomen: true*/
  9010. var SimulcastSender = require("./SimulcastSender");
  9011. var NoSimulcastSender = SimulcastSender["no"];
  9012. var NativeSimulcastSender = SimulcastSender["native"];
  9013. var SimulcastReceiver = require("./SimulcastReceiver");
  9014. var SimulcastUtils = require("./SimulcastUtils");
  9015. var RTCEvents = require("../../service/RTC/RTCEvents");
  9016. /**
  9017. *
  9018. * @constructor
  9019. */
  9020. function SimulcastManager() {
  9021. // Create the simulcast utilities.
  9022. this.simulcastUtils = new SimulcastUtils();
  9023. // Create remote simulcast.
  9024. this.simulcastReceiver = new SimulcastReceiver();
  9025. // Initialize local simulcast.
  9026. // TODO(gp) move into SimulcastManager.prototype.getUserMedia and take into
  9027. // account constraints.
  9028. if (!config.enableSimulcast) {
  9029. this.simulcastSender = new NoSimulcastSender();
  9030. } else {
  9031. var isChromium = window.chrome,
  9032. vendorName = window.navigator.vendor;
  9033. if(isChromium !== null && isChromium !== undefined
  9034. /* skip opera */
  9035. && vendorName === "Google Inc."
  9036. /* skip Chromium as suggested by fippo */
  9037. && !window.navigator.appVersion.match(/Chromium\//) ) {
  9038. var ver = parseInt(window.navigator.appVersion.match(/Chrome\/(\d+)\./)[1], 10);
  9039. if (ver > 37) {
  9040. this.simulcastSender = new NativeSimulcastSender();
  9041. } else {
  9042. this.simulcastSender = new NoSimulcastSender();
  9043. }
  9044. } else {
  9045. this.simulcastSender = new NoSimulcastSender();
  9046. }
  9047. }
  9048. APP.RTC.addListener(RTCEvents.SIMULCAST_LAYER_CHANGED,
  9049. function (endpointSimulcastLayers) {
  9050. endpointSimulcastLayers.forEach(function (esl) {
  9051. var ssrc = esl.simulcastLayer.primarySSRC;
  9052. simulcast._setReceivingVideoStream(esl.endpoint, ssrc);
  9053. });
  9054. });
  9055. APP.RTC.addListener(RTCEvents.SIMULCAST_START, function (simulcastLayer) {
  9056. var ssrc = simulcastLayer.primarySSRC;
  9057. simulcast._setLocalVideoStreamEnabled(ssrc, true);
  9058. });
  9059. APP.RTC.addListener(RTCEvents.SIMULCAST_STOP, function (simulcastLayer) {
  9060. var ssrc = simulcastLayer.primarySSRC;
  9061. simulcast._setLocalVideoStreamEnabled(ssrc, false);
  9062. });
  9063. }
  9064. /**
  9065. * Restores the simulcast groups of the remote description. In
  9066. * transformRemoteDescription we remove those in order for the set remote
  9067. * description to succeed. The focus needs the signal the groups to new
  9068. * participants.
  9069. *
  9070. * @param desc
  9071. * @returns {*}
  9072. */
  9073. SimulcastManager.prototype.reverseTransformRemoteDescription = function (desc) {
  9074. return this.simulcastReceiver.reverseTransformRemoteDescription(desc);
  9075. };
  9076. /**
  9077. * Removes the ssrc-group:SIM from the remote description bacause Chrome
  9078. * either gets confused and thinks this is an FID group or, if an FID group
  9079. * is already present, it fails to set the remote description.
  9080. *
  9081. * @param desc
  9082. * @returns {*}
  9083. */
  9084. SimulcastManager.prototype.transformRemoteDescription = function (desc) {
  9085. return this.simulcastReceiver.transformRemoteDescription(desc);
  9086. };
  9087. /**
  9088. * Gets the fully qualified msid (stream.id + track.id) associated to the
  9089. * SSRC.
  9090. *
  9091. * @param ssrc
  9092. * @returns {*}
  9093. */
  9094. SimulcastManager.prototype.getRemoteVideoStreamIdBySSRC = function (ssrc) {
  9095. return this.simulcastReceiver.getRemoteVideoStreamIdBySSRC(ssrc);
  9096. };
  9097. /**
  9098. * Returns a stream with single video track, the one currently being
  9099. * received by this endpoint.
  9100. *
  9101. * @param stream the remote simulcast stream.
  9102. * @returns {webkitMediaStream}
  9103. */
  9104. SimulcastManager.prototype.getReceivingVideoStream = function (stream) {
  9105. return this.simulcastReceiver.getReceivingVideoStream(stream);
  9106. };
  9107. /**
  9108. *
  9109. *
  9110. * @param desc
  9111. * @returns {*}
  9112. */
  9113. SimulcastManager.prototype.transformLocalDescription = function (desc) {
  9114. return this.simulcastSender.transformLocalDescription(desc);
  9115. };
  9116. /**
  9117. *
  9118. * @returns {*}
  9119. */
  9120. SimulcastManager.prototype.getLocalVideoStream = function() {
  9121. return this.simulcastSender.getLocalVideoStream();
  9122. };
  9123. /**
  9124. * GUM for simulcast.
  9125. *
  9126. * @param constraints
  9127. * @param success
  9128. * @param err
  9129. */
  9130. SimulcastManager.prototype.getUserMedia = function (constraints, success, err) {
  9131. this.simulcastSender.getUserMedia(constraints, success, err);
  9132. };
  9133. /**
  9134. * Prepares the local description for public usage (i.e. to be signaled
  9135. * through Jingle to the focus).
  9136. *
  9137. * @param desc
  9138. * @returns {RTCSessionDescription}
  9139. */
  9140. SimulcastManager.prototype.reverseTransformLocalDescription = function (desc) {
  9141. return this.simulcastSender.reverseTransformLocalDescription(desc);
  9142. };
  9143. /**
  9144. * Ensures that the simulcast group is present in the answer, _if_ native
  9145. * simulcast is enabled,
  9146. *
  9147. * @param desc
  9148. * @returns {*}
  9149. */
  9150. SimulcastManager.prototype.transformAnswer = function (desc) {
  9151. return this.simulcastSender.transformAnswer(desc);
  9152. };
  9153. SimulcastManager.prototype.getReceivingSSRC = function (jid) {
  9154. return this.simulcastReceiver.getReceivingSSRC(jid);
  9155. };
  9156. SimulcastManager.prototype.getReceivingVideoStreamBySSRC = function (msid) {
  9157. return this.simulcastReceiver.getReceivingVideoStreamBySSRC(msid);
  9158. };
  9159. /**
  9160. *
  9161. * @param lines
  9162. * @param mediatypes
  9163. * @returns {*}
  9164. */
  9165. SimulcastManager.prototype.parseMedia = function(lines, mediatypes) {
  9166. var sb = lines.sdp.split('\r\n');
  9167. return this.simulcastUtils.parseMedia(sb, mediatypes);
  9168. };
  9169. SimulcastManager.prototype._setReceivingVideoStream = function(resource, ssrc) {
  9170. this.simulcastReceiver._setReceivingVideoStream(resource, ssrc);
  9171. };
  9172. SimulcastManager.prototype._setLocalVideoStreamEnabled = function(ssrc, enabled) {
  9173. this.simulcastSender._setLocalVideoStreamEnabled(ssrc, enabled);
  9174. };
  9175. SimulcastManager.prototype.resetSender = function() {
  9176. if (typeof this.simulcastSender.reset === 'function'){
  9177. this.simulcastSender.reset();
  9178. }
  9179. };
  9180. var simulcast = new SimulcastManager();
  9181. module.exports = simulcast;
  9182. },{"../../service/RTC/RTCEvents":88,"./SimulcastReceiver":39,"./SimulcastSender":40,"./SimulcastUtils":41}],43:[function(require,module,exports){
  9183. /**
  9184. * Provides statistics for the local stream.
  9185. */
  9186. /**
  9187. * Size of the webaudio analizer buffer.
  9188. * @type {number}
  9189. */
  9190. var WEBAUDIO_ANALIZER_FFT_SIZE = 2048;
  9191. /**
  9192. * Value of the webaudio analizer smoothing time parameter.
  9193. * @type {number}
  9194. */
  9195. var WEBAUDIO_ANALIZER_SMOOTING_TIME = 0.8;
  9196. /**
  9197. * Converts time domain data array to audio level.
  9198. * @param array the time domain data array.
  9199. * @returns {number} the audio level
  9200. */
  9201. function timeDomainDataToAudioLevel(samples) {
  9202. var maxVolume = 0;
  9203. var length = samples.length;
  9204. for (var i = 0; i < length; i++) {
  9205. if (maxVolume < samples[i])
  9206. maxVolume = samples[i];
  9207. }
  9208. return parseFloat(((maxVolume - 127) / 128).toFixed(3));
  9209. };
  9210. /**
  9211. * Animates audio level change
  9212. * @param newLevel the new audio level
  9213. * @param lastLevel the last audio level
  9214. * @returns {Number} the audio level to be set
  9215. */
  9216. function animateLevel(newLevel, lastLevel)
  9217. {
  9218. var value = 0;
  9219. var diff = lastLevel - newLevel;
  9220. if(diff > 0.2)
  9221. {
  9222. value = lastLevel - 0.2;
  9223. }
  9224. else if(diff < -0.4)
  9225. {
  9226. value = lastLevel + 0.4;
  9227. }
  9228. else
  9229. {
  9230. value = newLevel;
  9231. }
  9232. return parseFloat(value.toFixed(3));
  9233. }
  9234. /**
  9235. * <tt>LocalStatsCollector</tt> calculates statistics for the local stream.
  9236. *
  9237. * @param stream the local stream
  9238. * @param interval stats refresh interval given in ms.
  9239. * @param {function(LocalStatsCollector)} updateCallback the callback called on stats
  9240. * update.
  9241. * @constructor
  9242. */
  9243. function LocalStatsCollector(stream, interval, statisticsService, eventEmitter) {
  9244. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  9245. this.stream = stream;
  9246. this.intervalId = null;
  9247. this.intervalMilis = interval;
  9248. this.eventEmitter = eventEmitter;
  9249. this.audioLevel = 0;
  9250. this.statisticsService = statisticsService;
  9251. }
  9252. /**
  9253. * Starts the collecting the statistics.
  9254. */
  9255. LocalStatsCollector.prototype.start = function () {
  9256. if (config.disableAudioLevels || !window.AudioContext)
  9257. return;
  9258. var context = new AudioContext();
  9259. var analyser = context.createAnalyser();
  9260. analyser.smoothingTimeConstant = WEBAUDIO_ANALIZER_SMOOTING_TIME;
  9261. analyser.fftSize = WEBAUDIO_ANALIZER_FFT_SIZE;
  9262. var source = context.createMediaStreamSource(this.stream);
  9263. source.connect(analyser);
  9264. var self = this;
  9265. this.intervalId = setInterval(
  9266. function () {
  9267. var array = new Uint8Array(analyser.frequencyBinCount);
  9268. analyser.getByteTimeDomainData(array);
  9269. var audioLevel = timeDomainDataToAudioLevel(array);
  9270. if(audioLevel != self.audioLevel) {
  9271. self.audioLevel = animateLevel(audioLevel, self.audioLevel);
  9272. self.eventEmitter.emit(
  9273. "statistics.audioLevel",
  9274. self.statisticsService.LOCAL_JID,
  9275. self.audioLevel);
  9276. }
  9277. },
  9278. this.intervalMilis
  9279. );
  9280. };
  9281. /**
  9282. * Stops collecting the statistics.
  9283. */
  9284. LocalStatsCollector.prototype.stop = function () {
  9285. if (this.intervalId) {
  9286. clearInterval(this.intervalId);
  9287. this.intervalId = null;
  9288. }
  9289. };
  9290. module.exports = LocalStatsCollector;
  9291. },{}],44:[function(require,module,exports){
  9292. /* global ssrc2jid */
  9293. /* jshint -W117 */
  9294. var RTCBrowserType = require("../../service/RTC/RTCBrowserType");
  9295. /**
  9296. * Calculates packet lost percent using the number of lost packets and the
  9297. * number of all packet.
  9298. * @param lostPackets the number of lost packets
  9299. * @param totalPackets the number of all packets.
  9300. * @returns {number} packet loss percent
  9301. */
  9302. function calculatePacketLoss(lostPackets, totalPackets) {
  9303. if(!totalPackets || totalPackets <= 0 || !lostPackets || lostPackets <= 0)
  9304. return 0;
  9305. return Math.round((lostPackets/totalPackets)*100);
  9306. }
  9307. function getStatValue(item, name) {
  9308. if(!keyMap[APP.RTC.getBrowserType()][name])
  9309. throw "The property isn't supported!";
  9310. var key = keyMap[APP.RTC.getBrowserType()][name];
  9311. return APP.RTC.getBrowserType() == RTCBrowserType.RTC_BROWSER_CHROME? item.stat(key) : item[key];
  9312. }
  9313. /**
  9314. * Peer statistics data holder.
  9315. * @constructor
  9316. */
  9317. function PeerStats()
  9318. {
  9319. this.ssrc2Loss = {};
  9320. this.ssrc2AudioLevel = {};
  9321. this.ssrc2bitrate = {};
  9322. this.ssrc2resolution = {};
  9323. }
  9324. /**
  9325. * The bandwidth
  9326. * @type {{}}
  9327. */
  9328. PeerStats.bandwidth = {};
  9329. /**
  9330. * The bit rate
  9331. * @type {{}}
  9332. */
  9333. PeerStats.bitrate = {};
  9334. /**
  9335. * The packet loss rate
  9336. * @type {{}}
  9337. */
  9338. PeerStats.packetLoss = null;
  9339. /**
  9340. * Sets packets loss rate for given <tt>ssrc</tt> that blong to the peer
  9341. * represented by this instance.
  9342. * @param ssrc audio or video RTP stream SSRC.
  9343. * @param lossRate new packet loss rate value to be set.
  9344. */
  9345. PeerStats.prototype.setSsrcLoss = function (ssrc, lossRate)
  9346. {
  9347. this.ssrc2Loss[ssrc] = lossRate;
  9348. };
  9349. /**
  9350. * Sets resolution for given <tt>ssrc</tt> that belong to the peer
  9351. * represented by this instance.
  9352. * @param ssrc audio or video RTP stream SSRC.
  9353. * @param resolution new resolution value to be set.
  9354. */
  9355. PeerStats.prototype.setSsrcResolution = function (ssrc, resolution)
  9356. {
  9357. if(resolution === null && this.ssrc2resolution[ssrc])
  9358. {
  9359. delete this.ssrc2resolution[ssrc];
  9360. }
  9361. else if(resolution !== null)
  9362. this.ssrc2resolution[ssrc] = resolution;
  9363. };
  9364. /**
  9365. * Sets the bit rate for given <tt>ssrc</tt> that blong to the peer
  9366. * represented by this instance.
  9367. * @param ssrc audio or video RTP stream SSRC.
  9368. * @param bitrate new bitrate value to be set.
  9369. */
  9370. PeerStats.prototype.setSsrcBitrate = function (ssrc, bitrate)
  9371. {
  9372. if(this.ssrc2bitrate[ssrc])
  9373. {
  9374. this.ssrc2bitrate[ssrc].download += bitrate.download;
  9375. this.ssrc2bitrate[ssrc].upload += bitrate.upload;
  9376. }
  9377. else {
  9378. this.ssrc2bitrate[ssrc] = bitrate;
  9379. }
  9380. };
  9381. /**
  9382. * Sets new audio level(input or output) for given <tt>ssrc</tt> that identifies
  9383. * the stream which belongs to the peer represented by this instance.
  9384. * @param ssrc RTP stream SSRC for which current audio level value will be
  9385. * updated.
  9386. * @param audioLevel the new audio level value to be set. Value is truncated to
  9387. * fit the range from 0 to 1.
  9388. */
  9389. PeerStats.prototype.setSsrcAudioLevel = function (ssrc, audioLevel)
  9390. {
  9391. // Range limit 0 - 1
  9392. this.ssrc2AudioLevel[ssrc] = formatAudioLevel(audioLevel);
  9393. };
  9394. function formatAudioLevel(audioLevel) {
  9395. return Math.min(Math.max(audioLevel, 0), 1);
  9396. }
  9397. /**
  9398. * Array with the transport information.
  9399. * @type {Array}
  9400. */
  9401. PeerStats.transport = [];
  9402. /**
  9403. * <tt>StatsCollector</tt> registers for stats updates of given
  9404. * <tt>peerconnection</tt> in given <tt>interval</tt>. On each update particular
  9405. * stats are extracted and put in {@link PeerStats} objects. Once the processing
  9406. * is done <tt>audioLevelsUpdateCallback</tt> is called with <tt>this</tt>
  9407. * instance as an event source.
  9408. *
  9409. * @param peerconnection webRTC peer connection object.
  9410. * @param interval stats refresh interval given in ms.
  9411. * @param {function(StatsCollector)} audioLevelsUpdateCallback the callback
  9412. * called on stats update.
  9413. * @constructor
  9414. */
  9415. function StatsCollector(peerconnection, audioLevelsInterval, statsInterval, eventEmitter)
  9416. {
  9417. this.peerconnection = peerconnection;
  9418. this.baselineAudioLevelsReport = null;
  9419. this.currentAudioLevelsReport = null;
  9420. this.currentStatsReport = null;
  9421. this.baselineStatsReport = null;
  9422. this.audioLevelsIntervalId = null;
  9423. this.eventEmitter = eventEmitter;
  9424. /**
  9425. * Gather PeerConnection stats once every this many milliseconds.
  9426. */
  9427. this.GATHER_INTERVAL = 15000;
  9428. /**
  9429. * Log stats via the focus once every this many milliseconds.
  9430. */
  9431. this.LOG_INTERVAL = 60000;
  9432. /**
  9433. * Gather stats and store them in this.statsToBeLogged.
  9434. */
  9435. this.gatherStatsIntervalId = null;
  9436. /**
  9437. * Send the stats already saved in this.statsToBeLogged to be logged via
  9438. * the focus.
  9439. */
  9440. this.logStatsIntervalId = null;
  9441. /**
  9442. * Stores the statistics which will be send to the focus to be logged.
  9443. */
  9444. this.statsToBeLogged =
  9445. {
  9446. timestamps: [],
  9447. stats: {}
  9448. };
  9449. // Updates stats interval
  9450. this.audioLevelsIntervalMilis = audioLevelsInterval;
  9451. this.statsIntervalId = null;
  9452. this.statsIntervalMilis = statsInterval;
  9453. // Map of jids to PeerStats
  9454. this.jid2stats = {};
  9455. }
  9456. module.exports = StatsCollector;
  9457. /**
  9458. * Stops stats updates.
  9459. */
  9460. StatsCollector.prototype.stop = function () {
  9461. if (this.audioLevelsIntervalId) {
  9462. clearInterval(this.audioLevelsIntervalId);
  9463. this.audioLevelsIntervalId = null;
  9464. }
  9465. if (this.statsIntervalId)
  9466. {
  9467. clearInterval(this.statsIntervalId);
  9468. this.statsIntervalId = null;
  9469. }
  9470. if(this.logStatsIntervalId)
  9471. {
  9472. clearInterval(this.logStatsIntervalId);
  9473. this.logStatsIntervalId = null;
  9474. }
  9475. if(this.gatherStatsIntervalId)
  9476. {
  9477. clearInterval(this.gatherStatsIntervalId);
  9478. this.gatherStatsIntervalId = null;
  9479. }
  9480. };
  9481. /**
  9482. * Callback passed to <tt>getStats</tt> method.
  9483. * @param error an error that occurred on <tt>getStats</tt> call.
  9484. */
  9485. StatsCollector.prototype.errorCallback = function (error)
  9486. {
  9487. console.error("Get stats error", error);
  9488. this.stop();
  9489. };
  9490. /**
  9491. * Starts stats updates.
  9492. */
  9493. StatsCollector.prototype.start = function ()
  9494. {
  9495. var self = this;
  9496. if(!config.disableAudioLevels) {
  9497. console.debug("set audio levels interval");
  9498. this.audioLevelsIntervalId = setInterval(
  9499. function () {
  9500. // Interval updates
  9501. self.peerconnection.getStats(
  9502. function (report) {
  9503. var results = null;
  9504. if (!report || !report.result ||
  9505. typeof report.result != 'function') {
  9506. results = report;
  9507. }
  9508. else {
  9509. results = report.result();
  9510. }
  9511. //console.error("Got interval report", results);
  9512. self.currentAudioLevelsReport = results;
  9513. self.processAudioLevelReport();
  9514. self.baselineAudioLevelsReport =
  9515. self.currentAudioLevelsReport;
  9516. },
  9517. self.errorCallback
  9518. );
  9519. },
  9520. self.audioLevelsIntervalMilis
  9521. );
  9522. }
  9523. if(!config.disableStats) {
  9524. console.debug("set stats interval");
  9525. this.statsIntervalId = setInterval(
  9526. function () {
  9527. // Interval updates
  9528. self.peerconnection.getStats(
  9529. function (report) {
  9530. var results = null;
  9531. if (!report || !report.result ||
  9532. typeof report.result != 'function') {
  9533. //firefox
  9534. results = report;
  9535. }
  9536. else {
  9537. //chrome
  9538. results = report.result();
  9539. }
  9540. //console.error("Got interval report", results);
  9541. self.currentStatsReport = results;
  9542. try {
  9543. self.processStatsReport();
  9544. }
  9545. catch (e) {
  9546. console.error("Unsupported key:" + e, e);
  9547. }
  9548. self.baselineStatsReport = self.currentStatsReport;
  9549. },
  9550. self.errorCallback
  9551. );
  9552. },
  9553. self.statsIntervalMilis
  9554. );
  9555. }
  9556. if (config.logStats) {
  9557. this.gatherStatsIntervalId = setInterval(
  9558. function () {
  9559. self.peerconnection.getStats(
  9560. function (report) {
  9561. self.addStatsToBeLogged(report.result());
  9562. },
  9563. function () {
  9564. }
  9565. );
  9566. },
  9567. this.GATHER_INTERVAL
  9568. );
  9569. this.logStatsIntervalId = setInterval(
  9570. function() { self.logStats(); },
  9571. this.LOG_INTERVAL);
  9572. }
  9573. };
  9574. /**
  9575. * Checks whether a certain record should be included in the logged statistics.
  9576. */
  9577. function acceptStat(reportId, reportType, statName) {
  9578. if (reportType == "googCandidatePair" && statName == "googChannelId")
  9579. return false;
  9580. if (reportType == "ssrc") {
  9581. if (statName == "googTrackId" ||
  9582. statName == "transportId" ||
  9583. statName == "ssrc")
  9584. return false;
  9585. }
  9586. return true;
  9587. }
  9588. /**
  9589. * Checks whether a certain record should be included in the logged statistics.
  9590. */
  9591. function acceptReport(id, type) {
  9592. if (id.substring(0, 15) == "googCertificate" ||
  9593. id.substring(0, 9) == "googTrack" ||
  9594. id.substring(0, 20) == "googLibjingleSession")
  9595. return false;
  9596. if (type == "googComponent")
  9597. return false;
  9598. return true;
  9599. }
  9600. /**
  9601. * Converts the stats to the format used for logging, and saves the data in
  9602. * this.statsToBeLogged.
  9603. * @param reports Reports as given by webkitRTCPerConnection.getStats.
  9604. */
  9605. StatsCollector.prototype.addStatsToBeLogged = function (reports) {
  9606. var self = this;
  9607. var num_records = this.statsToBeLogged.timestamps.length;
  9608. this.statsToBeLogged.timestamps.push(new Date().getTime());
  9609. reports.map(function (report) {
  9610. if (!acceptReport(report.id, report.type))
  9611. return;
  9612. var stat = self.statsToBeLogged.stats[report.id];
  9613. if (!stat) {
  9614. stat = self.statsToBeLogged.stats[report.id] = {};
  9615. }
  9616. stat.type = report.type;
  9617. report.names().map(function (name) {
  9618. if (!acceptStat(report.id, report.type, name))
  9619. return;
  9620. var values = stat[name];
  9621. if (!values) {
  9622. values = stat[name] = [];
  9623. }
  9624. while (values.length < num_records) {
  9625. values.push(null);
  9626. }
  9627. values.push(report.stat(name));
  9628. });
  9629. });
  9630. };
  9631. StatsCollector.prototype.logStats = function () {
  9632. if(!APP.xmpp.sendLogs(this.statsToBeLogged))
  9633. return;
  9634. // Reset the stats
  9635. this.statsToBeLogged.stats = {};
  9636. this.statsToBeLogged.timestamps = [];
  9637. };
  9638. var keyMap = {};
  9639. keyMap[RTCBrowserType.RTC_BROWSER_FIREFOX] = {
  9640. "ssrc": "ssrc",
  9641. "packetsReceived": "packetsReceived",
  9642. "packetsLost": "packetsLost",
  9643. "packetsSent": "packetsSent",
  9644. "bytesReceived": "bytesReceived",
  9645. "bytesSent": "bytesSent"
  9646. };
  9647. keyMap[RTCBrowserType.RTC_BROWSER_CHROME] = {
  9648. "receiveBandwidth": "googAvailableReceiveBandwidth",
  9649. "sendBandwidth": "googAvailableSendBandwidth",
  9650. "remoteAddress": "googRemoteAddress",
  9651. "transportType": "googTransportType",
  9652. "localAddress": "googLocalAddress",
  9653. "activeConnection": "googActiveConnection",
  9654. "ssrc": "ssrc",
  9655. "packetsReceived": "packetsReceived",
  9656. "packetsSent": "packetsSent",
  9657. "packetsLost": "packetsLost",
  9658. "bytesReceived": "bytesReceived",
  9659. "bytesSent": "bytesSent",
  9660. "googFrameHeightReceived": "googFrameHeightReceived",
  9661. "googFrameWidthReceived": "googFrameWidthReceived",
  9662. "googFrameHeightSent": "googFrameHeightSent",
  9663. "googFrameWidthSent": "googFrameWidthSent",
  9664. "audioInputLevel": "audioInputLevel",
  9665. "audioOutputLevel": "audioOutputLevel"
  9666. };
  9667. /**
  9668. * Stats processing logic.
  9669. */
  9670. StatsCollector.prototype.processStatsReport = function () {
  9671. if (!this.baselineStatsReport) {
  9672. return;
  9673. }
  9674. for (var idx in this.currentStatsReport) {
  9675. var now = this.currentStatsReport[idx];
  9676. try {
  9677. if (getStatValue(now, 'receiveBandwidth') ||
  9678. getStatValue(now, 'sendBandwidth')) {
  9679. PeerStats.bandwidth = {
  9680. "download": Math.round(
  9681. (getStatValue(now, 'receiveBandwidth')) / 1000),
  9682. "upload": Math.round(
  9683. (getStatValue(now, 'sendBandwidth')) / 1000)
  9684. };
  9685. }
  9686. }
  9687. catch(e){/*not supported*/}
  9688. if(now.type == 'googCandidatePair')
  9689. {
  9690. var ip, type, localIP, active;
  9691. try {
  9692. ip = getStatValue(now, 'remoteAddress');
  9693. type = getStatValue(now, "transportType");
  9694. localIP = getStatValue(now, "localAddress");
  9695. active = getStatValue(now, "activeConnection");
  9696. }
  9697. catch(e){/*not supported*/}
  9698. if(!ip || !type || !localIP || active != "true")
  9699. continue;
  9700. var addressSaved = false;
  9701. for(var i = 0; i < PeerStats.transport.length; i++)
  9702. {
  9703. if(PeerStats.transport[i].ip == ip &&
  9704. PeerStats.transport[i].type == type &&
  9705. PeerStats.transport[i].localip == localIP)
  9706. {
  9707. addressSaved = true;
  9708. }
  9709. }
  9710. if(addressSaved)
  9711. continue;
  9712. PeerStats.transport.push({localip: localIP, ip: ip, type: type});
  9713. continue;
  9714. }
  9715. if(now.type == "candidatepair")
  9716. {
  9717. if(now.state == "succeeded")
  9718. continue;
  9719. var local = this.currentStatsReport[now.localCandidateId];
  9720. var remote = this.currentStatsReport[now.remoteCandidateId];
  9721. PeerStats.transport.push({localip: local.ipAddress + ":" + local.portNumber,
  9722. ip: remote.ipAddress + ":" + remote.portNumber, type: local.transport});
  9723. }
  9724. if (now.type != 'ssrc' && now.type != "outboundrtp" &&
  9725. now.type != "inboundrtp") {
  9726. continue;
  9727. }
  9728. var before = this.baselineStatsReport[idx];
  9729. if (!before) {
  9730. console.warn(getStatValue(now, 'ssrc') + ' not enough data');
  9731. continue;
  9732. }
  9733. var ssrc = getStatValue(now, 'ssrc');
  9734. if(!ssrc)
  9735. continue;
  9736. var jid = APP.xmpp.getJidFromSSRC(ssrc);
  9737. if (!jid && (Date.now() - now.timestamp) < 3000) {
  9738. console.warn("No jid for ssrc: " + ssrc);
  9739. continue;
  9740. }
  9741. var jidStats = this.jid2stats[jid];
  9742. if (!jidStats) {
  9743. jidStats = new PeerStats();
  9744. this.jid2stats[jid] = jidStats;
  9745. }
  9746. var isDownloadStream = true;
  9747. var key = 'packetsReceived';
  9748. if (!getStatValue(now, key))
  9749. {
  9750. isDownloadStream = false;
  9751. key = 'packetsSent';
  9752. if (!getStatValue(now, key))
  9753. {
  9754. console.warn("No packetsReceived nor packetSent stat found");
  9755. continue;
  9756. }
  9757. }
  9758. var packetsNow = getStatValue(now, key);
  9759. if(!packetsNow || packetsNow < 0)
  9760. packetsNow = 0;
  9761. var packetsBefore = getStatValue(before, key);
  9762. if(!packetsBefore || packetsBefore < 0)
  9763. packetsBefore = 0;
  9764. var packetRate = packetsNow - packetsBefore;
  9765. if(!packetRate || packetRate < 0)
  9766. packetRate = 0;
  9767. var currentLoss = getStatValue(now, 'packetsLost');
  9768. if(!currentLoss || currentLoss < 0)
  9769. currentLoss = 0;
  9770. var previousLoss = getStatValue(before, 'packetsLost');
  9771. if(!previousLoss || previousLoss < 0)
  9772. previousLoss = 0;
  9773. var lossRate = currentLoss - previousLoss;
  9774. if(!lossRate || lossRate < 0)
  9775. lossRate = 0;
  9776. var packetsTotal = (packetRate + lossRate);
  9777. jidStats.setSsrcLoss(ssrc,
  9778. {"packetsTotal": packetsTotal,
  9779. "packetsLost": lossRate,
  9780. "isDownloadStream": isDownloadStream});
  9781. var bytesReceived = 0, bytesSent = 0;
  9782. if(getStatValue(now, "bytesReceived"))
  9783. {
  9784. bytesReceived = getStatValue(now, "bytesReceived") -
  9785. getStatValue(before, "bytesReceived");
  9786. }
  9787. if(getStatValue(now, "bytesSent"))
  9788. {
  9789. bytesSent = getStatValue(now, "bytesSent") -
  9790. getStatValue(before, "bytesSent");
  9791. }
  9792. var time = Math.round((now.timestamp - before.timestamp) / 1000);
  9793. if(bytesReceived <= 0 || time <= 0)
  9794. {
  9795. bytesReceived = 0;
  9796. }
  9797. else
  9798. {
  9799. bytesReceived = Math.round(((bytesReceived * 8) / time) / 1000);
  9800. }
  9801. if(bytesSent <= 0 || time <= 0)
  9802. {
  9803. bytesSent = 0;
  9804. }
  9805. else
  9806. {
  9807. bytesSent = Math.round(((bytesSent * 8) / time) / 1000);
  9808. }
  9809. jidStats.setSsrcBitrate(ssrc, {
  9810. "download": bytesReceived,
  9811. "upload": bytesSent});
  9812. var resolution = {height: null, width: null};
  9813. try {
  9814. if (getStatValue(now, "googFrameHeightReceived") &&
  9815. getStatValue(now, "googFrameWidthReceived")) {
  9816. resolution.height = getStatValue(now, "googFrameHeightReceived");
  9817. resolution.width = getStatValue(now, "googFrameWidthReceived");
  9818. }
  9819. else if (getStatValue(now, "googFrameHeightSent") &&
  9820. getStatValue(now, "googFrameWidthSent")) {
  9821. resolution.height = getStatValue(now, "googFrameHeightSent");
  9822. resolution.width = getStatValue(now, "googFrameWidthSent");
  9823. }
  9824. }
  9825. catch(e){/*not supported*/}
  9826. if(resolution.height && resolution.width)
  9827. {
  9828. jidStats.setSsrcResolution(ssrc, resolution);
  9829. }
  9830. else
  9831. {
  9832. jidStats.setSsrcResolution(ssrc, null);
  9833. }
  9834. }
  9835. var self = this;
  9836. // Jid stats
  9837. var totalPackets = {download: 0, upload: 0};
  9838. var lostPackets = {download: 0, upload: 0};
  9839. var bitrateDownload = 0;
  9840. var bitrateUpload = 0;
  9841. var resolutions = {};
  9842. Object.keys(this.jid2stats).forEach(
  9843. function (jid)
  9844. {
  9845. Object.keys(self.jid2stats[jid].ssrc2Loss).forEach(
  9846. function (ssrc)
  9847. {
  9848. var type = "upload";
  9849. if(self.jid2stats[jid].ssrc2Loss[ssrc].isDownloadStream)
  9850. type = "download";
  9851. totalPackets[type] +=
  9852. self.jid2stats[jid].ssrc2Loss[ssrc].packetsTotal;
  9853. lostPackets[type] +=
  9854. self.jid2stats[jid].ssrc2Loss[ssrc].packetsLost;
  9855. }
  9856. );
  9857. Object.keys(self.jid2stats[jid].ssrc2bitrate).forEach(
  9858. function (ssrc) {
  9859. bitrateDownload +=
  9860. self.jid2stats[jid].ssrc2bitrate[ssrc].download;
  9861. bitrateUpload +=
  9862. self.jid2stats[jid].ssrc2bitrate[ssrc].upload;
  9863. delete self.jid2stats[jid].ssrc2bitrate[ssrc];
  9864. }
  9865. );
  9866. resolutions[jid] = self.jid2stats[jid].ssrc2resolution;
  9867. }
  9868. );
  9869. PeerStats.bitrate = {"upload": bitrateUpload, "download": bitrateDownload};
  9870. PeerStats.packetLoss = {
  9871. total:
  9872. calculatePacketLoss(lostPackets.download + lostPackets.upload,
  9873. totalPackets.download + totalPackets.upload),
  9874. download:
  9875. calculatePacketLoss(lostPackets.download, totalPackets.download),
  9876. upload:
  9877. calculatePacketLoss(lostPackets.upload, totalPackets.upload)
  9878. };
  9879. this.eventEmitter.emit("statistics.connectionstats",
  9880. {
  9881. "bitrate": PeerStats.bitrate,
  9882. "packetLoss": PeerStats.packetLoss,
  9883. "bandwidth": PeerStats.bandwidth,
  9884. "resolution": resolutions,
  9885. "transport": PeerStats.transport
  9886. });
  9887. PeerStats.transport = [];
  9888. };
  9889. /**
  9890. * Stats processing logic.
  9891. */
  9892. StatsCollector.prototype.processAudioLevelReport = function ()
  9893. {
  9894. if (!this.baselineAudioLevelsReport)
  9895. {
  9896. return;
  9897. }
  9898. for (var idx in this.currentAudioLevelsReport)
  9899. {
  9900. var now = this.currentAudioLevelsReport[idx];
  9901. if (now.type != 'ssrc')
  9902. {
  9903. continue;
  9904. }
  9905. var before = this.baselineAudioLevelsReport[idx];
  9906. if (!before)
  9907. {
  9908. console.warn(getStatValue(now, 'ssrc') + ' not enough data');
  9909. continue;
  9910. }
  9911. var ssrc = getStatValue(now, 'ssrc');
  9912. var jid = APP.xmpp.getJidFromSSRC(ssrc);
  9913. if (!jid && (Date.now() - now.timestamp) < 3000)
  9914. {
  9915. console.warn("No jid for ssrc: " + ssrc);
  9916. continue;
  9917. }
  9918. var jidStats = this.jid2stats[jid];
  9919. if (!jidStats)
  9920. {
  9921. jidStats = new PeerStats();
  9922. this.jid2stats[jid] = jidStats;
  9923. }
  9924. // Audio level
  9925. var audioLevel = null;
  9926. try {
  9927. audioLevel = getStatValue(now, 'audioInputLevel');
  9928. if (!audioLevel)
  9929. audioLevel = getStatValue(now, 'audioOutputLevel');
  9930. }
  9931. catch(e) {/*not supported*/
  9932. console.warn("Audio Levels are not available in the statistics.");
  9933. clearInterval(this.audioLevelsIntervalId);
  9934. return;
  9935. }
  9936. if (audioLevel)
  9937. {
  9938. // TODO: can't find specs about what this value really is,
  9939. // but it seems to vary between 0 and around 32k.
  9940. audioLevel = audioLevel / 32767;
  9941. jidStats.setSsrcAudioLevel(ssrc, audioLevel);
  9942. if(jid != APP.xmpp.myJid())
  9943. this.eventEmitter.emit("statistics.audioLevel", jid, audioLevel);
  9944. }
  9945. }
  9946. };
  9947. },{"../../service/RTC/RTCBrowserType":87}],45:[function(require,module,exports){
  9948. /**
  9949. * Created by hristo on 8/4/14.
  9950. */
  9951. var LocalStats = require("./LocalStatsCollector.js");
  9952. var RTPStats = require("./RTPStatsCollector.js");
  9953. var EventEmitter = require("events");
  9954. var StreamEventTypes = require("../../service/RTC/StreamEventTypes.js");
  9955. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  9956. var eventEmitter = new EventEmitter();
  9957. var localStats = null;
  9958. var rtpStats = null;
  9959. function stopLocal()
  9960. {
  9961. if(localStats)
  9962. {
  9963. localStats.stop();
  9964. localStats = null;
  9965. }
  9966. }
  9967. function stopRemote()
  9968. {
  9969. if(rtpStats)
  9970. {
  9971. rtpStats.stop();
  9972. eventEmitter.emit("statistics.stop");
  9973. rtpStats = null;
  9974. }
  9975. }
  9976. function startRemoteStats (peerconnection) {
  9977. if(rtpStats)
  9978. {
  9979. rtpStats.stop();
  9980. rtpStats = null;
  9981. }
  9982. rtpStats = new RTPStats(peerconnection, 200, 2000, eventEmitter);
  9983. rtpStats.start();
  9984. }
  9985. function onStreamCreated(stream)
  9986. {
  9987. if(stream.getOriginalStream().getAudioTracks().length === 0)
  9988. return;
  9989. localStats = new LocalStats(stream.getOriginalStream(), 200, statistics,
  9990. eventEmitter);
  9991. localStats.start();
  9992. }
  9993. function onDisposeConference(onUnload) {
  9994. stopRemote();
  9995. if(onUnload) {
  9996. stopLocal();
  9997. eventEmitter.removeAllListeners();
  9998. }
  9999. }
  10000. var statistics =
  10001. {
  10002. /**
  10003. * Indicates that this audio level is for local jid.
  10004. * @type {string}
  10005. */
  10006. LOCAL_JID: 'local',
  10007. addAudioLevelListener: function(listener)
  10008. {
  10009. eventEmitter.on("statistics.audioLevel", listener);
  10010. },
  10011. removeAudioLevelListener: function(listener)
  10012. {
  10013. eventEmitter.removeListener("statistics.audioLevel", listener);
  10014. },
  10015. addConnectionStatsListener: function(listener)
  10016. {
  10017. eventEmitter.on("statistics.connectionstats", listener);
  10018. },
  10019. removeConnectionStatsListener: function(listener)
  10020. {
  10021. eventEmitter.removeListener("statistics.connectionstats", listener);
  10022. },
  10023. addRemoteStatsStopListener: function(listener)
  10024. {
  10025. eventEmitter.on("statistics.stop", listener);
  10026. },
  10027. removeRemoteStatsStopListener: function(listener)
  10028. {
  10029. eventEmitter.removeListener("statistics.stop", listener);
  10030. },
  10031. stop: function () {
  10032. stopLocal();
  10033. stopRemote();
  10034. if(eventEmitter)
  10035. {
  10036. eventEmitter.removeAllListeners();
  10037. }
  10038. },
  10039. stopRemoteStatistics: function()
  10040. {
  10041. stopRemote();
  10042. },
  10043. start: function () {
  10044. APP.RTC.addStreamListener(onStreamCreated,
  10045. StreamEventTypes.EVENT_TYPE_LOCAL_CREATED);
  10046. APP.xmpp.addListener(XMPPEvents.DISPOSE_CONFERENCE, onDisposeConference);
  10047. APP.xmpp.addListener(XMPPEvents.CALL_INCOMING, function (event) {
  10048. startRemoteStats(event.peerconnection);
  10049. });
  10050. }
  10051. };
  10052. module.exports = statistics;
  10053. },{"../../service/RTC/StreamEventTypes.js":90,"../../service/xmpp/XMPPEvents":96,"./LocalStatsCollector.js":43,"./RTPStatsCollector.js":44,"events":97}],46:[function(require,module,exports){
  10054. var i18n = require("i18next-client");
  10055. var languages = require("../../service/translation/languages");
  10056. var Settings = require("../settings/Settings");
  10057. var DEFAULT_LANG = languages.EN;
  10058. i18n.addPostProcessor("resolveAppName", function(value, key, options) {
  10059. return value.replace("__app__", interfaceConfig.APP_NAME);
  10060. });
  10061. var defaultOptions = {
  10062. detectLngQS: "lang",
  10063. useCookie: false,
  10064. fallbackLng: DEFAULT_LANG,
  10065. load: "unspecific",
  10066. resGetPath: 'lang/__ns__-__lng__.json',
  10067. ns: {
  10068. namespaces: ['main', 'languages'],
  10069. defaultNs: 'main'
  10070. },
  10071. lngWhitelist : languages.getLanguages(),
  10072. fallbackOnNull: true,
  10073. fallbackOnEmpty: true,
  10074. useDataAttrOptions: true,
  10075. defaultValueFromContent: false,
  10076. app: interfaceConfig.APP_NAME,
  10077. getAsync: false,
  10078. defaultValueFromContent: false,
  10079. customLoad: function(lng, ns, options, done) {
  10080. var resPath = "lang/__ns__-__lng__.json";
  10081. if(lng === languages.EN)
  10082. resPath = "lang/__ns__.json";
  10083. var url = i18n.functions.applyReplacement(resPath, { lng: lng, ns: ns });
  10084. i18n.functions.ajax({
  10085. url: url,
  10086. success: function(data, status, xhr) {
  10087. i18n.functions.log('loaded: ' + url);
  10088. done(null, data);
  10089. },
  10090. error : function(xhr, status, error) {
  10091. if ((status && status == 200) ||
  10092. (xhr && xhr.status && xhr.status == 200)) {
  10093. // file loaded but invalid json, stop waste time !
  10094. i18n.functions.error('There is a typo in: ' + url);
  10095. } else if ((status && status == 404) ||
  10096. (xhr && xhr.status && xhr.status == 404)) {
  10097. i18n.functions.log('Does not exist: ' + url);
  10098. } else {
  10099. var theStatus = status ? status :
  10100. ((xhr && xhr.status) ? xhr.status : null);
  10101. i18n.functions.log(theStatus + ' when loading ' + url);
  10102. }
  10103. done(error, {});
  10104. },
  10105. dataType: "json",
  10106. async : options.getAsync
  10107. });
  10108. }
  10109. // options for caching
  10110. // useLocalStorage: true,
  10111. // localStorageExpirationTime: 86400000 // in ms, default 1 week
  10112. };
  10113. function initCompleted(t)
  10114. {
  10115. $("[data-i18n]").i18n();
  10116. }
  10117. function checkForParameter() {
  10118. var query = window.location.search.substring(1);
  10119. var vars = query.split("&");
  10120. for (var i=0;i<vars.length;i++) {
  10121. var pair = vars[i].split("=");
  10122. if(pair[0] == "lang")
  10123. {
  10124. return pair[1];
  10125. }
  10126. }
  10127. return null;
  10128. }
  10129. module.exports = {
  10130. init: function (lang) {
  10131. var options = defaultOptions;
  10132. if(!lang)
  10133. {
  10134. lang = checkForParameter();
  10135. if(!lang)
  10136. {
  10137. var settings = Settings.getSettings();
  10138. if(settings)
  10139. lang = settings.language;
  10140. }
  10141. }
  10142. if(lang) {
  10143. options.lng = lang;
  10144. }
  10145. i18n.init(options, initCompleted);
  10146. },
  10147. translateString: function (key, options) {
  10148. return i18n.t(key, options);
  10149. },
  10150. setLanguage: function (lang) {
  10151. if(!lang)
  10152. lang = DEFAULT_LANG;
  10153. i18n.setLng(lang, defaultOptions, initCompleted);
  10154. },
  10155. getCurrentLanguage: function () {
  10156. return i18n.lng();
  10157. },
  10158. translateElement: function (selector) {
  10159. selector.i18n();
  10160. },
  10161. generateTranslatonHTML: function (key, options) {
  10162. var str = "<span data-i18n=\"" + key + "\"";
  10163. if(options)
  10164. {
  10165. str += " data-i18n-options=\"" + JSON.stringify(options) + "\"";
  10166. }
  10167. str += ">";
  10168. str += this.translateString(key, options);
  10169. str += "</span>";
  10170. return str;
  10171. }
  10172. };
  10173. },{"../../service/translation/languages":95,"../settings/Settings":37,"i18next-client":61}],47:[function(require,module,exports){
  10174. /* jshint -W117 */
  10175. var TraceablePeerConnection = require("./TraceablePeerConnection");
  10176. var SDPDiffer = require("./SDPDiffer");
  10177. var SDPUtil = require("./SDPUtil");
  10178. var SDP = require("./SDP");
  10179. var RTCBrowserType = require("../../service/RTC/RTCBrowserType");
  10180. // Jingle stuff
  10181. function JingleSession(me, sid, connection, service) {
  10182. this.me = me;
  10183. this.sid = sid;
  10184. this.connection = connection;
  10185. this.initiator = null;
  10186. this.responder = null;
  10187. this.isInitiator = null;
  10188. this.peerjid = null;
  10189. this.state = null;
  10190. this.localSDP = null;
  10191. this.remoteSDP = null;
  10192. this.relayedStreams = [];
  10193. this.startTime = null;
  10194. this.stopTime = null;
  10195. this.media_constraints = null;
  10196. this.pc_constraints = null;
  10197. this.ice_config = {};
  10198. this.drip_container = [];
  10199. this.service = service;
  10200. this.usetrickle = true;
  10201. this.usepranswer = false; // early transport warmup -- mind you, this might fail. depends on webrtc issue 1718
  10202. this.usedrip = false; // dripping is sending trickle candidates not one-by-one
  10203. this.hadstuncandidate = false;
  10204. this.hadturncandidate = false;
  10205. this.lasticecandidate = false;
  10206. this.statsinterval = null;
  10207. this.reason = null;
  10208. this.addssrc = [];
  10209. this.removessrc = [];
  10210. this.pendingop = null;
  10211. this.switchstreams = false;
  10212. this.wait = true;
  10213. this.localStreamsSSRC = null;
  10214. /**
  10215. * The indicator which determines whether the (local) video has been muted
  10216. * in response to a user command in contrast to an automatic decision made
  10217. * by the application logic.
  10218. */
  10219. this.videoMuteByUser = false;
  10220. }
  10221. //TODO: this array must be removed when firefox implement multistream support
  10222. JingleSession.notReceivedSSRCs = [];
  10223. JingleSession.prototype.initiate = function (peerjid, isInitiator) {
  10224. var self = this;
  10225. if (this.state !== null) {
  10226. console.error('attempt to initiate on session ' + this.sid +
  10227. 'in state ' + this.state);
  10228. return;
  10229. }
  10230. this.isInitiator = isInitiator;
  10231. this.state = 'pending';
  10232. this.initiator = isInitiator ? this.me : peerjid;
  10233. this.responder = !isInitiator ? this.me : peerjid;
  10234. this.peerjid = peerjid;
  10235. this.hadstuncandidate = false;
  10236. this.hadturncandidate = false;
  10237. this.lasticecandidate = false;
  10238. this.peerconnection
  10239. = new TraceablePeerConnection(
  10240. this.connection.jingle.ice_config,
  10241. this.connection.jingle.pc_constraints );
  10242. this.peerconnection.onicecandidate = function (event) {
  10243. self.sendIceCandidate(event.candidate);
  10244. };
  10245. this.peerconnection.onaddstream = function (event) {
  10246. console.log("REMOTE STREAM ADDED: " + event.stream + " - " + event.stream.id);
  10247. self.remoteStreamAdded(event);
  10248. };
  10249. this.peerconnection.onremovestream = function (event) {
  10250. // Remove the stream from remoteStreams
  10251. // FIXME: remotestreamremoved.jingle not defined anywhere(unused)
  10252. $(document).trigger('remotestreamremoved.jingle', [event, self.sid]);
  10253. };
  10254. this.peerconnection.onsignalingstatechange = function (event) {
  10255. if (!(self && self.peerconnection)) return;
  10256. };
  10257. this.peerconnection.oniceconnectionstatechange = function (event) {
  10258. if (!(self && self.peerconnection)) return;
  10259. switch (self.peerconnection.iceConnectionState) {
  10260. case 'connected':
  10261. this.startTime = new Date();
  10262. break;
  10263. case 'disconnected':
  10264. this.stopTime = new Date();
  10265. break;
  10266. }
  10267. onIceConnectionStateChange(self.sid, self);
  10268. };
  10269. // add any local and relayed stream
  10270. APP.RTC.localStreams.forEach(function(stream) {
  10271. self.peerconnection.addStream(stream.getOriginalStream());
  10272. });
  10273. this.relayedStreams.forEach(function(stream) {
  10274. self.peerconnection.addStream(stream);
  10275. });
  10276. };
  10277. function onIceConnectionStateChange(sid, session) {
  10278. switch (session.peerconnection.iceConnectionState) {
  10279. case 'checking':
  10280. session.timeChecking = (new Date()).getTime();
  10281. session.firstconnect = true;
  10282. break;
  10283. case 'completed': // on caller side
  10284. case 'connected':
  10285. if (session.firstconnect) {
  10286. session.firstconnect = false;
  10287. var metadata = {};
  10288. metadata.setupTime
  10289. = (new Date()).getTime() - session.timeChecking;
  10290. session.peerconnection.getStats(function (res) {
  10291. if(res && res.result) {
  10292. res.result().forEach(function (report) {
  10293. if (report.type == 'googCandidatePair' &&
  10294. report.stat('googActiveConnection') == 'true') {
  10295. metadata.localCandidateType
  10296. = report.stat('googLocalCandidateType');
  10297. metadata.remoteCandidateType
  10298. = report.stat('googRemoteCandidateType');
  10299. // log pair as well so we can get nice pie
  10300. // charts
  10301. metadata.candidatePair
  10302. = report.stat('googLocalCandidateType') +
  10303. ';' +
  10304. report.stat('googRemoteCandidateType');
  10305. if (report.stat('googRemoteAddress').indexOf('[') === 0)
  10306. {
  10307. metadata.ipv6 = true;
  10308. }
  10309. }
  10310. });
  10311. }
  10312. });
  10313. }
  10314. break;
  10315. }
  10316. }
  10317. JingleSession.prototype.accept = function () {
  10318. var self = this;
  10319. this.state = 'active';
  10320. var pranswer = this.peerconnection.localDescription;
  10321. if (!pranswer || pranswer.type != 'pranswer') {
  10322. return;
  10323. }
  10324. console.log('going from pranswer to answer');
  10325. if (this.usetrickle) {
  10326. // remove candidates already sent from session-accept
  10327. var lines = SDPUtil.find_lines(pranswer.sdp, 'a=candidate:');
  10328. for (var i = 0; i < lines.length; i++) {
  10329. pranswer.sdp = pranswer.sdp.replace(lines[i] + '\r\n', '');
  10330. }
  10331. }
  10332. while (SDPUtil.find_line(pranswer.sdp, 'a=inactive')) {
  10333. // FIXME: change any inactive to sendrecv or whatever they were originally
  10334. pranswer.sdp = pranswer.sdp.replace('a=inactive', 'a=sendrecv');
  10335. }
  10336. pranswer = APP.simulcast.reverseTransformLocalDescription(pranswer);
  10337. var prsdp = new SDP(pranswer.sdp);
  10338. var accept = $iq({to: this.peerjid,
  10339. type: 'set'})
  10340. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  10341. action: 'session-accept',
  10342. initiator: this.initiator,
  10343. responder: this.responder,
  10344. sid: this.sid });
  10345. prsdp.toJingle(accept, this.initiator == this.me ? 'initiator' : 'responder', this.localStreamsSSRC);
  10346. var sdp = this.peerconnection.localDescription.sdp;
  10347. while (SDPUtil.find_line(sdp, 'a=inactive')) {
  10348. // FIXME: change any inactive to sendrecv or whatever they were originally
  10349. sdp = sdp.replace('a=inactive', 'a=sendrecv');
  10350. }
  10351. var self = this;
  10352. this.peerconnection.setLocalDescription(new RTCSessionDescription({type: 'answer', sdp: sdp}),
  10353. function () {
  10354. //console.log('setLocalDescription success');
  10355. self.setLocalDescription();
  10356. self.connection.sendIQ(accept,
  10357. function () {
  10358. var ack = {};
  10359. ack.source = 'answer';
  10360. $(document).trigger('ack.jingle', [self.sid, ack]);
  10361. },
  10362. function (stanza) {
  10363. var error = ($(stanza).find('error').length) ? {
  10364. code: $(stanza).find('error').attr('code'),
  10365. reason: $(stanza).find('error :first')[0].tagName
  10366. }:{};
  10367. error.source = 'answer';
  10368. JingleSession.onJingleError(self.sid, error);
  10369. },
  10370. 10000);
  10371. },
  10372. function (e) {
  10373. console.error('setLocalDescription failed', e);
  10374. }
  10375. );
  10376. };
  10377. JingleSession.prototype.terminate = function (reason) {
  10378. this.state = 'ended';
  10379. this.reason = reason;
  10380. this.peerconnection.close();
  10381. if (this.statsinterval !== null) {
  10382. window.clearInterval(this.statsinterval);
  10383. this.statsinterval = null;
  10384. }
  10385. };
  10386. JingleSession.prototype.active = function () {
  10387. return this.state == 'active';
  10388. };
  10389. JingleSession.prototype.sendIceCandidate = function (candidate) {
  10390. var self = this;
  10391. if (candidate && !this.lasticecandidate) {
  10392. var ice = SDPUtil.iceparams(this.localSDP.media[candidate.sdpMLineIndex], this.localSDP.session);
  10393. var jcand = SDPUtil.candidateToJingle(candidate.candidate);
  10394. if (!(ice && jcand)) {
  10395. console.error('failed to get ice && jcand');
  10396. return;
  10397. }
  10398. ice.xmlns = 'urn:xmpp:jingle:transports:ice-udp:1';
  10399. if (jcand.type === 'srflx') {
  10400. this.hadstuncandidate = true;
  10401. } else if (jcand.type === 'relay') {
  10402. this.hadturncandidate = true;
  10403. }
  10404. if (this.usetrickle) {
  10405. if (this.usedrip) {
  10406. if (this.drip_container.length === 0) {
  10407. // start 20ms callout
  10408. window.setTimeout(function () {
  10409. if (self.drip_container.length === 0) return;
  10410. self.sendIceCandidates(self.drip_container);
  10411. self.drip_container = [];
  10412. }, 20);
  10413. }
  10414. this.drip_container.push(candidate);
  10415. return;
  10416. } else {
  10417. self.sendIceCandidate([candidate]);
  10418. }
  10419. }
  10420. } else {
  10421. //console.log('sendIceCandidate: last candidate.');
  10422. if (!this.usetrickle) {
  10423. //console.log('should send full offer now...');
  10424. var init = $iq({to: this.peerjid,
  10425. type: 'set'})
  10426. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  10427. action: this.peerconnection.localDescription.type == 'offer' ? 'session-initiate' : 'session-accept',
  10428. initiator: this.initiator,
  10429. sid: this.sid});
  10430. this.localSDP = new SDP(this.peerconnection.localDescription.sdp);
  10431. var self = this;
  10432. var sendJingle = function (ssrc) {
  10433. if(!ssrc)
  10434. ssrc = {};
  10435. self.localSDP.toJingle(init, self.initiator == self.me ? 'initiator' : 'responder', ssrc);
  10436. self.connection.sendIQ(init,
  10437. function () {
  10438. //console.log('session initiate ack');
  10439. var ack = {};
  10440. ack.source = 'offer';
  10441. $(document).trigger('ack.jingle', [self.sid, ack]);
  10442. },
  10443. function (stanza) {
  10444. self.state = 'error';
  10445. self.peerconnection.close();
  10446. var error = ($(stanza).find('error').length) ? {
  10447. code: $(stanza).find('error').attr('code'),
  10448. reason: $(stanza).find('error :first')[0].tagName,
  10449. }:{};
  10450. error.source = 'offer';
  10451. JingleSession.onJingleError(self.sid, error);
  10452. },
  10453. 10000);
  10454. }
  10455. sendJingle();
  10456. }
  10457. this.lasticecandidate = true;
  10458. console.log('Have we encountered any srflx candidates? ' + this.hadstuncandidate);
  10459. console.log('Have we encountered any relay candidates? ' + this.hadturncandidate);
  10460. if (!(this.hadstuncandidate || this.hadturncandidate) && this.peerconnection.signalingState != 'closed') {
  10461. $(document).trigger('nostuncandidates.jingle', [this.sid]);
  10462. }
  10463. }
  10464. };
  10465. JingleSession.prototype.sendIceCandidates = function (candidates) {
  10466. console.log('sendIceCandidates', candidates);
  10467. var cand = $iq({to: this.peerjid, type: 'set'})
  10468. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  10469. action: 'transport-info',
  10470. initiator: this.initiator,
  10471. sid: this.sid});
  10472. for (var mid = 0; mid < this.localSDP.media.length; mid++) {
  10473. var cands = candidates.filter(function (el) { return el.sdpMLineIndex == mid; });
  10474. var mline = SDPUtil.parse_mline(this.localSDP.media[mid].split('\r\n')[0]);
  10475. if (cands.length > 0) {
  10476. var ice = SDPUtil.iceparams(this.localSDP.media[mid], this.localSDP.session);
  10477. ice.xmlns = 'urn:xmpp:jingle:transports:ice-udp:1';
  10478. cand.c('content', {creator: this.initiator == this.me ? 'initiator' : 'responder',
  10479. name: (cands[0].sdpMid? cands[0].sdpMid : mline.media)
  10480. }).c('transport', ice);
  10481. for (var i = 0; i < cands.length; i++) {
  10482. cand.c('candidate', SDPUtil.candidateToJingle(cands[i].candidate)).up();
  10483. }
  10484. // add fingerprint
  10485. if (SDPUtil.find_line(this.localSDP.media[mid], 'a=fingerprint:', this.localSDP.session)) {
  10486. var tmp = SDPUtil.parse_fingerprint(SDPUtil.find_line(this.localSDP.media[mid], 'a=fingerprint:', this.localSDP.session));
  10487. tmp.required = true;
  10488. cand.c(
  10489. 'fingerprint',
  10490. {xmlns: 'urn:xmpp:jingle:apps:dtls:0'})
  10491. .t(tmp.fingerprint);
  10492. delete tmp.fingerprint;
  10493. cand.attrs(tmp);
  10494. cand.up();
  10495. }
  10496. cand.up(); // transport
  10497. cand.up(); // content
  10498. }
  10499. }
  10500. // might merge last-candidate notification into this, but it is called alot later. See webrtc issue #2340
  10501. //console.log('was this the last candidate', this.lasticecandidate);
  10502. this.connection.sendIQ(cand,
  10503. function () {
  10504. var ack = {};
  10505. ack.source = 'transportinfo';
  10506. $(document).trigger('ack.jingle', [this.sid, ack]);
  10507. },
  10508. function (stanza) {
  10509. var error = ($(stanza).find('error').length) ? {
  10510. code: $(stanza).find('error').attr('code'),
  10511. reason: $(stanza).find('error :first')[0].tagName,
  10512. }:{};
  10513. error.source = 'transportinfo';
  10514. JingleSession.onJingleError(this.sid, error);
  10515. },
  10516. 10000);
  10517. };
  10518. JingleSession.prototype.sendOffer = function () {
  10519. //console.log('sendOffer...');
  10520. var self = this;
  10521. this.peerconnection.createOffer(function (sdp) {
  10522. self.createdOffer(sdp);
  10523. },
  10524. function (e) {
  10525. console.error('createOffer failed', e);
  10526. },
  10527. this.media_constraints
  10528. );
  10529. };
  10530. JingleSession.prototype.createdOffer = function (sdp) {
  10531. //console.log('createdOffer', sdp);
  10532. var self = this;
  10533. this.localSDP = new SDP(sdp.sdp);
  10534. //this.localSDP.mangle();
  10535. var sendJingle = function () {
  10536. var init = $iq({to: this.peerjid,
  10537. type: 'set'})
  10538. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  10539. action: 'session-initiate',
  10540. initiator: this.initiator,
  10541. sid: this.sid});
  10542. self.localSDP.toJingle(init, this.initiator == this.me ? 'initiator' : 'responder', this.localStreamsSSRC);
  10543. self.connection.sendIQ(init,
  10544. function () {
  10545. var ack = {};
  10546. ack.source = 'offer';
  10547. $(document).trigger('ack.jingle', [self.sid, ack]);
  10548. },
  10549. function (stanza) {
  10550. self.state = 'error';
  10551. self.peerconnection.close();
  10552. var error = ($(stanza).find('error').length) ? {
  10553. code: $(stanza).find('error').attr('code'),
  10554. reason: $(stanza).find('error :first')[0].tagName,
  10555. }:{};
  10556. error.source = 'offer';
  10557. JingleSession.onJingleError(self.sid, error);
  10558. },
  10559. 10000);
  10560. }
  10561. sdp.sdp = this.localSDP.raw;
  10562. this.peerconnection.setLocalDescription(sdp,
  10563. function () {
  10564. if(self.usetrickle)
  10565. {
  10566. sendJingle();
  10567. }
  10568. self.setLocalDescription();
  10569. //console.log('setLocalDescription success');
  10570. },
  10571. function (e) {
  10572. console.error('setLocalDescription failed', e);
  10573. }
  10574. );
  10575. var cands = SDPUtil.find_lines(this.localSDP.raw, 'a=candidate:');
  10576. for (var i = 0; i < cands.length; i++) {
  10577. var cand = SDPUtil.parse_icecandidate(cands[i]);
  10578. if (cand.type == 'srflx') {
  10579. this.hadstuncandidate = true;
  10580. } else if (cand.type == 'relay') {
  10581. this.hadturncandidate = true;
  10582. }
  10583. }
  10584. };
  10585. JingleSession.prototype.setRemoteDescription = function (elem, desctype) {
  10586. //console.log('setting remote description... ', desctype);
  10587. this.remoteSDP = new SDP('');
  10588. this.remoteSDP.fromJingle(elem);
  10589. if (this.peerconnection.remoteDescription !== null) {
  10590. console.log('setRemoteDescription when remote description is not null, should be pranswer', this.peerconnection.remoteDescription);
  10591. if (this.peerconnection.remoteDescription.type == 'pranswer') {
  10592. var pranswer = new SDP(this.peerconnection.remoteDescription.sdp);
  10593. for (var i = 0; i < pranswer.media.length; i++) {
  10594. // make sure we have ice ufrag and pwd
  10595. if (!SDPUtil.find_line(this.remoteSDP.media[i], 'a=ice-ufrag:', this.remoteSDP.session)) {
  10596. if (SDPUtil.find_line(pranswer.media[i], 'a=ice-ufrag:', pranswer.session)) {
  10597. this.remoteSDP.media[i] += SDPUtil.find_line(pranswer.media[i], 'a=ice-ufrag:', pranswer.session) + '\r\n';
  10598. } else {
  10599. console.warn('no ice ufrag?');
  10600. }
  10601. if (SDPUtil.find_line(pranswer.media[i], 'a=ice-pwd:', pranswer.session)) {
  10602. this.remoteSDP.media[i] += SDPUtil.find_line(pranswer.media[i], 'a=ice-pwd:', pranswer.session) + '\r\n';
  10603. } else {
  10604. console.warn('no ice pwd?');
  10605. }
  10606. }
  10607. // copy over candidates
  10608. var lines = SDPUtil.find_lines(pranswer.media[i], 'a=candidate:');
  10609. for (var j = 0; j < lines.length; j++) {
  10610. this.remoteSDP.media[i] += lines[j] + '\r\n';
  10611. }
  10612. }
  10613. this.remoteSDP.raw = this.remoteSDP.session + this.remoteSDP.media.join('');
  10614. }
  10615. }
  10616. var remotedesc = new RTCSessionDescription({type: desctype, sdp: this.remoteSDP.raw});
  10617. this.peerconnection.setRemoteDescription(remotedesc,
  10618. function () {
  10619. //console.log('setRemoteDescription success');
  10620. },
  10621. function (e) {
  10622. console.error('setRemoteDescription error', e);
  10623. JingleSession.onJingleFatalError(self, e);
  10624. }
  10625. );
  10626. };
  10627. JingleSession.prototype.addIceCandidate = function (elem) {
  10628. var self = this;
  10629. if (this.peerconnection.signalingState == 'closed') {
  10630. return;
  10631. }
  10632. if (!this.peerconnection.remoteDescription && this.peerconnection.signalingState == 'have-local-offer') {
  10633. console.log('trickle ice candidate arriving before session accept...');
  10634. // create a PRANSWER for setRemoteDescription
  10635. if (!this.remoteSDP) {
  10636. var cobbled = 'v=0\r\n' +
  10637. 'o=- ' + '1923518516' + ' 2 IN IP4 0.0.0.0\r\n' +// FIXME
  10638. 's=-\r\n' +
  10639. 't=0 0\r\n';
  10640. // first, take some things from the local description
  10641. for (var i = 0; i < this.localSDP.media.length; i++) {
  10642. cobbled += SDPUtil.find_line(this.localSDP.media[i], 'm=') + '\r\n';
  10643. cobbled += SDPUtil.find_lines(this.localSDP.media[i], 'a=rtpmap:').join('\r\n') + '\r\n';
  10644. if (SDPUtil.find_line(this.localSDP.media[i], 'a=mid:')) {
  10645. cobbled += SDPUtil.find_line(this.localSDP.media[i], 'a=mid:') + '\r\n';
  10646. }
  10647. cobbled += 'a=inactive\r\n';
  10648. }
  10649. this.remoteSDP = new SDP(cobbled);
  10650. }
  10651. // then add things like ice and dtls from remote candidate
  10652. elem.each(function () {
  10653. for (var i = 0; i < self.remoteSDP.media.length; i++) {
  10654. if (SDPUtil.find_line(self.remoteSDP.media[i], 'a=mid:' + $(this).attr('name')) ||
  10655. self.remoteSDP.media[i].indexOf('m=' + $(this).attr('name')) === 0) {
  10656. if (!SDPUtil.find_line(self.remoteSDP.media[i], 'a=ice-ufrag:')) {
  10657. var tmp = $(this).find('transport');
  10658. self.remoteSDP.media[i] += 'a=ice-ufrag:' + tmp.attr('ufrag') + '\r\n';
  10659. self.remoteSDP.media[i] += 'a=ice-pwd:' + tmp.attr('pwd') + '\r\n';
  10660. tmp = $(this).find('transport>fingerprint');
  10661. if (tmp.length) {
  10662. self.remoteSDP.media[i] += 'a=fingerprint:' + tmp.attr('hash') + ' ' + tmp.text() + '\r\n';
  10663. } else {
  10664. console.log('no dtls fingerprint (webrtc issue #1718?)');
  10665. self.remoteSDP.media[i] += 'a=crypto:1 AES_CM_128_HMAC_SHA1_80 inline:BAADBAADBAADBAADBAADBAADBAADBAADBAADBAAD\r\n';
  10666. }
  10667. break;
  10668. }
  10669. }
  10670. }
  10671. });
  10672. this.remoteSDP.raw = this.remoteSDP.session + this.remoteSDP.media.join('');
  10673. // we need a complete SDP with ice-ufrag/ice-pwd in all parts
  10674. // this makes the assumption that the PRANSWER is constructed such that the ice-ufrag is in all mediaparts
  10675. // but it could be in the session part as well. since the code above constructs this sdp this can't happen however
  10676. var iscomplete = this.remoteSDP.media.filter(function (mediapart) {
  10677. return SDPUtil.find_line(mediapart, 'a=ice-ufrag:');
  10678. }).length == this.remoteSDP.media.length;
  10679. if (iscomplete) {
  10680. console.log('setting pranswer');
  10681. try {
  10682. this.peerconnection.setRemoteDescription(new RTCSessionDescription({type: 'pranswer', sdp: this.remoteSDP.raw }),
  10683. function() {
  10684. },
  10685. function(e) {
  10686. console.log('setRemoteDescription pranswer failed', e.toString());
  10687. });
  10688. } catch (e) {
  10689. console.error('setting pranswer failed', e);
  10690. }
  10691. } else {
  10692. //console.log('not yet setting pranswer');
  10693. }
  10694. }
  10695. // operate on each content element
  10696. elem.each(function () {
  10697. // would love to deactivate this, but firefox still requires it
  10698. var idx = -1;
  10699. var i;
  10700. for (i = 0; i < self.remoteSDP.media.length; i++) {
  10701. if (SDPUtil.find_line(self.remoteSDP.media[i], 'a=mid:' + $(this).attr('name')) ||
  10702. self.remoteSDP.media[i].indexOf('m=' + $(this).attr('name')) === 0) {
  10703. idx = i;
  10704. break;
  10705. }
  10706. }
  10707. if (idx == -1) { // fall back to localdescription
  10708. for (i = 0; i < self.localSDP.media.length; i++) {
  10709. if (SDPUtil.find_line(self.localSDP.media[i], 'a=mid:' + $(this).attr('name')) ||
  10710. self.localSDP.media[i].indexOf('m=' + $(this).attr('name')) === 0) {
  10711. idx = i;
  10712. break;
  10713. }
  10714. }
  10715. }
  10716. var name = $(this).attr('name');
  10717. // TODO: check ice-pwd and ice-ufrag?
  10718. $(this).find('transport>candidate').each(function () {
  10719. var line, candidate;
  10720. line = SDPUtil.candidateFromJingle(this);
  10721. candidate = new RTCIceCandidate({sdpMLineIndex: idx,
  10722. sdpMid: name,
  10723. candidate: line});
  10724. try {
  10725. self.peerconnection.addIceCandidate(candidate);
  10726. } catch (e) {
  10727. console.error('addIceCandidate failed', e.toString(), line);
  10728. }
  10729. });
  10730. });
  10731. };
  10732. JingleSession.prototype.sendAnswer = function (provisional) {
  10733. //console.log('createAnswer', provisional);
  10734. var self = this;
  10735. this.peerconnection.createAnswer(
  10736. function (sdp) {
  10737. self.createdAnswer(sdp, provisional);
  10738. },
  10739. function (e) {
  10740. console.error('createAnswer failed', e);
  10741. },
  10742. this.media_constraints
  10743. );
  10744. };
  10745. JingleSession.prototype.createdAnswer = function (sdp, provisional) {
  10746. //console.log('createAnswer callback');
  10747. var self = this;
  10748. this.localSDP = new SDP(sdp.sdp);
  10749. //this.localSDP.mangle();
  10750. this.usepranswer = provisional === true;
  10751. if (this.usetrickle) {
  10752. if (this.usepranswer) {
  10753. sdp.type = 'pranswer';
  10754. for (var i = 0; i < this.localSDP.media.length; i++) {
  10755. this.localSDP.media[i] = this.localSDP.media[i].replace('a=sendrecv\r\n', 'a=inactive\r\n');
  10756. }
  10757. this.localSDP.raw = this.localSDP.session + '\r\n' + this.localSDP.media.join('');
  10758. }
  10759. }
  10760. var self = this;
  10761. var sendJingle = function (ssrcs) {
  10762. var accept = $iq({to: self.peerjid,
  10763. type: 'set'})
  10764. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  10765. action: 'session-accept',
  10766. initiator: self.initiator,
  10767. responder: self.responder,
  10768. sid: self.sid });
  10769. var publicLocalDesc = APP.simulcast.reverseTransformLocalDescription(sdp);
  10770. var publicLocalSDP = new SDP(publicLocalDesc.sdp);
  10771. publicLocalSDP.toJingle(accept, self.initiator == self.me ? 'initiator' : 'responder', ssrcs);
  10772. self.connection.sendIQ(accept,
  10773. function () {
  10774. var ack = {};
  10775. ack.source = 'answer';
  10776. $(document).trigger('ack.jingle', [self.sid, ack]);
  10777. },
  10778. function (stanza) {
  10779. var error = ($(stanza).find('error').length) ? {
  10780. code: $(stanza).find('error').attr('code'),
  10781. reason: $(stanza).find('error :first')[0].tagName,
  10782. }:{};
  10783. error.source = 'answer';
  10784. JingleSession.onJingleError(self.sid, error);
  10785. },
  10786. 10000);
  10787. }
  10788. sdp.sdp = this.localSDP.raw;
  10789. this.peerconnection.setLocalDescription(sdp,
  10790. function () {
  10791. //console.log('setLocalDescription success');
  10792. if (self.usetrickle && !self.usepranswer) {
  10793. sendJingle();
  10794. }
  10795. self.setLocalDescription();
  10796. },
  10797. function (e) {
  10798. console.error('setLocalDescription failed', e);
  10799. }
  10800. );
  10801. var cands = SDPUtil.find_lines(this.localSDP.raw, 'a=candidate:');
  10802. for (var j = 0; j < cands.length; j++) {
  10803. var cand = SDPUtil.parse_icecandidate(cands[j]);
  10804. if (cand.type == 'srflx') {
  10805. this.hadstuncandidate = true;
  10806. } else if (cand.type == 'relay') {
  10807. this.hadturncandidate = true;
  10808. }
  10809. }
  10810. };
  10811. JingleSession.prototype.sendTerminate = function (reason, text) {
  10812. var self = this,
  10813. term = $iq({to: this.peerjid,
  10814. type: 'set'})
  10815. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  10816. action: 'session-terminate',
  10817. initiator: this.initiator,
  10818. sid: this.sid})
  10819. .c('reason')
  10820. .c(reason || 'success');
  10821. if (text) {
  10822. term.up().c('text').t(text);
  10823. }
  10824. this.connection.sendIQ(term,
  10825. function () {
  10826. self.peerconnection.close();
  10827. self.peerconnection = null;
  10828. self.terminate();
  10829. var ack = {};
  10830. ack.source = 'terminate';
  10831. $(document).trigger('ack.jingle', [self.sid, ack]);
  10832. },
  10833. function (stanza) {
  10834. var error = ($(stanza).find('error').length) ? {
  10835. code: $(stanza).find('error').attr('code'),
  10836. reason: $(stanza).find('error :first')[0].tagName,
  10837. }:{};
  10838. $(document).trigger('ack.jingle', [self.sid, error]);
  10839. },
  10840. 10000);
  10841. if (this.statsinterval !== null) {
  10842. window.clearInterval(this.statsinterval);
  10843. this.statsinterval = null;
  10844. }
  10845. };
  10846. JingleSession.prototype.addSource = function (elem, fromJid) {
  10847. var self = this;
  10848. // FIXME: dirty waiting
  10849. if (!this.peerconnection.localDescription)
  10850. {
  10851. console.warn("addSource - localDescription not ready yet")
  10852. setTimeout(function()
  10853. {
  10854. self.addSource(elem, fromJid);
  10855. },
  10856. 200
  10857. );
  10858. return;
  10859. }
  10860. console.log('addssrc', new Date().getTime());
  10861. console.log('ice', this.peerconnection.iceConnectionState);
  10862. var sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  10863. var mySdp = new SDP(this.peerconnection.localDescription.sdp);
  10864. $(elem).each(function (idx, content) {
  10865. var name = $(content).attr('name');
  10866. var lines = '';
  10867. $(content).find('ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]').each(function() {
  10868. var semantics = this.getAttribute('semantics');
  10869. var ssrcs = $(this).find('>source').map(function () {
  10870. return this.getAttribute('ssrc');
  10871. }).get();
  10872. if (ssrcs.length != 0) {
  10873. lines += 'a=ssrc-group:' + semantics + ' ' + ssrcs.join(' ') + '\r\n';
  10874. }
  10875. });
  10876. var tmp = $(content).find('source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]'); // can handle both >source and >description>source
  10877. tmp.each(function () {
  10878. var ssrc = $(this).attr('ssrc');
  10879. if(mySdp.containsSSRC(ssrc)){
  10880. /**
  10881. * This happens when multiple participants change their streams at the same time and
  10882. * ColibriFocus.modifySources have to wait for stable state. In the meantime multiple
  10883. * addssrc are scheduled for update IQ. See
  10884. */
  10885. console.warn("Got add stream request for my own ssrc: "+ssrc);
  10886. return;
  10887. }
  10888. $(this).find('>parameter').each(function () {
  10889. lines += 'a=ssrc:' + ssrc + ' ' + $(this).attr('name');
  10890. if ($(this).attr('value') && $(this).attr('value').length)
  10891. lines += ':' + $(this).attr('value');
  10892. lines += '\r\n';
  10893. });
  10894. });
  10895. sdp.media.forEach(function(media, idx) {
  10896. if (!SDPUtil.find_line(media, 'a=mid:' + name))
  10897. return;
  10898. sdp.media[idx] += lines;
  10899. if (!self.addssrc[idx]) self.addssrc[idx] = '';
  10900. self.addssrc[idx] += lines;
  10901. });
  10902. sdp.raw = sdp.session + sdp.media.join('');
  10903. });
  10904. this.modifySources();
  10905. };
  10906. JingleSession.prototype.removeSource = function (elem, fromJid) {
  10907. var self = this;
  10908. // FIXME: dirty waiting
  10909. if (!this.peerconnection.localDescription)
  10910. {
  10911. console.warn("removeSource - localDescription not ready yet")
  10912. setTimeout(function()
  10913. {
  10914. self.removeSource(elem, fromJid);
  10915. },
  10916. 200
  10917. );
  10918. return;
  10919. }
  10920. console.log('removessrc', new Date().getTime());
  10921. console.log('ice', this.peerconnection.iceConnectionState);
  10922. var sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  10923. var mySdp = new SDP(this.peerconnection.localDescription.sdp);
  10924. $(elem).each(function (idx, content) {
  10925. var name = $(content).attr('name');
  10926. var lines = '';
  10927. $(content).find('ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]').each(function() {
  10928. var semantics = this.getAttribute('semantics');
  10929. var ssrcs = $(this).find('>source').map(function () {
  10930. return this.getAttribute('ssrc');
  10931. }).get();
  10932. if (ssrcs.length != 0) {
  10933. lines += 'a=ssrc-group:' + semantics + ' ' + ssrcs.join(' ') + '\r\n';
  10934. }
  10935. });
  10936. var tmp = $(content).find('source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]'); // can handle both >source and >description>source
  10937. tmp.each(function () {
  10938. var ssrc = $(this).attr('ssrc');
  10939. // This should never happen, but can be useful for bug detection
  10940. if(mySdp.containsSSRC(ssrc)){
  10941. console.error("Got remove stream request for my own ssrc: "+ssrc);
  10942. return;
  10943. }
  10944. $(this).find('>parameter').each(function () {
  10945. lines += 'a=ssrc:' + ssrc + ' ' + $(this).attr('name');
  10946. if ($(this).attr('value') && $(this).attr('value').length)
  10947. lines += ':' + $(this).attr('value');
  10948. lines += '\r\n';
  10949. });
  10950. });
  10951. sdp.media.forEach(function(media, idx) {
  10952. if (!SDPUtil.find_line(media, 'a=mid:' + name))
  10953. return;
  10954. sdp.media[idx] += lines;
  10955. if (!self.removessrc[idx]) self.removessrc[idx] = '';
  10956. self.removessrc[idx] += lines;
  10957. });
  10958. sdp.raw = sdp.session + sdp.media.join('');
  10959. });
  10960. this.modifySources();
  10961. };
  10962. JingleSession.prototype.modifySources = function (successCallback) {
  10963. var self = this;
  10964. if (this.peerconnection.signalingState == 'closed') return;
  10965. if (!(this.addssrc.length || this.removessrc.length || this.pendingop !== null || this.switchstreams)){
  10966. // There is nothing to do since scheduled job might have been executed by another succeeding call
  10967. this.setLocalDescription();
  10968. if(successCallback){
  10969. successCallback();
  10970. }
  10971. return;
  10972. }
  10973. // FIXME: this is a big hack
  10974. // https://code.google.com/p/webrtc/issues/detail?id=2688
  10975. // ^ has been fixed.
  10976. if (!(this.peerconnection.signalingState == 'stable' && this.peerconnection.iceConnectionState == 'connected')) {
  10977. console.warn('modifySources not yet', this.peerconnection.signalingState, this.peerconnection.iceConnectionState);
  10978. this.wait = true;
  10979. window.setTimeout(function() { self.modifySources(successCallback); }, 250);
  10980. return;
  10981. }
  10982. if (this.wait) {
  10983. window.setTimeout(function() { self.modifySources(successCallback); }, 2500);
  10984. this.wait = false;
  10985. return;
  10986. }
  10987. // Reset switch streams flag
  10988. this.switchstreams = false;
  10989. var sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  10990. // add sources
  10991. this.addssrc.forEach(function(lines, idx) {
  10992. sdp.media[idx] += lines;
  10993. });
  10994. this.addssrc = [];
  10995. // remove sources
  10996. this.removessrc.forEach(function(lines, idx) {
  10997. lines = lines.split('\r\n');
  10998. lines.pop(); // remove empty last element;
  10999. lines.forEach(function(line) {
  11000. sdp.media[idx] = sdp.media[idx].replace(line + '\r\n', '');
  11001. });
  11002. });
  11003. this.removessrc = [];
  11004. // FIXME:
  11005. // this was a hack for the situation when only one peer exists
  11006. // in the conference.
  11007. // check if still required and remove
  11008. if (sdp.media[0])
  11009. sdp.media[0] = sdp.media[0].replace('a=recvonly', 'a=sendrecv');
  11010. if (sdp.media[1])
  11011. sdp.media[1] = sdp.media[1].replace('a=recvonly', 'a=sendrecv');
  11012. sdp.raw = sdp.session + sdp.media.join('');
  11013. this.peerconnection.setRemoteDescription(new RTCSessionDescription({type: 'offer', sdp: sdp.raw}),
  11014. function() {
  11015. if(self.signalingState == 'closed') {
  11016. console.error("createAnswer attempt on closed state");
  11017. return;
  11018. }
  11019. self.peerconnection.createAnswer(
  11020. function(modifiedAnswer) {
  11021. // change video direction, see https://github.com/jitsi/jitmeet/issues/41
  11022. if (self.pendingop !== null) {
  11023. var sdp = new SDP(modifiedAnswer.sdp);
  11024. if (sdp.media.length > 1) {
  11025. switch(self.pendingop) {
  11026. case 'mute':
  11027. sdp.media[1] = sdp.media[1].replace('a=sendrecv', 'a=recvonly');
  11028. break;
  11029. case 'unmute':
  11030. sdp.media[1] = sdp.media[1].replace('a=recvonly', 'a=sendrecv');
  11031. break;
  11032. }
  11033. sdp.raw = sdp.session + sdp.media.join('');
  11034. modifiedAnswer.sdp = sdp.raw;
  11035. }
  11036. self.pendingop = null;
  11037. }
  11038. // FIXME: pushing down an answer while ice connection state
  11039. // is still checking is bad...
  11040. //console.log(self.peerconnection.iceConnectionState);
  11041. // trying to work around another chrome bug
  11042. //modifiedAnswer.sdp = modifiedAnswer.sdp.replace(/a=setup:active/g, 'a=setup:actpass');
  11043. self.peerconnection.setLocalDescription(modifiedAnswer,
  11044. function() {
  11045. //console.log('modified setLocalDescription ok');
  11046. self.setLocalDescription();
  11047. if(successCallback){
  11048. successCallback();
  11049. }
  11050. },
  11051. function(error) {
  11052. console.error('modified setLocalDescription failed', error);
  11053. }
  11054. );
  11055. },
  11056. function(error) {
  11057. console.error('modified answer failed', error);
  11058. }
  11059. );
  11060. },
  11061. function(error) {
  11062. console.error('modify failed', error);
  11063. }
  11064. );
  11065. };
  11066. /**
  11067. * Switches video streams.
  11068. * @param new_stream new stream that will be used as video of this session.
  11069. * @param oldStream old video stream of this session.
  11070. * @param success_callback callback executed after successful stream switch.
  11071. */
  11072. JingleSession.prototype.switchStreams = function (new_stream, oldStream, success_callback) {
  11073. var self = this;
  11074. // Remember SDP to figure out added/removed SSRCs
  11075. var oldSdp = null;
  11076. if(self.peerconnection) {
  11077. if(self.peerconnection.localDescription) {
  11078. oldSdp = new SDP(self.peerconnection.localDescription.sdp);
  11079. }
  11080. self.peerconnection.removeStream(oldStream, true);
  11081. self.peerconnection.addStream(new_stream);
  11082. }
  11083. APP.RTC.switchVideoStreams(new_stream, oldStream);
  11084. // Conference is not active
  11085. if(!oldSdp || !self.peerconnection) {
  11086. success_callback();
  11087. return;
  11088. }
  11089. self.switchstreams = true;
  11090. self.modifySources(function() {
  11091. console.log('modify sources done');
  11092. success_callback();
  11093. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  11094. console.log("SDPs", oldSdp, newSdp);
  11095. self.notifyMySSRCUpdate(oldSdp, newSdp);
  11096. });
  11097. };
  11098. /**
  11099. * Figures out added/removed ssrcs and send update IQs.
  11100. * @param old_sdp SDP object for old description.
  11101. * @param new_sdp SDP object for new description.
  11102. */
  11103. JingleSession.prototype.notifyMySSRCUpdate = function (old_sdp, new_sdp) {
  11104. if (!(this.peerconnection.signalingState == 'stable' &&
  11105. this.peerconnection.iceConnectionState == 'connected')){
  11106. console.log("Too early to send updates");
  11107. return;
  11108. }
  11109. // send source-remove IQ.
  11110. sdpDiffer = new SDPDiffer(new_sdp, old_sdp);
  11111. var remove = $iq({to: this.peerjid, type: 'set'})
  11112. .c('jingle', {
  11113. xmlns: 'urn:xmpp:jingle:1',
  11114. action: 'source-remove',
  11115. initiator: this.initiator,
  11116. sid: this.sid
  11117. }
  11118. );
  11119. var removed = sdpDiffer.toJingle(remove);
  11120. if (removed) {
  11121. this.connection.sendIQ(remove,
  11122. function (res) {
  11123. console.info('got remove result', res);
  11124. },
  11125. function (err) {
  11126. console.error('got remove error', err);
  11127. }
  11128. );
  11129. } else {
  11130. console.log('removal not necessary');
  11131. }
  11132. // send source-add IQ.
  11133. var sdpDiffer = new SDPDiffer(old_sdp, new_sdp);
  11134. var add = $iq({to: this.peerjid, type: 'set'})
  11135. .c('jingle', {
  11136. xmlns: 'urn:xmpp:jingle:1',
  11137. action: 'source-add',
  11138. initiator: this.initiator,
  11139. sid: this.sid
  11140. }
  11141. );
  11142. var added = sdpDiffer.toJingle(add);
  11143. if (added) {
  11144. this.connection.sendIQ(add,
  11145. function (res) {
  11146. console.info('got add result', res);
  11147. },
  11148. function (err) {
  11149. console.error('got add error', err);
  11150. }
  11151. );
  11152. } else {
  11153. console.log('addition not necessary');
  11154. }
  11155. };
  11156. /**
  11157. * Determines whether the (local) video is mute i.e. all video tracks are
  11158. * disabled.
  11159. *
  11160. * @return <tt>true</tt> if the (local) video is mute i.e. all video tracks are
  11161. * disabled; otherwise, <tt>false</tt>
  11162. */
  11163. JingleSession.prototype.isVideoMute = function () {
  11164. var tracks = APP.RTC.localVideo.getVideoTracks();
  11165. var mute = true;
  11166. for (var i = 0; i < tracks.length; ++i) {
  11167. if (tracks[i].enabled) {
  11168. mute = false;
  11169. break;
  11170. }
  11171. }
  11172. return mute;
  11173. };
  11174. /**
  11175. * Mutes/unmutes the (local) video i.e. enables/disables all video tracks.
  11176. *
  11177. * @param mute <tt>true</tt> to mute the (local) video i.e. to disable all video
  11178. * tracks; otherwise, <tt>false</tt>
  11179. * @param callback a function to be invoked with <tt>mute</tt> after all video
  11180. * tracks have been enabled/disabled. The function may, optionally, return
  11181. * another function which is to be invoked after the whole mute/unmute operation
  11182. * has completed successfully.
  11183. * @param options an object which specifies optional arguments such as the
  11184. * <tt>boolean</tt> key <tt>byUser</tt> with default value <tt>true</tt> which
  11185. * specifies whether the method was initiated in response to a user command (in
  11186. * contrast to an automatic decision made by the application logic)
  11187. */
  11188. JingleSession.prototype.setVideoMute = function (mute, callback, options) {
  11189. var byUser;
  11190. if (options) {
  11191. byUser = options.byUser;
  11192. if (typeof byUser === 'undefined') {
  11193. byUser = true;
  11194. }
  11195. } else {
  11196. byUser = true;
  11197. }
  11198. // The user's command to mute the (local) video takes precedence over any
  11199. // automatic decision made by the application logic.
  11200. if (byUser) {
  11201. this.videoMuteByUser = mute;
  11202. } else if (this.videoMuteByUser) {
  11203. return;
  11204. }
  11205. var self = this;
  11206. var localCallback = function (mute) {
  11207. self.connection.emuc.addVideoInfoToPresence(mute);
  11208. self.connection.emuc.sendPresence();
  11209. return callback(mute)
  11210. };
  11211. if (mute == APP.RTC.localVideo.isMuted())
  11212. {
  11213. // Even if no change occurs, the specified callback is to be executed.
  11214. // The specified callback may, optionally, return a successCallback
  11215. // which is to be executed as well.
  11216. var successCallback = localCallback(mute);
  11217. if (successCallback) {
  11218. successCallback();
  11219. }
  11220. } else {
  11221. APP.RTC.localVideo.setMute(!mute);
  11222. this.hardMuteVideo(mute);
  11223. this.modifySources(localCallback(mute));
  11224. }
  11225. };
  11226. // SDP-based mute by going recvonly/sendrecv
  11227. // FIXME: should probably black out the screen as well
  11228. JingleSession.prototype.toggleVideoMute = function (callback) {
  11229. this.service.setVideoMute(APP.RTC.localVideo.isMuted(), callback);
  11230. };
  11231. JingleSession.prototype.hardMuteVideo = function (muted) {
  11232. this.pendingop = muted ? 'mute' : 'unmute';
  11233. };
  11234. JingleSession.prototype.sendMute = function (muted, content) {
  11235. var info = $iq({to: this.peerjid,
  11236. type: 'set'})
  11237. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  11238. action: 'session-info',
  11239. initiator: this.initiator,
  11240. sid: this.sid });
  11241. info.c(muted ? 'mute' : 'unmute', {xmlns: 'urn:xmpp:jingle:apps:rtp:info:1'});
  11242. info.attrs({'creator': this.me == this.initiator ? 'creator' : 'responder'});
  11243. if (content) {
  11244. info.attrs({'name': content});
  11245. }
  11246. this.connection.send(info);
  11247. };
  11248. JingleSession.prototype.sendRinging = function () {
  11249. var info = $iq({to: this.peerjid,
  11250. type: 'set'})
  11251. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  11252. action: 'session-info',
  11253. initiator: this.initiator,
  11254. sid: this.sid });
  11255. info.c('ringing', {xmlns: 'urn:xmpp:jingle:apps:rtp:info:1'});
  11256. this.connection.send(info);
  11257. };
  11258. JingleSession.prototype.getStats = function (interval) {
  11259. var self = this;
  11260. var recv = {audio: 0, video: 0};
  11261. var lost = {audio: 0, video: 0};
  11262. var lastrecv = {audio: 0, video: 0};
  11263. var lastlost = {audio: 0, video: 0};
  11264. var loss = {audio: 0, video: 0};
  11265. var delta = {audio: 0, video: 0};
  11266. this.statsinterval = window.setInterval(function () {
  11267. if (self && self.peerconnection && self.peerconnection.getStats) {
  11268. self.peerconnection.getStats(function (stats) {
  11269. var results = stats.result();
  11270. // TODO: there are so much statistics you can get from this..
  11271. for (var i = 0; i < results.length; ++i) {
  11272. if (results[i].type == 'ssrc') {
  11273. var packetsrecv = results[i].stat('packetsReceived');
  11274. var packetslost = results[i].stat('packetsLost');
  11275. if (packetsrecv && packetslost) {
  11276. packetsrecv = parseInt(packetsrecv, 10);
  11277. packetslost = parseInt(packetslost, 10);
  11278. if (results[i].stat('googFrameRateReceived')) {
  11279. lastlost.video = lost.video;
  11280. lastrecv.video = recv.video;
  11281. recv.video = packetsrecv;
  11282. lost.video = packetslost;
  11283. } else {
  11284. lastlost.audio = lost.audio;
  11285. lastrecv.audio = recv.audio;
  11286. recv.audio = packetsrecv;
  11287. lost.audio = packetslost;
  11288. }
  11289. }
  11290. }
  11291. }
  11292. delta.audio = recv.audio - lastrecv.audio;
  11293. delta.video = recv.video - lastrecv.video;
  11294. loss.audio = (delta.audio > 0) ? Math.ceil(100 * (lost.audio - lastlost.audio) / delta.audio) : 0;
  11295. loss.video = (delta.video > 0) ? Math.ceil(100 * (lost.video - lastlost.video) / delta.video) : 0;
  11296. $(document).trigger('packetloss.jingle', [self.sid, loss]);
  11297. });
  11298. }
  11299. }, interval || 3000);
  11300. return this.statsinterval;
  11301. };
  11302. JingleSession.onJingleError = function (session, error)
  11303. {
  11304. console.error("Jingle error", error);
  11305. }
  11306. JingleSession.onJingleFatalError = function (session, error)
  11307. {
  11308. this.service.sessionTerminated = true;
  11309. this.connection.emuc.doLeave();
  11310. APP.UI.messageHandler.showError("dialog.sorry",
  11311. "dialog.internalError");
  11312. }
  11313. JingleSession.prototype.setLocalDescription = function () {
  11314. // put our ssrcs into presence so other clients can identify our stream
  11315. var newssrcs = [];
  11316. var media = APP.simulcast.parseMedia(this.peerconnection.localDescription);
  11317. media.forEach(function (media) {
  11318. if(Object.keys(media.sources).length > 0) {
  11319. // TODO(gp) maybe exclude FID streams?
  11320. Object.keys(media.sources).forEach(function (ssrc) {
  11321. newssrcs.push({
  11322. 'ssrc': ssrc,
  11323. 'type': media.type,
  11324. 'direction': media.direction
  11325. });
  11326. });
  11327. }
  11328. else if(this.localStreamsSSRC && this.localStreamsSSRC[media.type])
  11329. {
  11330. newssrcs.push({
  11331. 'ssrc': this.localStreamsSSRC[media.type],
  11332. 'type': media.type,
  11333. 'direction': media.direction
  11334. });
  11335. }
  11336. });
  11337. console.log('new ssrcs', newssrcs);
  11338. // Have to clear presence map to get rid of removed streams
  11339. this.connection.emuc.clearPresenceMedia();
  11340. if (newssrcs.length > 0) {
  11341. for (var i = 1; i <= newssrcs.length; i ++) {
  11342. // Change video type to screen
  11343. if (newssrcs[i-1].type === 'video' && APP.desktopsharing.isUsingScreenStream()) {
  11344. newssrcs[i-1].type = 'screen';
  11345. }
  11346. this.connection.emuc.addMediaToPresence(i,
  11347. newssrcs[i-1].type, newssrcs[i-1].ssrc, newssrcs[i-1].direction);
  11348. }
  11349. this.connection.emuc.sendPresence();
  11350. }
  11351. }
  11352. // an attempt to work around https://github.com/jitsi/jitmeet/issues/32
  11353. function sendKeyframe(pc) {
  11354. console.log('sendkeyframe', pc.iceConnectionState);
  11355. if (pc.iceConnectionState !== 'connected') return; // safe...
  11356. pc.setRemoteDescription(
  11357. pc.remoteDescription,
  11358. function () {
  11359. pc.createAnswer(
  11360. function (modifiedAnswer) {
  11361. pc.setLocalDescription(
  11362. modifiedAnswer,
  11363. function () {
  11364. // noop
  11365. },
  11366. function (error) {
  11367. console.log('triggerKeyframe setLocalDescription failed', error);
  11368. APP.UI.messageHandler.showError();
  11369. }
  11370. );
  11371. },
  11372. function (error) {
  11373. console.log('triggerKeyframe createAnswer failed', error);
  11374. APP.UI.messageHandler.showError();
  11375. }
  11376. );
  11377. },
  11378. function (error) {
  11379. console.log('triggerKeyframe setRemoteDescription failed', error);
  11380. APP.UI.messageHandler.showError();
  11381. }
  11382. );
  11383. }
  11384. JingleSession.prototype.remoteStreamAdded = function (data, times) {
  11385. var self = this;
  11386. var thessrc;
  11387. var ssrc2jid = this.connection.emuc.ssrc2jid;
  11388. // look up an associated JID for a stream id
  11389. if (data.stream.id && data.stream.id.indexOf('mixedmslabel') === -1) {
  11390. // look only at a=ssrc: and _not_ at a=ssrc-group: lines
  11391. var ssrclines
  11392. = SDPUtil.find_lines(this.peerconnection.remoteDescription.sdp, 'a=ssrc:');
  11393. ssrclines = ssrclines.filter(function (line) {
  11394. // NOTE(gp) previously we filtered on the mslabel, but that property
  11395. // is not always present.
  11396. // return line.indexOf('mslabel:' + data.stream.label) !== -1;
  11397. return ((line.indexOf('msid:' + data.stream.id) !== -1));
  11398. });
  11399. if (ssrclines.length) {
  11400. thessrc = ssrclines[0].substring(7).split(' ')[0];
  11401. // We signal our streams (through Jingle to the focus) before we set
  11402. // our presence (through which peers associate remote streams to
  11403. // jids). So, it might arrive that a remote stream is added but
  11404. // ssrc2jid is not yet updated and thus data.peerjid cannot be
  11405. // successfully set. Here we wait for up to a second for the
  11406. // presence to arrive.
  11407. if (!ssrc2jid[thessrc]) {
  11408. if (typeof times === 'undefined')
  11409. {
  11410. times = 0;
  11411. }
  11412. if (times > 10)
  11413. {
  11414. console.warning('Waiting for jid timed out', thessrc);
  11415. }
  11416. else
  11417. {
  11418. setTimeout(function(d) {
  11419. return function() {
  11420. self.remoteStreamAdded(d, times++);
  11421. }
  11422. }(data), 250);
  11423. }
  11424. return;
  11425. }
  11426. // ok to overwrite the one from focus? might save work in colibri.js
  11427. console.log('associated jid', ssrc2jid[thessrc], data.peerjid);
  11428. if (ssrc2jid[thessrc]) {
  11429. data.peerjid = ssrc2jid[thessrc];
  11430. }
  11431. }
  11432. }
  11433. APP.RTC.createRemoteStream(data, this.sid, thessrc);
  11434. var isVideo = data.stream.getVideoTracks().length > 0;
  11435. // an attempt to work around https://github.com/jitsi/jitmeet/issues/32
  11436. if (isVideo &&
  11437. data.peerjid && this.peerjid === data.peerjid &&
  11438. data.stream.getVideoTracks().length === 0 &&
  11439. APP.RTC.localVideo.getTracks().length > 0) {
  11440. window.setTimeout(function () {
  11441. sendKeyframe(self.peerconnection);
  11442. }, 3000);
  11443. }
  11444. }
  11445. module.exports = JingleSession;
  11446. },{"../../service/RTC/RTCBrowserType":87,"./SDP":48,"./SDPDiffer":49,"./SDPUtil":50,"./TraceablePeerConnection":51}],48:[function(require,module,exports){
  11447. /* jshint -W117 */
  11448. var SDPUtil = require("./SDPUtil");
  11449. // SDP STUFF
  11450. function SDP(sdp) {
  11451. this.media = sdp.split('\r\nm=');
  11452. for (var i = 1; i < this.media.length; i++) {
  11453. this.media[i] = 'm=' + this.media[i];
  11454. if (i != this.media.length - 1) {
  11455. this.media[i] += '\r\n';
  11456. }
  11457. }
  11458. this.session = this.media.shift() + '\r\n';
  11459. this.raw = this.session + this.media.join('');
  11460. }
  11461. /**
  11462. * Returns map of MediaChannel mapped per channel idx.
  11463. */
  11464. SDP.prototype.getMediaSsrcMap = function() {
  11465. var self = this;
  11466. var media_ssrcs = {};
  11467. var tmp;
  11468. for (var mediaindex = 0; mediaindex < self.media.length; mediaindex++) {
  11469. tmp = SDPUtil.find_lines(self.media[mediaindex], 'a=ssrc:');
  11470. var mid = SDPUtil.parse_mid(SDPUtil.find_line(self.media[mediaindex], 'a=mid:'));
  11471. var media = {
  11472. mediaindex: mediaindex,
  11473. mid: mid,
  11474. ssrcs: {},
  11475. ssrcGroups: []
  11476. };
  11477. media_ssrcs[mediaindex] = media;
  11478. tmp.forEach(function (line) {
  11479. var linessrc = line.substring(7).split(' ')[0];
  11480. // allocate new ChannelSsrc
  11481. if(!media.ssrcs[linessrc]) {
  11482. media.ssrcs[linessrc] = {
  11483. ssrc: linessrc,
  11484. lines: []
  11485. };
  11486. }
  11487. media.ssrcs[linessrc].lines.push(line);
  11488. });
  11489. tmp = SDPUtil.find_lines(self.media[mediaindex], 'a=ssrc-group:');
  11490. tmp.forEach(function(line){
  11491. var semantics = line.substr(0, idx).substr(13);
  11492. var ssrcs = line.substr(14 + semantics.length).split(' ');
  11493. if (ssrcs.length != 0) {
  11494. media.ssrcGroups.push({
  11495. semantics: semantics,
  11496. ssrcs: ssrcs
  11497. });
  11498. }
  11499. });
  11500. }
  11501. return media_ssrcs;
  11502. };
  11503. /**
  11504. * Returns <tt>true</tt> if this SDP contains given SSRC.
  11505. * @param ssrc the ssrc to check.
  11506. * @returns {boolean} <tt>true</tt> if this SDP contains given SSRC.
  11507. */
  11508. SDP.prototype.containsSSRC = function(ssrc) {
  11509. var medias = this.getMediaSsrcMap();
  11510. var contains = false;
  11511. Object.keys(medias).forEach(function(mediaindex){
  11512. var media = medias[mediaindex];
  11513. //console.log("Check", channel, ssrc);
  11514. if(Object.keys(media.ssrcs).indexOf(ssrc) != -1){
  11515. contains = true;
  11516. }
  11517. });
  11518. return contains;
  11519. };
  11520. // remove iSAC and CN from SDP
  11521. SDP.prototype.mangle = function () {
  11522. var i, j, mline, lines, rtpmap, newdesc;
  11523. for (i = 0; i < this.media.length; i++) {
  11524. lines = this.media[i].split('\r\n');
  11525. lines.pop(); // remove empty last element
  11526. mline = SDPUtil.parse_mline(lines.shift());
  11527. if (mline.media != 'audio')
  11528. continue;
  11529. newdesc = '';
  11530. mline.fmt.length = 0;
  11531. for (j = 0; j < lines.length; j++) {
  11532. if (lines[j].substr(0, 9) == 'a=rtpmap:') {
  11533. rtpmap = SDPUtil.parse_rtpmap(lines[j]);
  11534. if (rtpmap.name == 'CN' || rtpmap.name == 'ISAC')
  11535. continue;
  11536. mline.fmt.push(rtpmap.id);
  11537. newdesc += lines[j] + '\r\n';
  11538. } else {
  11539. newdesc += lines[j] + '\r\n';
  11540. }
  11541. }
  11542. this.media[i] = SDPUtil.build_mline(mline) + '\r\n';
  11543. this.media[i] += newdesc;
  11544. }
  11545. this.raw = this.session + this.media.join('');
  11546. };
  11547. // remove lines matching prefix from session section
  11548. SDP.prototype.removeSessionLines = function(prefix) {
  11549. var self = this;
  11550. var lines = SDPUtil.find_lines(this.session, prefix);
  11551. lines.forEach(function(line) {
  11552. self.session = self.session.replace(line + '\r\n', '');
  11553. });
  11554. this.raw = this.session + this.media.join('');
  11555. return lines;
  11556. }
  11557. // remove lines matching prefix from a media section specified by mediaindex
  11558. // TODO: non-numeric mediaindex could match mid
  11559. SDP.prototype.removeMediaLines = function(mediaindex, prefix) {
  11560. var self = this;
  11561. var lines = SDPUtil.find_lines(this.media[mediaindex], prefix);
  11562. lines.forEach(function(line) {
  11563. self.media[mediaindex] = self.media[mediaindex].replace(line + '\r\n', '');
  11564. });
  11565. this.raw = this.session + this.media.join('');
  11566. return lines;
  11567. }
  11568. // add content's to a jingle element
  11569. SDP.prototype.toJingle = function (elem, thecreator, ssrcs) {
  11570. // console.log("SSRC" + ssrcs["audio"] + " - " + ssrcs["video"]);
  11571. var i, j, k, mline, ssrc, rtpmap, tmp, line, lines;
  11572. var self = this;
  11573. // new bundle plan
  11574. if (SDPUtil.find_line(this.session, 'a=group:')) {
  11575. lines = SDPUtil.find_lines(this.session, 'a=group:');
  11576. for (i = 0; i < lines.length; i++) {
  11577. tmp = lines[i].split(' ');
  11578. var semantics = tmp.shift().substr(8);
  11579. elem.c('group', {xmlns: 'urn:xmpp:jingle:apps:grouping:0', semantics:semantics});
  11580. for (j = 0; j < tmp.length; j++) {
  11581. elem.c('content', {name: tmp[j]}).up();
  11582. }
  11583. elem.up();
  11584. }
  11585. }
  11586. for (i = 0; i < this.media.length; i++) {
  11587. mline = SDPUtil.parse_mline(this.media[i].split('\r\n')[0]);
  11588. if (!(mline.media === 'audio' ||
  11589. mline.media === 'video' ||
  11590. mline.media === 'application'))
  11591. {
  11592. continue;
  11593. }
  11594. if (SDPUtil.find_line(this.media[i], 'a=ssrc:')) {
  11595. ssrc = SDPUtil.find_line(this.media[i], 'a=ssrc:').substring(7).split(' ')[0]; // take the first
  11596. } else {
  11597. if(ssrcs && ssrcs[mline.media])
  11598. {
  11599. ssrc = ssrcs[mline.media];
  11600. }
  11601. else
  11602. ssrc = false;
  11603. }
  11604. elem.c('content', {creator: thecreator, name: mline.media});
  11605. if (SDPUtil.find_line(this.media[i], 'a=mid:')) {
  11606. // prefer identifier from a=mid if present
  11607. var mid = SDPUtil.parse_mid(SDPUtil.find_line(this.media[i], 'a=mid:'));
  11608. elem.attrs({ name: mid });
  11609. }
  11610. if (SDPUtil.find_line(this.media[i], 'a=rtpmap:').length)
  11611. {
  11612. elem.c('description',
  11613. {xmlns: 'urn:xmpp:jingle:apps:rtp:1',
  11614. media: mline.media });
  11615. if (ssrc) {
  11616. elem.attrs({ssrc: ssrc});
  11617. }
  11618. for (j = 0; j < mline.fmt.length; j++) {
  11619. rtpmap = SDPUtil.find_line(this.media[i], 'a=rtpmap:' + mline.fmt[j]);
  11620. elem.c('payload-type', SDPUtil.parse_rtpmap(rtpmap));
  11621. // put any 'a=fmtp:' + mline.fmt[j] lines into <param name=foo value=bar/>
  11622. if (SDPUtil.find_line(this.media[i], 'a=fmtp:' + mline.fmt[j])) {
  11623. tmp = SDPUtil.parse_fmtp(SDPUtil.find_line(this.media[i], 'a=fmtp:' + mline.fmt[j]));
  11624. for (k = 0; k < tmp.length; k++) {
  11625. elem.c('parameter', tmp[k]).up();
  11626. }
  11627. }
  11628. this.RtcpFbToJingle(i, elem, mline.fmt[j]); // XEP-0293 -- map a=rtcp-fb
  11629. elem.up();
  11630. }
  11631. if (SDPUtil.find_line(this.media[i], 'a=crypto:', this.session)) {
  11632. elem.c('encryption', {required: 1});
  11633. var crypto = SDPUtil.find_lines(this.media[i], 'a=crypto:', this.session);
  11634. crypto.forEach(function(line) {
  11635. elem.c('crypto', SDPUtil.parse_crypto(line)).up();
  11636. });
  11637. elem.up(); // end of encryption
  11638. }
  11639. if (ssrc) {
  11640. // new style mapping
  11641. elem.c('source', { ssrc: ssrc, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  11642. // FIXME: group by ssrc and support multiple different ssrcs
  11643. var ssrclines = SDPUtil.find_lines(this.media[i], 'a=ssrc:');
  11644. if(ssrclines.length > 0) {
  11645. ssrclines.forEach(function (line) {
  11646. idx = line.indexOf(' ');
  11647. var linessrc = line.substr(0, idx).substr(7);
  11648. if (linessrc != ssrc) {
  11649. elem.up();
  11650. ssrc = linessrc;
  11651. elem.c('source', { ssrc: ssrc, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  11652. }
  11653. var kv = line.substr(idx + 1);
  11654. elem.c('parameter');
  11655. if (kv.indexOf(':') == -1) {
  11656. elem.attrs({ name: kv });
  11657. } else {
  11658. elem.attrs({ name: kv.split(':', 2)[0] });
  11659. elem.attrs({ value: kv.split(':', 2)[1] });
  11660. }
  11661. elem.up();
  11662. });
  11663. elem.up();
  11664. }
  11665. else
  11666. {
  11667. elem.up();
  11668. elem.c('source', { ssrc: ssrc, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  11669. elem.c('parameter');
  11670. elem.attrs({name: "cname", value:Math.random().toString(36).substring(7)});
  11671. elem.up();
  11672. var msid = null;
  11673. if(mline.media == "audio")
  11674. {
  11675. msid = APP.RTC.localAudio.getId();
  11676. }
  11677. else
  11678. {
  11679. msid = APP.RTC.localVideo.getId();
  11680. }
  11681. if(msid != null)
  11682. {
  11683. msid = msid.replace(/[\{,\}]/g,"");
  11684. elem.c('parameter');
  11685. elem.attrs({name: "msid", value:msid});
  11686. elem.up();
  11687. elem.c('parameter');
  11688. elem.attrs({name: "mslabel", value:msid});
  11689. elem.up();
  11690. elem.c('parameter');
  11691. elem.attrs({name: "label", value:msid});
  11692. elem.up();
  11693. elem.up();
  11694. }
  11695. }
  11696. // XEP-0339 handle ssrc-group attributes
  11697. var ssrc_group_lines = SDPUtil.find_lines(this.media[i], 'a=ssrc-group:');
  11698. ssrc_group_lines.forEach(function(line) {
  11699. idx = line.indexOf(' ');
  11700. var semantics = line.substr(0, idx).substr(13);
  11701. var ssrcs = line.substr(14 + semantics.length).split(' ');
  11702. if (ssrcs.length != 0) {
  11703. elem.c('ssrc-group', { semantics: semantics, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  11704. ssrcs.forEach(function(ssrc) {
  11705. elem.c('source', { ssrc: ssrc })
  11706. .up();
  11707. });
  11708. elem.up();
  11709. }
  11710. });
  11711. }
  11712. if (SDPUtil.find_line(this.media[i], 'a=rtcp-mux')) {
  11713. elem.c('rtcp-mux').up();
  11714. }
  11715. // XEP-0293 -- map a=rtcp-fb:*
  11716. this.RtcpFbToJingle(i, elem, '*');
  11717. // XEP-0294
  11718. if (SDPUtil.find_line(this.media[i], 'a=extmap:')) {
  11719. lines = SDPUtil.find_lines(this.media[i], 'a=extmap:');
  11720. for (j = 0; j < lines.length; j++) {
  11721. tmp = SDPUtil.parse_extmap(lines[j]);
  11722. elem.c('rtp-hdrext', { xmlns: 'urn:xmpp:jingle:apps:rtp:rtp-hdrext:0',
  11723. uri: tmp.uri,
  11724. id: tmp.value });
  11725. if (tmp.hasOwnProperty('direction')) {
  11726. switch (tmp.direction) {
  11727. case 'sendonly':
  11728. elem.attrs({senders: 'responder'});
  11729. break;
  11730. case 'recvonly':
  11731. elem.attrs({senders: 'initiator'});
  11732. break;
  11733. case 'sendrecv':
  11734. elem.attrs({senders: 'both'});
  11735. break;
  11736. case 'inactive':
  11737. elem.attrs({senders: 'none'});
  11738. break;
  11739. }
  11740. }
  11741. // TODO: handle params
  11742. elem.up();
  11743. }
  11744. }
  11745. elem.up(); // end of description
  11746. }
  11747. // map ice-ufrag/pwd, dtls fingerprint, candidates
  11748. this.TransportToJingle(i, elem);
  11749. if (SDPUtil.find_line(this.media[i], 'a=sendrecv', this.session)) {
  11750. elem.attrs({senders: 'both'});
  11751. } else if (SDPUtil.find_line(this.media[i], 'a=sendonly', this.session)) {
  11752. elem.attrs({senders: 'initiator'});
  11753. } else if (SDPUtil.find_line(this.media[i], 'a=recvonly', this.session)) {
  11754. elem.attrs({senders: 'responder'});
  11755. } else if (SDPUtil.find_line(this.media[i], 'a=inactive', this.session)) {
  11756. elem.attrs({senders: 'none'});
  11757. }
  11758. if (mline.port == '0') {
  11759. // estos hack to reject an m-line
  11760. elem.attrs({senders: 'rejected'});
  11761. }
  11762. elem.up(); // end of content
  11763. }
  11764. elem.up();
  11765. return elem;
  11766. };
  11767. SDP.prototype.TransportToJingle = function (mediaindex, elem) {
  11768. var i = mediaindex;
  11769. var tmp;
  11770. var self = this;
  11771. elem.c('transport');
  11772. // XEP-0343 DTLS/SCTP
  11773. if (SDPUtil.find_line(this.media[mediaindex], 'a=sctpmap:').length)
  11774. {
  11775. var sctpmap = SDPUtil.find_line(
  11776. this.media[i], 'a=sctpmap:', self.session);
  11777. if (sctpmap)
  11778. {
  11779. var sctpAttrs = SDPUtil.parse_sctpmap(sctpmap);
  11780. elem.c('sctpmap',
  11781. {
  11782. xmlns: 'urn:xmpp:jingle:transports:dtls-sctp:1',
  11783. number: sctpAttrs[0], /* SCTP port */
  11784. protocol: sctpAttrs[1], /* protocol */
  11785. });
  11786. // Optional stream count attribute
  11787. if (sctpAttrs.length > 2)
  11788. elem.attrs({ streams: sctpAttrs[2]});
  11789. elem.up();
  11790. }
  11791. }
  11792. // XEP-0320
  11793. var fingerprints = SDPUtil.find_lines(this.media[mediaindex], 'a=fingerprint:', this.session);
  11794. fingerprints.forEach(function(line) {
  11795. tmp = SDPUtil.parse_fingerprint(line);
  11796. tmp.xmlns = 'urn:xmpp:jingle:apps:dtls:0';
  11797. elem.c('fingerprint').t(tmp.fingerprint);
  11798. delete tmp.fingerprint;
  11799. line = SDPUtil.find_line(self.media[mediaindex], 'a=setup:', self.session);
  11800. if (line) {
  11801. tmp.setup = line.substr(8);
  11802. }
  11803. elem.attrs(tmp);
  11804. elem.up(); // end of fingerprint
  11805. });
  11806. tmp = SDPUtil.iceparams(this.media[mediaindex], this.session);
  11807. if (tmp) {
  11808. tmp.xmlns = 'urn:xmpp:jingle:transports:ice-udp:1';
  11809. elem.attrs(tmp);
  11810. // XEP-0176
  11811. if (SDPUtil.find_line(this.media[mediaindex], 'a=candidate:', this.session)) { // add any a=candidate lines
  11812. var lines = SDPUtil.find_lines(this.media[mediaindex], 'a=candidate:', this.session);
  11813. lines.forEach(function (line) {
  11814. elem.c('candidate', SDPUtil.candidateToJingle(line)).up();
  11815. });
  11816. }
  11817. }
  11818. elem.up(); // end of transport
  11819. }
  11820. SDP.prototype.RtcpFbToJingle = function (mediaindex, elem, payloadtype) { // XEP-0293
  11821. var lines = SDPUtil.find_lines(this.media[mediaindex], 'a=rtcp-fb:' + payloadtype);
  11822. lines.forEach(function (line) {
  11823. var tmp = SDPUtil.parse_rtcpfb(line);
  11824. if (tmp.type == 'trr-int') {
  11825. elem.c('rtcp-fb-trr-int', {xmlns: 'urn:xmpp:jingle:apps:rtp:rtcp-fb:0', value: tmp.params[0]});
  11826. elem.up();
  11827. } else {
  11828. elem.c('rtcp-fb', {xmlns: 'urn:xmpp:jingle:apps:rtp:rtcp-fb:0', type: tmp.type});
  11829. if (tmp.params.length > 0) {
  11830. elem.attrs({'subtype': tmp.params[0]});
  11831. }
  11832. elem.up();
  11833. }
  11834. });
  11835. };
  11836. SDP.prototype.RtcpFbFromJingle = function (elem, payloadtype) { // XEP-0293
  11837. var media = '';
  11838. var tmp = elem.find('>rtcp-fb-trr-int[xmlns="urn:xmpp:jingle:apps:rtp:rtcp-fb:0"]');
  11839. if (tmp.length) {
  11840. media += 'a=rtcp-fb:' + '*' + ' ' + 'trr-int' + ' ';
  11841. if (tmp.attr('value')) {
  11842. media += tmp.attr('value');
  11843. } else {
  11844. media += '0';
  11845. }
  11846. media += '\r\n';
  11847. }
  11848. tmp = elem.find('>rtcp-fb[xmlns="urn:xmpp:jingle:apps:rtp:rtcp-fb:0"]');
  11849. tmp.each(function () {
  11850. media += 'a=rtcp-fb:' + payloadtype + ' ' + $(this).attr('type');
  11851. if ($(this).attr('subtype')) {
  11852. media += ' ' + $(this).attr('subtype');
  11853. }
  11854. media += '\r\n';
  11855. });
  11856. return media;
  11857. };
  11858. // construct an SDP from a jingle stanza
  11859. SDP.prototype.fromJingle = function (jingle) {
  11860. var self = this;
  11861. this.raw = 'v=0\r\n' +
  11862. 'o=- ' + '1923518516' + ' 2 IN IP4 0.0.0.0\r\n' +// FIXME
  11863. 's=-\r\n' +
  11864. 't=0 0\r\n';
  11865. // http://tools.ietf.org/html/draft-ietf-mmusic-sdp-bundle-negotiation-04#section-8
  11866. if ($(jingle).find('>group[xmlns="urn:xmpp:jingle:apps:grouping:0"]').length) {
  11867. $(jingle).find('>group[xmlns="urn:xmpp:jingle:apps:grouping:0"]').each(function (idx, group) {
  11868. var contents = $(group).find('>content').map(function (idx, content) {
  11869. return content.getAttribute('name');
  11870. }).get();
  11871. if (contents.length > 0) {
  11872. self.raw += 'a=group:' + (group.getAttribute('semantics') || group.getAttribute('type')) + ' ' + contents.join(' ') + '\r\n';
  11873. }
  11874. });
  11875. }
  11876. this.session = this.raw;
  11877. jingle.find('>content').each(function () {
  11878. var m = self.jingle2media($(this));
  11879. self.media.push(m);
  11880. });
  11881. // reconstruct msid-semantic -- apparently not necessary
  11882. /*
  11883. var msid = SDPUtil.parse_ssrc(this.raw);
  11884. if (msid.hasOwnProperty('mslabel')) {
  11885. this.session += "a=msid-semantic: WMS " + msid.mslabel + "\r\n";
  11886. }
  11887. */
  11888. this.raw = this.session + this.media.join('');
  11889. };
  11890. // translate a jingle content element into an an SDP media part
  11891. SDP.prototype.jingle2media = function (content) {
  11892. var media = '',
  11893. desc = content.find('description'),
  11894. ssrc = desc.attr('ssrc'),
  11895. self = this,
  11896. tmp;
  11897. var sctp = content.find(
  11898. '>transport>sctpmap[xmlns="urn:xmpp:jingle:transports:dtls-sctp:1"]');
  11899. tmp = { media: desc.attr('media') };
  11900. tmp.port = '1';
  11901. if (content.attr('senders') == 'rejected') {
  11902. // estos hack to reject an m-line.
  11903. tmp.port = '0';
  11904. }
  11905. if (content.find('>transport>fingerprint').length || desc.find('encryption').length) {
  11906. if (sctp.length)
  11907. tmp.proto = 'DTLS/SCTP';
  11908. else
  11909. tmp.proto = 'RTP/SAVPF';
  11910. } else {
  11911. tmp.proto = 'RTP/AVPF';
  11912. }
  11913. if (!sctp.length)
  11914. {
  11915. tmp.fmt = desc.find('payload-type').map(
  11916. function () { return this.getAttribute('id'); }).get();
  11917. media += SDPUtil.build_mline(tmp) + '\r\n';
  11918. }
  11919. else
  11920. {
  11921. media += 'm=application 1 DTLS/SCTP ' + sctp.attr('number') + '\r\n';
  11922. media += 'a=sctpmap:' + sctp.attr('number') +
  11923. ' ' + sctp.attr('protocol');
  11924. var streamCount = sctp.attr('streams');
  11925. if (streamCount)
  11926. media += ' ' + streamCount + '\r\n';
  11927. else
  11928. media += '\r\n';
  11929. }
  11930. media += 'c=IN IP4 0.0.0.0\r\n';
  11931. if (!sctp.length)
  11932. media += 'a=rtcp:1 IN IP4 0.0.0.0\r\n';
  11933. tmp = content.find('>transport[xmlns="urn:xmpp:jingle:transports:ice-udp:1"]');
  11934. if (tmp.length) {
  11935. if (tmp.attr('ufrag')) {
  11936. media += SDPUtil.build_iceufrag(tmp.attr('ufrag')) + '\r\n';
  11937. }
  11938. if (tmp.attr('pwd')) {
  11939. media += SDPUtil.build_icepwd(tmp.attr('pwd')) + '\r\n';
  11940. }
  11941. tmp.find('>fingerprint').each(function () {
  11942. // FIXME: check namespace at some point
  11943. media += 'a=fingerprint:' + this.getAttribute('hash');
  11944. media += ' ' + $(this).text();
  11945. media += '\r\n';
  11946. if (this.getAttribute('setup')) {
  11947. media += 'a=setup:' + this.getAttribute('setup') + '\r\n';
  11948. }
  11949. });
  11950. }
  11951. switch (content.attr('senders')) {
  11952. case 'initiator':
  11953. media += 'a=sendonly\r\n';
  11954. break;
  11955. case 'responder':
  11956. media += 'a=recvonly\r\n';
  11957. break;
  11958. case 'none':
  11959. media += 'a=inactive\r\n';
  11960. break;
  11961. case 'both':
  11962. media += 'a=sendrecv\r\n';
  11963. break;
  11964. }
  11965. media += 'a=mid:' + content.attr('name') + '\r\n';
  11966. // <description><rtcp-mux/></description>
  11967. // see http://code.google.com/p/libjingle/issues/detail?id=309 -- no spec though
  11968. // and http://mail.jabber.org/pipermail/jingle/2011-December/001761.html
  11969. if (desc.find('rtcp-mux').length) {
  11970. media += 'a=rtcp-mux\r\n';
  11971. }
  11972. if (desc.find('encryption').length) {
  11973. desc.find('encryption>crypto').each(function () {
  11974. media += 'a=crypto:' + this.getAttribute('tag');
  11975. media += ' ' + this.getAttribute('crypto-suite');
  11976. media += ' ' + this.getAttribute('key-params');
  11977. if (this.getAttribute('session-params')) {
  11978. media += ' ' + this.getAttribute('session-params');
  11979. }
  11980. media += '\r\n';
  11981. });
  11982. }
  11983. desc.find('payload-type').each(function () {
  11984. media += SDPUtil.build_rtpmap(this) + '\r\n';
  11985. if ($(this).find('>parameter').length) {
  11986. media += 'a=fmtp:' + this.getAttribute('id') + ' ';
  11987. media += $(this).find('parameter').map(function () { return (this.getAttribute('name') ? (this.getAttribute('name') + '=') : '') + this.getAttribute('value'); }).get().join('; ');
  11988. media += '\r\n';
  11989. }
  11990. // xep-0293
  11991. media += self.RtcpFbFromJingle($(this), this.getAttribute('id'));
  11992. });
  11993. // xep-0293
  11994. media += self.RtcpFbFromJingle(desc, '*');
  11995. // xep-0294
  11996. tmp = desc.find('>rtp-hdrext[xmlns="urn:xmpp:jingle:apps:rtp:rtp-hdrext:0"]');
  11997. tmp.each(function () {
  11998. media += 'a=extmap:' + this.getAttribute('id') + ' ' + this.getAttribute('uri') + '\r\n';
  11999. });
  12000. content.find('>transport[xmlns="urn:xmpp:jingle:transports:ice-udp:1"]>candidate').each(function () {
  12001. media += SDPUtil.candidateFromJingle(this);
  12002. });
  12003. // XEP-0339 handle ssrc-group attributes
  12004. tmp = content.find('description>ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]').each(function() {
  12005. var semantics = this.getAttribute('semantics');
  12006. var ssrcs = $(this).find('>source').map(function() {
  12007. return this.getAttribute('ssrc');
  12008. }).get();
  12009. if (ssrcs.length != 0) {
  12010. media += 'a=ssrc-group:' + semantics + ' ' + ssrcs.join(' ') + '\r\n';
  12011. }
  12012. });
  12013. tmp = content.find('description>source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]');
  12014. tmp.each(function () {
  12015. var ssrc = this.getAttribute('ssrc');
  12016. $(this).find('>parameter').each(function () {
  12017. media += 'a=ssrc:' + ssrc + ' ' + this.getAttribute('name');
  12018. if (this.getAttribute('value') && this.getAttribute('value').length)
  12019. media += ':' + this.getAttribute('value');
  12020. media += '\r\n';
  12021. });
  12022. });
  12023. return media;
  12024. };
  12025. module.exports = SDP;
  12026. },{"./SDPUtil":50}],49:[function(require,module,exports){
  12027. function SDPDiffer(mySDP, otherSDP) {
  12028. this.mySDP = mySDP;
  12029. this.otherSDP = otherSDP;
  12030. }
  12031. /**
  12032. * Returns map of MediaChannel that contains only media not contained in <tt>otherSdp</tt>. Mapped by channel idx.
  12033. * @param otherSdp the other SDP to check ssrc with.
  12034. */
  12035. SDPDiffer.prototype.getNewMedia = function() {
  12036. // this could be useful in Array.prototype.
  12037. function arrayEquals(array) {
  12038. // if the other array is a falsy value, return
  12039. if (!array)
  12040. return false;
  12041. // compare lengths - can save a lot of time
  12042. if (this.length != array.length)
  12043. return false;
  12044. for (var i = 0, l=this.length; i < l; i++) {
  12045. // Check if we have nested arrays
  12046. if (this[i] instanceof Array && array[i] instanceof Array) {
  12047. // recurse into the nested arrays
  12048. if (!this[i].equals(array[i]))
  12049. return false;
  12050. }
  12051. else if (this[i] != array[i]) {
  12052. // Warning - two different object instances will never be equal: {x:20} != {x:20}
  12053. return false;
  12054. }
  12055. }
  12056. return true;
  12057. }
  12058. var myMedias = this.mySDP.getMediaSsrcMap();
  12059. var othersMedias = this.otherSDP.getMediaSsrcMap();
  12060. var newMedia = {};
  12061. Object.keys(othersMedias).forEach(function(othersMediaIdx) {
  12062. var myMedia = myMedias[othersMediaIdx];
  12063. var othersMedia = othersMedias[othersMediaIdx];
  12064. if(!myMedia && othersMedia) {
  12065. // Add whole channel
  12066. newMedia[othersMediaIdx] = othersMedia;
  12067. return;
  12068. }
  12069. // Look for new ssrcs accross the channel
  12070. Object.keys(othersMedia.ssrcs).forEach(function(ssrc) {
  12071. if(Object.keys(myMedia.ssrcs).indexOf(ssrc) === -1) {
  12072. // Allocate channel if we've found ssrc that doesn't exist in our channel
  12073. if(!newMedia[othersMediaIdx]){
  12074. newMedia[othersMediaIdx] = {
  12075. mediaindex: othersMedia.mediaindex,
  12076. mid: othersMedia.mid,
  12077. ssrcs: {},
  12078. ssrcGroups: []
  12079. };
  12080. }
  12081. newMedia[othersMediaIdx].ssrcs[ssrc] = othersMedia.ssrcs[ssrc];
  12082. }
  12083. });
  12084. // Look for new ssrc groups across the channels
  12085. othersMedia.ssrcGroups.forEach(function(otherSsrcGroup){
  12086. // try to match the other ssrc-group with an ssrc-group of ours
  12087. var matched = false;
  12088. for (var i = 0; i < myMedia.ssrcGroups.length; i++) {
  12089. var mySsrcGroup = myMedia.ssrcGroups[i];
  12090. if (otherSsrcGroup.semantics == mySsrcGroup.semantics
  12091. && arrayEquals.apply(otherSsrcGroup.ssrcs, [mySsrcGroup.ssrcs])) {
  12092. matched = true;
  12093. break;
  12094. }
  12095. }
  12096. if (!matched) {
  12097. // Allocate channel if we've found an ssrc-group that doesn't
  12098. // exist in our channel
  12099. if(!newMedia[othersMediaIdx]){
  12100. newMedia[othersMediaIdx] = {
  12101. mediaindex: othersMedia.mediaindex,
  12102. mid: othersMedia.mid,
  12103. ssrcs: {},
  12104. ssrcGroups: []
  12105. };
  12106. }
  12107. newMedia[othersMediaIdx].ssrcGroups.push(otherSsrcGroup);
  12108. }
  12109. });
  12110. });
  12111. return newMedia;
  12112. };
  12113. /**
  12114. * Sends SSRC update IQ.
  12115. * @param sdpMediaSsrcs SSRCs map obtained from SDP.getNewMedia. Cntains SSRCs to add/remove.
  12116. * @param sid session identifier that will be put into the IQ.
  12117. * @param initiator initiator identifier.
  12118. * @param toJid destination Jid
  12119. * @param isAdd indicates if this is remove or add operation.
  12120. */
  12121. SDPDiffer.prototype.toJingle = function(modify) {
  12122. var sdpMediaSsrcs = this.getNewMedia();
  12123. var self = this;
  12124. // FIXME: only announce video ssrcs since we mix audio and dont need
  12125. // the audio ssrcs therefore
  12126. var modified = false;
  12127. Object.keys(sdpMediaSsrcs).forEach(function(mediaindex){
  12128. modified = true;
  12129. var media = sdpMediaSsrcs[mediaindex];
  12130. modify.c('content', {name: media.mid});
  12131. modify.c('description', {xmlns:'urn:xmpp:jingle:apps:rtp:1', media: media.mid});
  12132. // FIXME: not completly sure this operates on blocks and / or handles different ssrcs correctly
  12133. // generate sources from lines
  12134. Object.keys(media.ssrcs).forEach(function(ssrcNum) {
  12135. var mediaSsrc = media.ssrcs[ssrcNum];
  12136. modify.c('source', { xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  12137. modify.attrs({ssrc: mediaSsrc.ssrc});
  12138. // iterate over ssrc lines
  12139. mediaSsrc.lines.forEach(function (line) {
  12140. var idx = line.indexOf(' ');
  12141. var kv = line.substr(idx + 1);
  12142. modify.c('parameter');
  12143. if (kv.indexOf(':') == -1) {
  12144. modify.attrs({ name: kv });
  12145. } else {
  12146. modify.attrs({ name: kv.split(':', 2)[0] });
  12147. modify.attrs({ value: kv.split(':', 2)[1] });
  12148. }
  12149. modify.up(); // end of parameter
  12150. });
  12151. modify.up(); // end of source
  12152. });
  12153. // generate source groups from lines
  12154. media.ssrcGroups.forEach(function(ssrcGroup) {
  12155. if (ssrcGroup.ssrcs.length != 0) {
  12156. modify.c('ssrc-group', {
  12157. semantics: ssrcGroup.semantics,
  12158. xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0'
  12159. });
  12160. ssrcGroup.ssrcs.forEach(function (ssrc) {
  12161. modify.c('source', { ssrc: ssrc })
  12162. .up(); // end of source
  12163. });
  12164. modify.up(); // end of ssrc-group
  12165. }
  12166. });
  12167. modify.up(); // end of description
  12168. modify.up(); // end of content
  12169. });
  12170. return modified;
  12171. };
  12172. module.exports = SDPDiffer;
  12173. },{}],50:[function(require,module,exports){
  12174. SDPUtil = {
  12175. iceparams: function (mediadesc, sessiondesc) {
  12176. var data = null;
  12177. if (SDPUtil.find_line(mediadesc, 'a=ice-ufrag:', sessiondesc) &&
  12178. SDPUtil.find_line(mediadesc, 'a=ice-pwd:', sessiondesc)) {
  12179. data = {
  12180. ufrag: SDPUtil.parse_iceufrag(SDPUtil.find_line(mediadesc, 'a=ice-ufrag:', sessiondesc)),
  12181. pwd: SDPUtil.parse_icepwd(SDPUtil.find_line(mediadesc, 'a=ice-pwd:', sessiondesc))
  12182. };
  12183. }
  12184. return data;
  12185. },
  12186. parse_iceufrag: function (line) {
  12187. return line.substring(12);
  12188. },
  12189. build_iceufrag: function (frag) {
  12190. return 'a=ice-ufrag:' + frag;
  12191. },
  12192. parse_icepwd: function (line) {
  12193. return line.substring(10);
  12194. },
  12195. build_icepwd: function (pwd) {
  12196. return 'a=ice-pwd:' + pwd;
  12197. },
  12198. parse_mid: function (line) {
  12199. return line.substring(6);
  12200. },
  12201. parse_mline: function (line) {
  12202. var parts = line.substring(2).split(' '),
  12203. data = {};
  12204. data.media = parts.shift();
  12205. data.port = parts.shift();
  12206. data.proto = parts.shift();
  12207. if (parts[parts.length - 1] === '') { // trailing whitespace
  12208. parts.pop();
  12209. }
  12210. data.fmt = parts;
  12211. return data;
  12212. },
  12213. build_mline: function (mline) {
  12214. return 'm=' + mline.media + ' ' + mline.port + ' ' + mline.proto + ' ' + mline.fmt.join(' ');
  12215. },
  12216. parse_rtpmap: function (line) {
  12217. var parts = line.substring(9).split(' '),
  12218. data = {};
  12219. data.id = parts.shift();
  12220. parts = parts[0].split('/');
  12221. data.name = parts.shift();
  12222. data.clockrate = parts.shift();
  12223. data.channels = parts.length ? parts.shift() : '1';
  12224. return data;
  12225. },
  12226. /**
  12227. * Parses SDP line "a=sctpmap:..." and extracts SCTP port from it.
  12228. * @param line eg. "a=sctpmap:5000 webrtc-datachannel"
  12229. * @returns [SCTP port number, protocol, streams]
  12230. */
  12231. parse_sctpmap: function (line)
  12232. {
  12233. var parts = line.substring(10).split(' ');
  12234. var sctpPort = parts[0];
  12235. var protocol = parts[1];
  12236. // Stream count is optional
  12237. var streamCount = parts.length > 2 ? parts[2] : null;
  12238. return [sctpPort, protocol, streamCount];// SCTP port
  12239. },
  12240. build_rtpmap: function (el) {
  12241. var line = 'a=rtpmap:' + el.getAttribute('id') + ' ' + el.getAttribute('name') + '/' + el.getAttribute('clockrate');
  12242. if (el.getAttribute('channels') && el.getAttribute('channels') != '1') {
  12243. line += '/' + el.getAttribute('channels');
  12244. }
  12245. return line;
  12246. },
  12247. parse_crypto: function (line) {
  12248. var parts = line.substring(9).split(' '),
  12249. data = {};
  12250. data.tag = parts.shift();
  12251. data['crypto-suite'] = parts.shift();
  12252. data['key-params'] = parts.shift();
  12253. if (parts.length) {
  12254. data['session-params'] = parts.join(' ');
  12255. }
  12256. return data;
  12257. },
  12258. parse_fingerprint: function (line) { // RFC 4572
  12259. var parts = line.substring(14).split(' '),
  12260. data = {};
  12261. data.hash = parts.shift();
  12262. data.fingerprint = parts.shift();
  12263. // TODO assert that fingerprint satisfies 2UHEX *(":" 2UHEX) ?
  12264. return data;
  12265. },
  12266. parse_fmtp: function (line) {
  12267. var parts = line.split(' '),
  12268. i, key, value,
  12269. data = [];
  12270. parts.shift();
  12271. parts = parts.join(' ').split(';');
  12272. for (i = 0; i < parts.length; i++) {
  12273. key = parts[i].split('=')[0];
  12274. while (key.length && key[0] == ' ') {
  12275. key = key.substring(1);
  12276. }
  12277. value = parts[i].split('=')[1];
  12278. if (key && value) {
  12279. data.push({name: key, value: value});
  12280. } else if (key) {
  12281. // rfc 4733 (DTMF) style stuff
  12282. data.push({name: '', value: key});
  12283. }
  12284. }
  12285. return data;
  12286. },
  12287. parse_icecandidate: function (line) {
  12288. var candidate = {},
  12289. elems = line.split(' ');
  12290. candidate.foundation = elems[0].substring(12);
  12291. candidate.component = elems[1];
  12292. candidate.protocol = elems[2].toLowerCase();
  12293. candidate.priority = elems[3];
  12294. candidate.ip = elems[4];
  12295. candidate.port = elems[5];
  12296. // elems[6] => "typ"
  12297. candidate.type = elems[7];
  12298. candidate.generation = 0; // default value, may be overwritten below
  12299. for (var i = 8; i < elems.length; i += 2) {
  12300. switch (elems[i]) {
  12301. case 'raddr':
  12302. candidate['rel-addr'] = elems[i + 1];
  12303. break;
  12304. case 'rport':
  12305. candidate['rel-port'] = elems[i + 1];
  12306. break;
  12307. case 'generation':
  12308. candidate.generation = elems[i + 1];
  12309. break;
  12310. case 'tcptype':
  12311. candidate.tcptype = elems[i + 1];
  12312. break;
  12313. default: // TODO
  12314. console.log('parse_icecandidate not translating "' + elems[i] + '" = "' + elems[i + 1] + '"');
  12315. }
  12316. }
  12317. candidate.network = '1';
  12318. candidate.id = Math.random().toString(36).substr(2, 10); // not applicable to SDP -- FIXME: should be unique, not just random
  12319. return candidate;
  12320. },
  12321. build_icecandidate: function (cand) {
  12322. var line = ['a=candidate:' + cand.foundation, cand.component, cand.protocol, cand.priority, cand.ip, cand.port, 'typ', cand.type].join(' ');
  12323. line += ' ';
  12324. switch (cand.type) {
  12325. case 'srflx':
  12326. case 'prflx':
  12327. case 'relay':
  12328. if (cand.hasOwnAttribute('rel-addr') && cand.hasOwnAttribute('rel-port')) {
  12329. line += 'raddr';
  12330. line += ' ';
  12331. line += cand['rel-addr'];
  12332. line += ' ';
  12333. line += 'rport';
  12334. line += ' ';
  12335. line += cand['rel-port'];
  12336. line += ' ';
  12337. }
  12338. break;
  12339. }
  12340. if (cand.hasOwnAttribute('tcptype')) {
  12341. line += 'tcptype';
  12342. line += ' ';
  12343. line += cand.tcptype;
  12344. line += ' ';
  12345. }
  12346. line += 'generation';
  12347. line += ' ';
  12348. line += cand.hasOwnAttribute('generation') ? cand.generation : '0';
  12349. return line;
  12350. },
  12351. parse_ssrc: function (desc) {
  12352. // proprietary mapping of a=ssrc lines
  12353. // TODO: see "Jingle RTP Source Description" by Juberti and P. Thatcher on google docs
  12354. // and parse according to that
  12355. var lines = desc.split('\r\n'),
  12356. data = {};
  12357. for (var i = 0; i < lines.length; i++) {
  12358. if (lines[i].substring(0, 7) == 'a=ssrc:') {
  12359. var idx = lines[i].indexOf(' ');
  12360. data[lines[i].substr(idx + 1).split(':', 2)[0]] = lines[i].substr(idx + 1).split(':', 2)[1];
  12361. }
  12362. }
  12363. return data;
  12364. },
  12365. parse_rtcpfb: function (line) {
  12366. var parts = line.substr(10).split(' ');
  12367. var data = {};
  12368. data.pt = parts.shift();
  12369. data.type = parts.shift();
  12370. data.params = parts;
  12371. return data;
  12372. },
  12373. parse_extmap: function (line) {
  12374. var parts = line.substr(9).split(' ');
  12375. var data = {};
  12376. data.value = parts.shift();
  12377. if (data.value.indexOf('/') != -1) {
  12378. data.direction = data.value.substr(data.value.indexOf('/') + 1);
  12379. data.value = data.value.substr(0, data.value.indexOf('/'));
  12380. } else {
  12381. data.direction = 'both';
  12382. }
  12383. data.uri = parts.shift();
  12384. data.params = parts;
  12385. return data;
  12386. },
  12387. find_line: function (haystack, needle, sessionpart) {
  12388. var lines = haystack.split('\r\n');
  12389. for (var i = 0; i < lines.length; i++) {
  12390. if (lines[i].substring(0, needle.length) == needle) {
  12391. return lines[i];
  12392. }
  12393. }
  12394. if (!sessionpart) {
  12395. return false;
  12396. }
  12397. // search session part
  12398. lines = sessionpart.split('\r\n');
  12399. for (var j = 0; j < lines.length; j++) {
  12400. if (lines[j].substring(0, needle.length) == needle) {
  12401. return lines[j];
  12402. }
  12403. }
  12404. return false;
  12405. },
  12406. find_lines: function (haystack, needle, sessionpart) {
  12407. var lines = haystack.split('\r\n'),
  12408. needles = [];
  12409. for (var i = 0; i < lines.length; i++) {
  12410. if (lines[i].substring(0, needle.length) == needle)
  12411. needles.push(lines[i]);
  12412. }
  12413. if (needles.length || !sessionpart) {
  12414. return needles;
  12415. }
  12416. // search session part
  12417. lines = sessionpart.split('\r\n');
  12418. for (var j = 0; j < lines.length; j++) {
  12419. if (lines[j].substring(0, needle.length) == needle) {
  12420. needles.push(lines[j]);
  12421. }
  12422. }
  12423. return needles;
  12424. },
  12425. candidateToJingle: function (line) {
  12426. // a=candidate:2979166662 1 udp 2113937151 192.168.2.100 57698 typ host generation 0
  12427. // <candidate component=... foundation=... generation=... id=... ip=... network=... port=... priority=... protocol=... type=.../>
  12428. if (line.indexOf('candidate:') === 0) {
  12429. line = 'a=' + line;
  12430. } else if (line.substring(0, 12) != 'a=candidate:') {
  12431. console.log('parseCandidate called with a line that is not a candidate line');
  12432. console.log(line);
  12433. return null;
  12434. }
  12435. if (line.substring(line.length - 2) == '\r\n') // chomp it
  12436. line = line.substring(0, line.length - 2);
  12437. var candidate = {},
  12438. elems = line.split(' '),
  12439. i;
  12440. if (elems[6] != 'typ') {
  12441. console.log('did not find typ in the right place');
  12442. console.log(line);
  12443. return null;
  12444. }
  12445. candidate.foundation = elems[0].substring(12);
  12446. candidate.component = elems[1];
  12447. candidate.protocol = elems[2].toLowerCase();
  12448. candidate.priority = elems[3];
  12449. candidate.ip = elems[4];
  12450. candidate.port = elems[5];
  12451. // elems[6] => "typ"
  12452. candidate.type = elems[7];
  12453. candidate.generation = '0'; // default, may be overwritten below
  12454. for (i = 8; i < elems.length; i += 2) {
  12455. switch (elems[i]) {
  12456. case 'raddr':
  12457. candidate['rel-addr'] = elems[i + 1];
  12458. break;
  12459. case 'rport':
  12460. candidate['rel-port'] = elems[i + 1];
  12461. break;
  12462. case 'generation':
  12463. candidate.generation = elems[i + 1];
  12464. break;
  12465. case 'tcptype':
  12466. candidate.tcptype = elems[i + 1];
  12467. break;
  12468. default: // TODO
  12469. console.log('not translating "' + elems[i] + '" = "' + elems[i + 1] + '"');
  12470. }
  12471. }
  12472. candidate.network = '1';
  12473. candidate.id = Math.random().toString(36).substr(2, 10); // not applicable to SDP -- FIXME: should be unique, not just random
  12474. return candidate;
  12475. },
  12476. candidateFromJingle: function (cand) {
  12477. var line = 'a=candidate:';
  12478. line += cand.getAttribute('foundation');
  12479. line += ' ';
  12480. line += cand.getAttribute('component');
  12481. line += ' ';
  12482. line += cand.getAttribute('protocol'); //.toUpperCase(); // chrome M23 doesn't like this
  12483. line += ' ';
  12484. line += cand.getAttribute('priority');
  12485. line += ' ';
  12486. line += cand.getAttribute('ip');
  12487. line += ' ';
  12488. line += cand.getAttribute('port');
  12489. line += ' ';
  12490. line += 'typ';
  12491. line += ' ' + cand.getAttribute('type');
  12492. line += ' ';
  12493. switch (cand.getAttribute('type')) {
  12494. case 'srflx':
  12495. case 'prflx':
  12496. case 'relay':
  12497. if (cand.getAttribute('rel-addr') && cand.getAttribute('rel-port')) {
  12498. line += 'raddr';
  12499. line += ' ';
  12500. line += cand.getAttribute('rel-addr');
  12501. line += ' ';
  12502. line += 'rport';
  12503. line += ' ';
  12504. line += cand.getAttribute('rel-port');
  12505. line += ' ';
  12506. }
  12507. break;
  12508. }
  12509. if (cand.getAttribute('protocol').toLowerCase() == 'tcp') {
  12510. line += 'tcptype';
  12511. line += ' ';
  12512. line += cand.getAttribute('tcptype');
  12513. line += ' ';
  12514. }
  12515. line += 'generation';
  12516. line += ' ';
  12517. line += cand.getAttribute('generation') || '0';
  12518. return line + '\r\n';
  12519. }
  12520. };
  12521. module.exports = SDPUtil;
  12522. },{}],51:[function(require,module,exports){
  12523. function TraceablePeerConnection(ice_config, constraints) {
  12524. var self = this;
  12525. var RTCPeerconnection = navigator.mozGetUserMedia ? mozRTCPeerConnection : webkitRTCPeerConnection;
  12526. this.peerconnection = new RTCPeerconnection(ice_config, constraints);
  12527. this.updateLog = [];
  12528. this.stats = {};
  12529. this.statsinterval = null;
  12530. this.maxstats = 0; // limit to 300 values, i.e. 5 minutes; set to 0 to disable
  12531. var Interop = require('sdp-interop').Interop;
  12532. this.interop = new Interop();
  12533. // override as desired
  12534. this.trace = function (what, info) {
  12535. //console.warn('WTRACE', what, info);
  12536. self.updateLog.push({
  12537. time: new Date(),
  12538. type: what,
  12539. value: info || ""
  12540. });
  12541. };
  12542. this.onicecandidate = null;
  12543. this.peerconnection.onicecandidate = function (event) {
  12544. self.trace('onicecandidate', JSON.stringify(event.candidate, null, ' '));
  12545. if (self.onicecandidate !== null) {
  12546. self.onicecandidate(event);
  12547. }
  12548. };
  12549. this.onaddstream = null;
  12550. this.peerconnection.onaddstream = function (event) {
  12551. self.trace('onaddstream', event.stream.id);
  12552. if (self.onaddstream !== null) {
  12553. self.onaddstream(event);
  12554. }
  12555. };
  12556. this.onremovestream = null;
  12557. this.peerconnection.onremovestream = function (event) {
  12558. self.trace('onremovestream', event.stream.id);
  12559. if (self.onremovestream !== null) {
  12560. self.onremovestream(event);
  12561. }
  12562. };
  12563. this.onsignalingstatechange = null;
  12564. this.peerconnection.onsignalingstatechange = function (event) {
  12565. self.trace('onsignalingstatechange', self.signalingState);
  12566. if (self.onsignalingstatechange !== null) {
  12567. self.onsignalingstatechange(event);
  12568. }
  12569. };
  12570. this.oniceconnectionstatechange = null;
  12571. this.peerconnection.oniceconnectionstatechange = function (event) {
  12572. self.trace('oniceconnectionstatechange', self.iceConnectionState);
  12573. if (self.oniceconnectionstatechange !== null) {
  12574. self.oniceconnectionstatechange(event);
  12575. }
  12576. };
  12577. this.onnegotiationneeded = null;
  12578. this.peerconnection.onnegotiationneeded = function (event) {
  12579. self.trace('onnegotiationneeded');
  12580. if (self.onnegotiationneeded !== null) {
  12581. self.onnegotiationneeded(event);
  12582. }
  12583. };
  12584. self.ondatachannel = null;
  12585. this.peerconnection.ondatachannel = function (event) {
  12586. self.trace('ondatachannel', event);
  12587. if (self.ondatachannel !== null) {
  12588. self.ondatachannel(event);
  12589. }
  12590. };
  12591. if (!navigator.mozGetUserMedia && this.maxstats) {
  12592. this.statsinterval = window.setInterval(function() {
  12593. self.peerconnection.getStats(function(stats) {
  12594. var results = stats.result();
  12595. for (var i = 0; i < results.length; ++i) {
  12596. //console.log(results[i].type, results[i].id, results[i].names())
  12597. var now = new Date();
  12598. results[i].names().forEach(function (name) {
  12599. var id = results[i].id + '-' + name;
  12600. if (!self.stats[id]) {
  12601. self.stats[id] = {
  12602. startTime: now,
  12603. endTime: now,
  12604. values: [],
  12605. times: []
  12606. };
  12607. }
  12608. self.stats[id].values.push(results[i].stat(name));
  12609. self.stats[id].times.push(now.getTime());
  12610. if (self.stats[id].values.length > self.maxstats) {
  12611. self.stats[id].values.shift();
  12612. self.stats[id].times.shift();
  12613. }
  12614. self.stats[id].endTime = now;
  12615. });
  12616. }
  12617. });
  12618. }, 1000);
  12619. }
  12620. };
  12621. dumpSDP = function(description) {
  12622. if (typeof description === 'undefined' || description == null) {
  12623. return '';
  12624. }
  12625. return 'type: ' + description.type + '\r\n' + description.sdp;
  12626. };
  12627. if (TraceablePeerConnection.prototype.__defineGetter__ !== undefined) {
  12628. TraceablePeerConnection.prototype.__defineGetter__('signalingState', function() { return this.peerconnection.signalingState; });
  12629. TraceablePeerConnection.prototype.__defineGetter__('iceConnectionState', function() { return this.peerconnection.iceConnectionState; });
  12630. TraceablePeerConnection.prototype.__defineGetter__('localDescription', function() {
  12631. this.trace('getLocalDescription::preTransform (Plan A)', dumpSDP(this.peerconnection.localDescription));
  12632. // if we're running on FF, transform to Plan B first.
  12633. var desc = this.peerconnection.localDescription;
  12634. if (navigator.mozGetUserMedia) {
  12635. desc = this.interop.toPlanB(desc);
  12636. } else {
  12637. desc = APP.simulcast.reverseTransformLocalDescription(this.peerconnection.localDescription);
  12638. }
  12639. this.trace('getLocalDescription::postTransform (Plan B)', dumpSDP(desc));
  12640. return desc;
  12641. });
  12642. TraceablePeerConnection.prototype.__defineGetter__('remoteDescription', function() {
  12643. this.trace('getRemoteDescription::preTransform (Plan A)', dumpSDP(this.peerconnection.remoteDescription));
  12644. // if we're running on FF, transform to Plan B first.
  12645. var desc = this.peerconnection.remoteDescription;
  12646. if (navigator.mozGetUserMedia) {
  12647. desc = this.interop.toPlanB(desc);
  12648. } else {
  12649. desc = APP.simulcast.reverseTransformRemoteDescription(this.peerconnection.remoteDescription);
  12650. }
  12651. this.trace('getRemoteDescription::postTransform (Plan B)', dumpSDP(desc));
  12652. return desc;
  12653. });
  12654. }
  12655. TraceablePeerConnection.prototype.addStream = function (stream) {
  12656. this.trace('addStream', stream.id);
  12657. APP.simulcast.resetSender();
  12658. try
  12659. {
  12660. this.peerconnection.addStream(stream);
  12661. }
  12662. catch (e)
  12663. {
  12664. console.error(e);
  12665. return;
  12666. }
  12667. };
  12668. TraceablePeerConnection.prototype.removeStream = function (stream, stopStreams) {
  12669. this.trace('removeStream', stream.id);
  12670. APP.simulcast.resetSender();
  12671. if(stopStreams) {
  12672. stream.getAudioTracks().forEach(function (track) {
  12673. track.stop();
  12674. });
  12675. stream.getVideoTracks().forEach(function (track) {
  12676. track.stop();
  12677. });
  12678. }
  12679. this.peerconnection.removeStream(stream);
  12680. };
  12681. TraceablePeerConnection.prototype.createDataChannel = function (label, opts) {
  12682. this.trace('createDataChannel', label, opts);
  12683. return this.peerconnection.createDataChannel(label, opts);
  12684. };
  12685. TraceablePeerConnection.prototype.setLocalDescription = function (description, successCallback, failureCallback) {
  12686. this.trace('setLocalDescription::preTransform (Plan B)', dumpSDP(description));
  12687. // if we're running on FF, transform to Plan A first.
  12688. if (navigator.mozGetUserMedia) {
  12689. description = this.interop.toPlanA(description);
  12690. } else {
  12691. description = APP.simulcast.transformLocalDescription(description);
  12692. }
  12693. this.trace('setLocalDescription::postTransform (Plan A)', dumpSDP(description));
  12694. var self = this;
  12695. this.peerconnection.setLocalDescription(description,
  12696. function () {
  12697. self.trace('setLocalDescriptionOnSuccess');
  12698. successCallback();
  12699. },
  12700. function (err) {
  12701. self.trace('setLocalDescriptionOnFailure', err);
  12702. failureCallback(err);
  12703. }
  12704. );
  12705. /*
  12706. if (this.statsinterval === null && this.maxstats > 0) {
  12707. // start gathering stats
  12708. }
  12709. */
  12710. };
  12711. TraceablePeerConnection.prototype.setRemoteDescription = function (description, successCallback, failureCallback) {
  12712. this.trace('setRemoteDescription::preTransform (Plan B)', dumpSDP(description));
  12713. // if we're running on FF, transform to Plan A first.
  12714. if (navigator.mozGetUserMedia) {
  12715. description = this.interop.toPlanA(description);
  12716. }
  12717. else {
  12718. description = APP.simulcast.transformRemoteDescription(description);
  12719. }
  12720. this.trace('setRemoteDescription::postTransform (Plan A)', dumpSDP(description));
  12721. var self = this;
  12722. this.peerconnection.setRemoteDescription(description,
  12723. function () {
  12724. self.trace('setRemoteDescriptionOnSuccess');
  12725. successCallback();
  12726. },
  12727. function (err) {
  12728. self.trace('setRemoteDescriptionOnFailure', err);
  12729. failureCallback(err);
  12730. }
  12731. );
  12732. /*
  12733. if (this.statsinterval === null && this.maxstats > 0) {
  12734. // start gathering stats
  12735. }
  12736. */
  12737. };
  12738. TraceablePeerConnection.prototype.close = function () {
  12739. this.trace('stop');
  12740. if (this.statsinterval !== null) {
  12741. window.clearInterval(this.statsinterval);
  12742. this.statsinterval = null;
  12743. }
  12744. this.peerconnection.close();
  12745. };
  12746. TraceablePeerConnection.prototype.createOffer = function (successCallback, failureCallback, constraints) {
  12747. var self = this;
  12748. this.trace('createOffer', JSON.stringify(constraints, null, ' '));
  12749. this.peerconnection.createOffer(
  12750. function (offer) {
  12751. self.trace('createOfferOnSuccess::preTransform (Plan A)', dumpSDP(offer));
  12752. // if we're running on FF, transform to Plan B first.
  12753. if (navigator.mozGetUserMedia) {
  12754. offer = self.interop.toPlanB(offer);
  12755. }
  12756. self.trace('createOfferOnSuccess::postTransform (Plan B)', dumpSDP(offer));
  12757. successCallback(offer);
  12758. },
  12759. function(err) {
  12760. self.trace('createOfferOnFailure', err);
  12761. failureCallback(err);
  12762. },
  12763. constraints
  12764. );
  12765. };
  12766. TraceablePeerConnection.prototype.createAnswer = function (successCallback, failureCallback, constraints) {
  12767. var self = this;
  12768. this.trace('createAnswer', JSON.stringify(constraints, null, ' '));
  12769. this.peerconnection.createAnswer(
  12770. function (answer) {
  12771. self.trace('createAnswerOnSuccess::preTransfom (Plan A)', dumpSDP(answer));
  12772. // if we're running on FF, transform to Plan A first.
  12773. if (navigator.mozGetUserMedia) {
  12774. answer = self.interop.toPlanB(answer);
  12775. } else {
  12776. answer = APP.simulcast.transformAnswer(answer);
  12777. }
  12778. self.trace('createAnswerOnSuccess::postTransfom (Plan B)', dumpSDP(answer));
  12779. successCallback(answer);
  12780. },
  12781. function(err) {
  12782. self.trace('createAnswerOnFailure', err);
  12783. failureCallback(err);
  12784. },
  12785. constraints
  12786. );
  12787. };
  12788. TraceablePeerConnection.prototype.addIceCandidate = function (candidate, successCallback, failureCallback) {
  12789. var self = this;
  12790. this.trace('addIceCandidate', JSON.stringify(candidate, null, ' '));
  12791. this.peerconnection.addIceCandidate(candidate);
  12792. /* maybe later
  12793. this.peerconnection.addIceCandidate(candidate,
  12794. function () {
  12795. self.trace('addIceCandidateOnSuccess');
  12796. successCallback();
  12797. },
  12798. function (err) {
  12799. self.trace('addIceCandidateOnFailure', err);
  12800. failureCallback(err);
  12801. }
  12802. );
  12803. */
  12804. };
  12805. TraceablePeerConnection.prototype.getStats = function(callback, errback) {
  12806. if (navigator.mozGetUserMedia) {
  12807. // ignore for now...
  12808. if(!errback)
  12809. errback = function () {
  12810. }
  12811. this.peerconnection.getStats(null,callback,errback);
  12812. } else {
  12813. this.peerconnection.getStats(callback);
  12814. }
  12815. };
  12816. module.exports = TraceablePeerConnection;
  12817. },{"sdp-interop":79}],52:[function(require,module,exports){
  12818. /* global $, $iq, APP, config, connection, UI, messageHandler,
  12819. roomName, sessionTerminated, Strophe, Util */
  12820. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  12821. var Settings = require("../settings/Settings");
  12822. var AuthenticationEvents
  12823. = require("../../service/authentication/AuthenticationEvents");
  12824. /**
  12825. * Contains logic responsible for enabling/disabling functionality available
  12826. * only to moderator users.
  12827. */
  12828. var connection = null;
  12829. var focusUserJid;
  12830. function createExpBackoffTimer(step) {
  12831. var count = 1;
  12832. return function (reset) {
  12833. // Reset call
  12834. if (reset) {
  12835. count = 1;
  12836. return;
  12837. }
  12838. // Calculate next timeout
  12839. var timeout = Math.pow(2, count - 1);
  12840. count += 1;
  12841. return timeout * step;
  12842. };
  12843. }
  12844. var getNextTimeout = createExpBackoffTimer(1000);
  12845. var getNextErrorTimeout = createExpBackoffTimer(1000);
  12846. // External authentication stuff
  12847. var externalAuthEnabled = false;
  12848. // Sip gateway can be enabled by configuring Jigasi host in config.js or
  12849. // it will be enabled automatically if focus detects the component through
  12850. // service discovery.
  12851. var sipGatewayEnabled = config.hosts.call_control !== undefined;
  12852. var eventEmitter = null;
  12853. var Moderator = {
  12854. isModerator: function () {
  12855. return connection && connection.emuc.isModerator();
  12856. },
  12857. isPeerModerator: function (peerJid) {
  12858. return connection &&
  12859. connection.emuc.getMemberRole(peerJid) === 'moderator';
  12860. },
  12861. isExternalAuthEnabled: function () {
  12862. return externalAuthEnabled;
  12863. },
  12864. isSipGatewayEnabled: function () {
  12865. return sipGatewayEnabled;
  12866. },
  12867. setConnection: function (con) {
  12868. connection = con;
  12869. },
  12870. init: function (xmpp, emitter) {
  12871. this.xmppService = xmpp;
  12872. eventEmitter = emitter;
  12873. // Message listener that talks to POPUP window
  12874. function listener(event) {
  12875. if (event.data && event.data.sessionId) {
  12876. if (event.origin !== window.location.origin) {
  12877. console.warn(
  12878. "Ignoring sessionId from different origin: " + event.origin);
  12879. return;
  12880. }
  12881. localStorage.setItem('sessionId', event.data.sessionId);
  12882. // After popup is closed we will authenticate
  12883. }
  12884. }
  12885. // Register
  12886. if (window.addEventListener) {
  12887. window.addEventListener("message", listener, false);
  12888. } else {
  12889. window.attachEvent("onmessage", listener);
  12890. }
  12891. },
  12892. onMucLeft: function (jid) {
  12893. console.info("Someone left is it focus ? " + jid);
  12894. var resource = Strophe.getResourceFromJid(jid);
  12895. if (resource === 'focus' && !this.xmppService.sessionTerminated) {
  12896. console.info(
  12897. "Focus has left the room - leaving conference");
  12898. //hangUp();
  12899. // We'd rather reload to have everything re-initialized
  12900. // FIXME: show some message before reload
  12901. location.reload();
  12902. }
  12903. },
  12904. setFocusUserJid: function (focusJid) {
  12905. if (!focusUserJid) {
  12906. focusUserJid = focusJid;
  12907. console.info("Focus jid set to: " + focusUserJid);
  12908. }
  12909. },
  12910. getFocusUserJid: function () {
  12911. return focusUserJid;
  12912. },
  12913. getFocusComponent: function () {
  12914. // Get focus component address
  12915. var focusComponent = config.hosts.focus;
  12916. // If not specified use default: 'focus.domain'
  12917. if (!focusComponent) {
  12918. focusComponent = 'focus.' + config.hosts.domain;
  12919. }
  12920. return focusComponent;
  12921. },
  12922. createConferenceIq: function (roomName) {
  12923. // Generate create conference IQ
  12924. var elem = $iq({to: Moderator.getFocusComponent(), type: 'set'});
  12925. // Session Id used for authentication
  12926. var sessionId = localStorage.getItem('sessionId');
  12927. var machineUID = Settings.getSettings().uid;
  12928. console.info(
  12929. "Session ID: " + sessionId + " machine UID: " + machineUID);
  12930. elem.c('conference', {
  12931. xmlns: 'http://jitsi.org/protocol/focus',
  12932. room: roomName,
  12933. 'machine-uid': machineUID
  12934. });
  12935. if (sessionId) {
  12936. elem.attrs({ 'session-id': sessionId});
  12937. }
  12938. if (config.hosts.bridge !== undefined) {
  12939. elem.c(
  12940. 'property',
  12941. { name: 'bridge', value: config.hosts.bridge})
  12942. .up();
  12943. }
  12944. // Tell the focus we have Jigasi configured
  12945. if (config.hosts.call_control !== undefined) {
  12946. elem.c(
  12947. 'property',
  12948. { name: 'call_control', value: config.hosts.call_control})
  12949. .up();
  12950. }
  12951. if (config.channelLastN !== undefined) {
  12952. elem.c(
  12953. 'property',
  12954. { name: 'channelLastN', value: config.channelLastN})
  12955. .up();
  12956. }
  12957. if (config.adaptiveLastN !== undefined) {
  12958. elem.c(
  12959. 'property',
  12960. { name: 'adaptiveLastN', value: config.adaptiveLastN})
  12961. .up();
  12962. }
  12963. if (config.adaptiveSimulcast !== undefined) {
  12964. elem.c(
  12965. 'property',
  12966. { name: 'adaptiveSimulcast', value: config.adaptiveSimulcast})
  12967. .up();
  12968. }
  12969. if (config.openSctp !== undefined) {
  12970. elem.c(
  12971. 'property',
  12972. { name: 'openSctp', value: config.openSctp})
  12973. .up();
  12974. }
  12975. if (config.enableFirefoxSupport !== undefined) {
  12976. elem.c(
  12977. 'property',
  12978. { name: 'enableFirefoxHacks',
  12979. value: config.enableFirefoxSupport})
  12980. .up();
  12981. }
  12982. elem.up();
  12983. return elem;
  12984. },
  12985. parseConfigOptions: function (resultIq) {
  12986. Moderator.setFocusUserJid(
  12987. $(resultIq).find('conference').attr('focusjid'));
  12988. var authenticationEnabled
  12989. = $(resultIq).find(
  12990. '>conference>property' +
  12991. '[name=\'authentication\'][value=\'true\']').length > 0;
  12992. console.info("Authentication enabled: " + authenticationEnabled);
  12993. externalAuthEnabled
  12994. = $(resultIq).find(
  12995. '>conference>property' +
  12996. '[name=\'externalAuth\'][value=\'true\']').length > 0;
  12997. console.info('External authentication enabled: ' + externalAuthEnabled);
  12998. if (!externalAuthEnabled) {
  12999. // We expect to receive sessionId in 'internal' authentication mode
  13000. var sessionId
  13001. = $(resultIq).find('conference').attr('session-id');
  13002. if (sessionId) {
  13003. console.info('Received sessionId: ' + sessionId);
  13004. localStorage.setItem('sessionId', sessionId);
  13005. }
  13006. }
  13007. var authIdentity = $(resultIq).find('>conference').attr('identity');
  13008. eventEmitter.emit(AuthenticationEvents.IDENTITY_UPDATED,
  13009. authenticationEnabled, authIdentity);
  13010. // Check if focus has auto-detected Jigasi component(this will be also
  13011. // included if we have passed our host from the config)
  13012. if ($(resultIq).find(
  13013. '>conference>property' +
  13014. '[name=\'sipGatewayEnabled\'][value=\'true\']').length) {
  13015. sipGatewayEnabled = true;
  13016. }
  13017. console.info("Sip gateway enabled: " + sipGatewayEnabled);
  13018. },
  13019. // FIXME: we need to show the fact that we're waiting for the focus
  13020. // to the user(or that focus is not available)
  13021. allocateConferenceFocus: function (roomName, callback) {
  13022. // Try to use focus user JID from the config
  13023. Moderator.setFocusUserJid(config.focusUserJid);
  13024. // Send create conference IQ
  13025. var iq = Moderator.createConferenceIq(roomName);
  13026. var self = this;
  13027. connection.sendIQ(
  13028. iq,
  13029. function (result) {
  13030. // Setup config options
  13031. Moderator.parseConfigOptions(result);
  13032. if ('true' === $(result).find('conference').attr('ready')) {
  13033. // Reset both timers
  13034. getNextTimeout(true);
  13035. getNextErrorTimeout(true);
  13036. // Exec callback
  13037. callback();
  13038. } else {
  13039. var waitMs = getNextTimeout();
  13040. console.info("Waiting for the focus... " + waitMs);
  13041. // Reset error timeout
  13042. getNextErrorTimeout(true);
  13043. window.setTimeout(
  13044. function () {
  13045. Moderator.allocateConferenceFocus(
  13046. roomName, callback);
  13047. }, waitMs);
  13048. }
  13049. },
  13050. function (error) {
  13051. // Invalid session ? remove and try again
  13052. // without session ID to get a new one
  13053. var invalidSession
  13054. = $(error).find('>error>session-invalid').length;
  13055. if (invalidSession) {
  13056. console.info("Session expired! - removing");
  13057. localStorage.removeItem("sessionId");
  13058. }
  13059. if ($(error).find('>error>graceful-shutdown').length) {
  13060. eventEmitter.emit(XMPPEvents.GRACEFUL_SHUTDOWN);
  13061. return;
  13062. }
  13063. // Check for error returned by the reservation system
  13064. var reservationErr = $(error).find('>error>reservation-error');
  13065. if (reservationErr.length) {
  13066. // Trigger error event
  13067. var errorCode = reservationErr.attr('error-code');
  13068. var errorMsg;
  13069. if ($(error).find('>error>text')) {
  13070. errorMsg = $(error).find('>error>text').text();
  13071. }
  13072. eventEmitter.emit(
  13073. XMPPEvents.RESERVATION_ERROR, errorCode, errorMsg);
  13074. return;
  13075. }
  13076. // Not authorized to create new room
  13077. if ($(error).find('>error>not-authorized').length) {
  13078. console.warn("Unauthorized to start the conference", error);
  13079. var toDomain
  13080. = Strophe.getDomainFromJid(error.getAttribute('to'));
  13081. if (toDomain === config.hosts.anonymousdomain) {
  13082. // we are connected with anonymous domain and
  13083. // only non anonymous users can create rooms
  13084. // we must authorize the user
  13085. self.xmppService.promptLogin();
  13086. } else {
  13087. // External authentication mode
  13088. eventEmitter.emit(
  13089. XMPPEvents.AUTHENTICATION_REQUIRED,
  13090. function () {
  13091. Moderator.allocateConferenceFocus(
  13092. roomName, callback);
  13093. });
  13094. }
  13095. return;
  13096. }
  13097. var waitMs = getNextErrorTimeout();
  13098. console.error("Focus error, retry after " + waitMs, error);
  13099. // Show message
  13100. var focusComponent = Moderator.getFocusComponent();
  13101. var retrySec = waitMs / 1000;
  13102. // FIXME: message is duplicated ?
  13103. // Do not show in case of session invalid
  13104. // which means just a retry
  13105. if (!invalidSession) {
  13106. APP.UI.messageHandler.notify(
  13107. null, "notify.focus",
  13108. 'disconnected', "notify.focusFail",
  13109. {component: focusComponent, ms: retrySec});
  13110. }
  13111. // Reset response timeout
  13112. getNextTimeout(true);
  13113. window.setTimeout(
  13114. function () {
  13115. Moderator.allocateConferenceFocus(roomName, callback);
  13116. }, waitMs);
  13117. }
  13118. );
  13119. },
  13120. getLoginUrl: function (roomName, urlCallback) {
  13121. var iq = $iq({to: Moderator.getFocusComponent(), type: 'get'});
  13122. iq.c('login-url', {
  13123. xmlns: 'http://jitsi.org/protocol/focus',
  13124. room: roomName,
  13125. 'machine-uid': Settings.getSettings().uid
  13126. });
  13127. connection.sendIQ(
  13128. iq,
  13129. function (result) {
  13130. var url = $(result).find('login-url').attr('url');
  13131. url = url = decodeURIComponent(url);
  13132. if (url) {
  13133. console.info("Got auth url: " + url);
  13134. urlCallback(url);
  13135. } else {
  13136. console.error(
  13137. "Failed to get auth url from the focus", result);
  13138. }
  13139. },
  13140. function (error) {
  13141. console.error("Get auth url error", error);
  13142. }
  13143. );
  13144. },
  13145. getPopupLoginUrl: function (roomName, urlCallback) {
  13146. var iq = $iq({to: Moderator.getFocusComponent(), type: 'get'});
  13147. iq.c('login-url', {
  13148. xmlns: 'http://jitsi.org/protocol/focus',
  13149. room: roomName,
  13150. 'machine-uid': Settings.getSettings().uid,
  13151. popup: true
  13152. });
  13153. connection.sendIQ(
  13154. iq,
  13155. function (result) {
  13156. var url = $(result).find('login-url').attr('url');
  13157. url = url = decodeURIComponent(url);
  13158. if (url) {
  13159. console.info("Got POPUP auth url: " + url);
  13160. urlCallback(url);
  13161. } else {
  13162. console.error(
  13163. "Failed to get POPUP auth url from the focus", result);
  13164. }
  13165. },
  13166. function (error) {
  13167. console.error('Get POPUP auth url error', error);
  13168. }
  13169. );
  13170. },
  13171. logout: function (callback) {
  13172. var iq = $iq({to: Moderator.getFocusComponent(), type: 'set'});
  13173. var sessionId = localStorage.getItem('sessionId');
  13174. if (!sessionId) {
  13175. callback();
  13176. return;
  13177. }
  13178. iq.c('logout', {
  13179. xmlns: 'http://jitsi.org/protocol/focus',
  13180. 'session-id': sessionId
  13181. });
  13182. connection.sendIQ(
  13183. iq,
  13184. function (result) {
  13185. var logoutUrl = $(result).find('logout').attr('logout-url');
  13186. if (logoutUrl) {
  13187. logoutUrl = decodeURIComponent(logoutUrl);
  13188. }
  13189. console.info("Log out OK, url: " + logoutUrl, result);
  13190. localStorage.removeItem('sessionId');
  13191. callback(logoutUrl);
  13192. },
  13193. function (error) {
  13194. console.error("Logout error", error);
  13195. }
  13196. );
  13197. }
  13198. };
  13199. module.exports = Moderator;
  13200. },{"../../service/authentication/AuthenticationEvents":92,"../../service/xmpp/XMPPEvents":96,"../settings/Settings":37}],53:[function(require,module,exports){
  13201. /* global $, $iq, config, connection, focusMucJid, messageHandler, Moderator,
  13202. Toolbar, Util */
  13203. var Moderator = require("./moderator");
  13204. var recordingToken = null;
  13205. var recordingEnabled;
  13206. /**
  13207. * Whether to use a jirecon component for recording, or use the videobridge
  13208. * through COLIBRI.
  13209. */
  13210. var useJirecon = (typeof config.hosts.jirecon != "undefined");
  13211. /**
  13212. * The ID of the jirecon recording session. Jirecon generates it when we
  13213. * initially start recording, and it needs to be used in subsequent requests
  13214. * to jirecon.
  13215. */
  13216. var jireconRid = null;
  13217. function setRecordingToken(token) {
  13218. recordingToken = token;
  13219. }
  13220. function setRecording(state, token, callback, connection) {
  13221. if (useJirecon){
  13222. setRecordingJirecon(state, token, callback, connection);
  13223. } else {
  13224. setRecordingColibri(state, token, callback, connection);
  13225. }
  13226. }
  13227. function setRecordingJirecon(state, token, callback, connection) {
  13228. if (state == recordingEnabled){
  13229. return;
  13230. }
  13231. var iq = $iq({to: config.hosts.jirecon, type: 'set'})
  13232. .c('recording', {xmlns: 'http://jitsi.org/protocol/jirecon',
  13233. action: state ? 'start' : 'stop',
  13234. mucjid: connection.emuc.roomjid});
  13235. if (!state){
  13236. iq.attrs({rid: jireconRid});
  13237. }
  13238. console.log('Start recording');
  13239. connection.sendIQ(
  13240. iq,
  13241. function (result) {
  13242. // TODO wait for an IQ with the real status, since this is
  13243. // provisional?
  13244. jireconRid = $(result).find('recording').attr('rid');
  13245. console.log('Recording ' + (state ? 'started' : 'stopped') +
  13246. '(jirecon)' + result);
  13247. recordingEnabled = state;
  13248. if (!state){
  13249. jireconRid = null;
  13250. }
  13251. callback(state);
  13252. },
  13253. function (error) {
  13254. console.log('Failed to start recording, error: ', error);
  13255. callback(recordingEnabled);
  13256. });
  13257. }
  13258. // Sends a COLIBRI message which enables or disables (according to 'state')
  13259. // the recording on the bridge. Waits for the result IQ and calls 'callback'
  13260. // with the new recording state, according to the IQ.
  13261. function setRecordingColibri(state, token, callback, connection) {
  13262. var elem = $iq({to: connection.emuc.focusMucJid, type: 'set'});
  13263. elem.c('conference', {
  13264. xmlns: 'http://jitsi.org/protocol/colibri'
  13265. });
  13266. elem.c('recording', {state: state, token: token});
  13267. connection.sendIQ(elem,
  13268. function (result) {
  13269. console.log('Set recording "', state, '". Result:', result);
  13270. var recordingElem = $(result).find('>conference>recording');
  13271. var newState = ('true' === recordingElem.attr('state'));
  13272. recordingEnabled = newState;
  13273. callback(newState);
  13274. },
  13275. function (error) {
  13276. console.warn(error);
  13277. callback(recordingEnabled);
  13278. }
  13279. );
  13280. }
  13281. var Recording = {
  13282. toggleRecording: function (tokenEmptyCallback,
  13283. startingCallback, startedCallback, connection) {
  13284. if (!Moderator.isModerator()) {
  13285. console.log(
  13286. 'non-focus, or conference not yet organized:' +
  13287. ' not enabling recording');
  13288. return;
  13289. }
  13290. var self = this;
  13291. // Jirecon does not (currently) support a token.
  13292. if (!recordingToken && !useJirecon) {
  13293. tokenEmptyCallback(function (value) {
  13294. setRecordingToken(value);
  13295. self.toggleRecording(tokenEmptyCallback,
  13296. startingCallback, startedCallback, connection);
  13297. });
  13298. return;
  13299. }
  13300. var oldState = recordingEnabled;
  13301. startingCallback(!oldState);
  13302. setRecording(!oldState,
  13303. recordingToken,
  13304. function (state) {
  13305. console.log("New recording state: ", state);
  13306. if (state === oldState) {
  13307. // FIXME: new focus:
  13308. // this will not work when moderator changes
  13309. // during active session. Then it will assume that
  13310. // recording status has changed to true, but it might have
  13311. // been already true(and we only received actual status from
  13312. // the focus).
  13313. //
  13314. // SO we start with status null, so that it is initialized
  13315. // here and will fail only after second click, so if invalid
  13316. // token was used we have to press the button twice before
  13317. // current status will be fetched and token will be reset.
  13318. //
  13319. // Reliable way would be to return authentication error.
  13320. // Or status update when moderator connects.
  13321. // Or we have to stop recording session when current
  13322. // moderator leaves the room.
  13323. // Failed to change, reset the token because it might
  13324. // have been wrong
  13325. setRecordingToken(null);
  13326. }
  13327. startedCallback(state);
  13328. },
  13329. connection
  13330. );
  13331. }
  13332. }
  13333. module.exports = Recording;
  13334. },{"./moderator":52}],54:[function(require,module,exports){
  13335. /* jshint -W117 */
  13336. /* a simple MUC connection plugin
  13337. * can only handle a single MUC room
  13338. */
  13339. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  13340. var Moderator = require("./moderator");
  13341. var JingleSession = require("./JingleSession");
  13342. var bridgeIsDown = false;
  13343. module.exports = function(XMPP, eventEmitter) {
  13344. Strophe.addConnectionPlugin('emuc', {
  13345. connection: null,
  13346. roomjid: null,
  13347. myroomjid: null,
  13348. members: {},
  13349. list_members: [], // so we can elect a new focus
  13350. presMap: {},
  13351. preziMap: {},
  13352. joined: false,
  13353. isOwner: false,
  13354. role: null,
  13355. focusMucJid: null,
  13356. ssrc2jid: {},
  13357. init: function (conn) {
  13358. this.connection = conn;
  13359. },
  13360. initPresenceMap: function (myroomjid) {
  13361. this.presMap['to'] = myroomjid;
  13362. this.presMap['xns'] = 'http://jabber.org/protocol/muc';
  13363. },
  13364. doJoin: function (jid, password) {
  13365. this.myroomjid = jid;
  13366. console.info("Joined MUC as " + this.myroomjid);
  13367. this.initPresenceMap(this.myroomjid);
  13368. if (!this.roomjid) {
  13369. this.roomjid = Strophe.getBareJidFromJid(jid);
  13370. // add handlers (just once)
  13371. this.connection.addHandler(this.onPresence.bind(this), null, 'presence', null, null, this.roomjid, {matchBare: true});
  13372. this.connection.addHandler(this.onPresenceUnavailable.bind(this), null, 'presence', 'unavailable', null, this.roomjid, {matchBare: true});
  13373. this.connection.addHandler(this.onPresenceError.bind(this), null, 'presence', 'error', null, this.roomjid, {matchBare: true});
  13374. this.connection.addHandler(this.onMessage.bind(this), null, 'message', null, null, this.roomjid, {matchBare: true});
  13375. }
  13376. if (password !== undefined) {
  13377. this.presMap['password'] = password;
  13378. }
  13379. this.sendPresence();
  13380. },
  13381. doLeave: function () {
  13382. console.log("do leave", this.myroomjid);
  13383. var pres = $pres({to: this.myroomjid, type: 'unavailable' });
  13384. this.presMap.length = 0;
  13385. this.connection.send(pres);
  13386. },
  13387. createNonAnonymousRoom: function () {
  13388. // http://xmpp.org/extensions/xep-0045.html#createroom-reserved
  13389. var getForm = $iq({type: 'get', to: this.roomjid})
  13390. .c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'})
  13391. .c('x', {xmlns: 'jabber:x:data', type: 'submit'});
  13392. var self = this;
  13393. this.connection.sendIQ(getForm, function (form) {
  13394. if (!$(form).find(
  13395. '>query>x[xmlns="jabber:x:data"]' +
  13396. '>field[var="muc#roomconfig_whois"]').length) {
  13397. console.error('non-anonymous rooms not supported');
  13398. return;
  13399. }
  13400. var formSubmit = $iq({to: this.roomjid, type: 'set'})
  13401. .c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'});
  13402. formSubmit.c('x', {xmlns: 'jabber:x:data', type: 'submit'});
  13403. formSubmit.c('field', {'var': 'FORM_TYPE'})
  13404. .c('value')
  13405. .t('http://jabber.org/protocol/muc#roomconfig').up().up();
  13406. formSubmit.c('field', {'var': 'muc#roomconfig_whois'})
  13407. .c('value').t('anyone').up().up();
  13408. self.connection.sendIQ(formSubmit);
  13409. }, function (error) {
  13410. console.error("Error getting room configuration form");
  13411. });
  13412. },
  13413. onPresence: function (pres) {
  13414. var from = pres.getAttribute('from');
  13415. // What is this for? A workaround for something?
  13416. if (pres.getAttribute('type')) {
  13417. return true;
  13418. }
  13419. // Parse etherpad tag.
  13420. var etherpad = $(pres).find('>etherpad');
  13421. if (etherpad.length) {
  13422. if (config.etherpad_base && !Moderator.isModerator()) {
  13423. eventEmitter.emit(XMPPEvents.ETHERPAD, etherpad.text());
  13424. }
  13425. }
  13426. // Parse prezi tag.
  13427. var presentation = $(pres).find('>prezi');
  13428. if (presentation.length) {
  13429. var url = presentation.attr('url');
  13430. var current = presentation.find('>current').text();
  13431. console.log('presentation info received from', from, url);
  13432. if (this.preziMap[from] == null) {
  13433. this.preziMap[from] = url;
  13434. $(document).trigger('presentationadded.muc', [from, url, current]);
  13435. }
  13436. else {
  13437. $(document).trigger('gotoslide.muc', [from, url, current]);
  13438. }
  13439. }
  13440. else if (this.preziMap[from] != null) {
  13441. var url = this.preziMap[from];
  13442. delete this.preziMap[from];
  13443. $(document).trigger('presentationremoved.muc', [from, url]);
  13444. }
  13445. // Parse audio info tag.
  13446. var audioMuted = $(pres).find('>audiomuted');
  13447. if (audioMuted.length) {
  13448. $(document).trigger('audiomuted.muc', [from, audioMuted.text()]);
  13449. }
  13450. // Parse video info tag.
  13451. var videoMuted = $(pres).find('>videomuted');
  13452. if (videoMuted.length) {
  13453. $(document).trigger('videomuted.muc', [from, videoMuted.text()]);
  13454. }
  13455. var stats = $(pres).find('>stats');
  13456. if (stats.length) {
  13457. var statsObj = {};
  13458. Strophe.forEachChild(stats[0], "stat", function (el) {
  13459. statsObj[el.getAttribute("name")] = el.getAttribute("value");
  13460. });
  13461. eventEmitter.emit(XMPPEvents.REMOTE_STATS, from, statsObj);
  13462. }
  13463. // Parse status.
  13464. if ($(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>status[code="201"]').length) {
  13465. this.isOwner = true;
  13466. this.createNonAnonymousRoom();
  13467. }
  13468. // Parse roles.
  13469. var member = {};
  13470. member.show = $(pres).find('>show').text();
  13471. member.status = $(pres).find('>status').text();
  13472. var tmp = $(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>item');
  13473. member.affiliation = tmp.attr('affiliation');
  13474. member.role = tmp.attr('role');
  13475. // Focus recognition
  13476. member.jid = tmp.attr('jid');
  13477. member.isFocus = false;
  13478. if (member.jid
  13479. && member.jid.indexOf(Moderator.getFocusUserJid() + "/") == 0) {
  13480. member.isFocus = true;
  13481. }
  13482. var nicktag = $(pres).find('>nick[xmlns="http://jabber.org/protocol/nick"]');
  13483. member.displayName = (nicktag.length > 0 ? nicktag.html() : null);
  13484. if (from == this.myroomjid) {
  13485. if (member.affiliation == 'owner') this.isOwner = true;
  13486. if (this.role !== member.role) {
  13487. this.role = member.role;
  13488. eventEmitter.emit(XMPPEvents.LOCALROLE_CHANGED,
  13489. from, member, pres, Moderator.isModerator());
  13490. }
  13491. if (!this.joined) {
  13492. this.joined = true;
  13493. eventEmitter.emit(XMPPEvents.MUC_JOINED, from, member);
  13494. this.list_members.push(from);
  13495. }
  13496. } else if (this.members[from] === undefined) {
  13497. // new participant
  13498. this.members[from] = member;
  13499. this.list_members.push(from);
  13500. console.log('entered', from, member);
  13501. if (member.isFocus) {
  13502. this.focusMucJid = from;
  13503. console.info("Ignore focus: " + from + ", real JID: " + member.jid);
  13504. }
  13505. else {
  13506. var id = $(pres).find('>userID').text();
  13507. var email = $(pres).find('>email');
  13508. if (email.length > 0) {
  13509. id = email.text();
  13510. }
  13511. eventEmitter.emit(XMPPEvents.MUC_ENTER, from, id, member.displayName);
  13512. }
  13513. } else {
  13514. // Presence update for existing participant
  13515. // Watch role change:
  13516. if (this.members[from].role != member.role) {
  13517. this.members[from].role = member.role;
  13518. eventEmitter.emit(XMPPEvents.MUC_ROLE_CHANGED,
  13519. member.role, member.displayName);
  13520. }
  13521. }
  13522. // Always trigger presence to update bindings
  13523. this.parsePresence(from, member, pres);
  13524. // Trigger status message update
  13525. if (member.status) {
  13526. eventEmitter.emit(XMPPEvents.PRESENCE_STATUS, from, member);
  13527. }
  13528. return true;
  13529. },
  13530. onPresenceUnavailable: function (pres) {
  13531. var from = pres.getAttribute('from');
  13532. // room destroyed ?
  13533. if ($(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]' +
  13534. '>destroy').length) {
  13535. var reason;
  13536. var reasonSelect = $(pres).find(
  13537. '>x[xmlns="http://jabber.org/protocol/muc#user"]' +
  13538. '>destroy>reason');
  13539. if (reasonSelect.length) {
  13540. reason = reasonSelect.text();
  13541. }
  13542. XMPP.disposeConference(false);
  13543. eventEmitter.emit(XMPPEvents.MUC_DESTROYED, reason);
  13544. return true;
  13545. }
  13546. // Status code 110 indicates that this notification is "self-presence".
  13547. if (!$(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>status[code="110"]').length) {
  13548. delete this.members[from];
  13549. this.list_members.splice(this.list_members.indexOf(from), 1);
  13550. this.onParticipantLeft(from);
  13551. }
  13552. // If the status code is 110 this means we're leaving and we would like
  13553. // to remove everyone else from our view, so we trigger the event.
  13554. else if (this.list_members.length > 1) {
  13555. for (var i = 0; i < this.list_members.length; i++) {
  13556. var member = this.list_members[i];
  13557. delete this.members[i];
  13558. this.list_members.splice(i, 1);
  13559. this.onParticipantLeft(member);
  13560. }
  13561. }
  13562. if ($(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>status[code="307"]').length) {
  13563. $(document).trigger('kicked.muc', [from]);
  13564. if (this.myroomjid === from) {
  13565. XMPP.disposeConference(false);
  13566. eventEmitter.emit(XMPPEvents.KICKED);
  13567. }
  13568. }
  13569. return true;
  13570. },
  13571. onPresenceError: function (pres) {
  13572. var from = pres.getAttribute('from');
  13573. if ($(pres).find('>error[type="auth"]>not-authorized[xmlns="urn:ietf:params:xml:ns:xmpp-stanzas"]').length) {
  13574. console.log('on password required', from);
  13575. var self = this;
  13576. eventEmitter.emit(XMPPEvents.PASSWORD_REQUIRED, function (value) {
  13577. self.doJoin(from, value);
  13578. });
  13579. } else if ($(pres).find(
  13580. '>error[type="cancel"]>not-allowed[xmlns="urn:ietf:params:xml:ns:xmpp-stanzas"]').length) {
  13581. var toDomain = Strophe.getDomainFromJid(pres.getAttribute('to'));
  13582. if (toDomain === config.hosts.anonymousdomain) {
  13583. // enter the room by replying with 'not-authorized'. This would
  13584. // result in reconnection from authorized domain.
  13585. // We're either missing Jicofo/Prosody config for anonymous
  13586. // domains or something is wrong.
  13587. // XMPP.promptLogin();
  13588. APP.UI.messageHandler.openReportDialog(null,
  13589. "dialog.joinError", pres);
  13590. } else {
  13591. console.warn('onPresError ', pres);
  13592. APP.UI.messageHandler.openReportDialog(null,
  13593. "dialog.connectError",
  13594. pres);
  13595. }
  13596. } else {
  13597. console.warn('onPresError ', pres);
  13598. APP.UI.messageHandler.openReportDialog(null,
  13599. "dialog.connectError",
  13600. pres);
  13601. }
  13602. return true;
  13603. },
  13604. sendMessage: function (body, nickname) {
  13605. var msg = $msg({to: this.roomjid, type: 'groupchat'});
  13606. msg.c('body', body).up();
  13607. if (nickname) {
  13608. msg.c('nick', {xmlns: 'http://jabber.org/protocol/nick'}).t(nickname).up().up();
  13609. }
  13610. this.connection.send(msg);
  13611. eventEmitter.emit(XMPPEvents.SENDING_CHAT_MESSAGE, body);
  13612. },
  13613. setSubject: function (subject) {
  13614. var msg = $msg({to: this.roomjid, type: 'groupchat'});
  13615. msg.c('subject', subject);
  13616. this.connection.send(msg);
  13617. console.log("topic changed to " + subject);
  13618. },
  13619. onMessage: function (msg) {
  13620. // FIXME: this is a hack. but jingle on muc makes nickchanges hard
  13621. var from = msg.getAttribute('from');
  13622. var nick =
  13623. $(msg).find('>nick[xmlns="http://jabber.org/protocol/nick"]')
  13624. .text() ||
  13625. Strophe.getResourceFromJid(from);
  13626. var txt = $(msg).find('>body').text();
  13627. var type = msg.getAttribute("type");
  13628. if (type == "error") {
  13629. eventEmitter.emit(XMPPEvents.CHAT_ERROR_RECEIVED,
  13630. $(msg).find('>text').text(), txt);
  13631. return true;
  13632. }
  13633. var subject = $(msg).find('>subject');
  13634. if (subject.length) {
  13635. var subjectText = subject.text();
  13636. if (subjectText || subjectText == "") {
  13637. eventEmitter.emit(XMPPEvents.SUBJECT_CHANGED, subjectText);
  13638. console.log("Subject is changed to " + subjectText);
  13639. }
  13640. }
  13641. if (txt) {
  13642. console.log('chat', nick, txt);
  13643. eventEmitter.emit(XMPPEvents.MESSAGE_RECEIVED,
  13644. from, nick, txt, this.myroomjid);
  13645. }
  13646. return true;
  13647. },
  13648. lockRoom: function (key, onSuccess, onError, onNotSupported) {
  13649. //http://xmpp.org/extensions/xep-0045.html#roomconfig
  13650. var ob = this;
  13651. this.connection.sendIQ($iq({to: this.roomjid, type: 'get'}).c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'}),
  13652. function (res) {
  13653. if ($(res).find('>query>x[xmlns="jabber:x:data"]>field[var="muc#roomconfig_roomsecret"]').length) {
  13654. var formsubmit = $iq({to: ob.roomjid, type: 'set'}).c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'});
  13655. formsubmit.c('x', {xmlns: 'jabber:x:data', type: 'submit'});
  13656. formsubmit.c('field', {'var': 'FORM_TYPE'}).c('value').t('http://jabber.org/protocol/muc#roomconfig').up().up();
  13657. formsubmit.c('field', {'var': 'muc#roomconfig_roomsecret'}).c('value').t(key).up().up();
  13658. // Fixes a bug in prosody 0.9.+ https://code.google.com/p/lxmppd/issues/detail?id=373
  13659. formsubmit.c('field', {'var': 'muc#roomconfig_whois'}).c('value').t('anyone').up().up();
  13660. // FIXME: is muc#roomconfig_passwordprotectedroom required?
  13661. ob.connection.sendIQ(formsubmit,
  13662. onSuccess,
  13663. onError);
  13664. } else {
  13665. onNotSupported();
  13666. }
  13667. }, onError);
  13668. },
  13669. kick: function (jid) {
  13670. var kickIQ = $iq({to: this.roomjid, type: 'set'})
  13671. .c('query', {xmlns: 'http://jabber.org/protocol/muc#admin'})
  13672. .c('item', {nick: Strophe.getResourceFromJid(jid), role: 'none'})
  13673. .c('reason').t('You have been kicked.').up().up().up();
  13674. this.connection.sendIQ(
  13675. kickIQ,
  13676. function (result) {
  13677. console.log('Kick participant with jid: ', jid, result);
  13678. },
  13679. function (error) {
  13680. console.log('Kick participant error: ', error);
  13681. });
  13682. },
  13683. sendPresence: function () {
  13684. var pres = $pres({to: this.presMap['to'] });
  13685. pres.c('x', {xmlns: this.presMap['xns']});
  13686. if (this.presMap['password']) {
  13687. pres.c('password').t(this.presMap['password']).up();
  13688. }
  13689. pres.up();
  13690. // Send XEP-0115 'c' stanza that contains our capabilities info
  13691. if (this.connection.caps) {
  13692. this.connection.caps.node = config.clientNode;
  13693. pres.c('c', this.connection.caps.generateCapsAttrs()).up();
  13694. }
  13695. pres.c('user-agent', {xmlns: 'http://jitsi.org/jitmeet/user-agent'})
  13696. .t(navigator.userAgent).up();
  13697. if (this.presMap['bridgeIsDown']) {
  13698. pres.c('bridgeIsDown').up();
  13699. }
  13700. if (this.presMap['email']) {
  13701. pres.c('email').t(this.presMap['email']).up();
  13702. }
  13703. if (this.presMap['userId']) {
  13704. pres.c('userId').t(this.presMap['userId']).up();
  13705. }
  13706. if (this.presMap['displayName']) {
  13707. // XEP-0172
  13708. pres.c('nick', {xmlns: 'http://jabber.org/protocol/nick'})
  13709. .t(this.presMap['displayName']).up();
  13710. }
  13711. if (this.presMap['audions']) {
  13712. pres.c('audiomuted', {xmlns: this.presMap['audions']})
  13713. .t(this.presMap['audiomuted']).up();
  13714. }
  13715. if (this.presMap['videons']) {
  13716. pres.c('videomuted', {xmlns: this.presMap['videons']})
  13717. .t(this.presMap['videomuted']).up();
  13718. }
  13719. if (this.presMap['statsns']) {
  13720. var stats = pres.c('stats', {xmlns: this.presMap['statsns']});
  13721. for (var stat in this.presMap["stats"])
  13722. if (this.presMap["stats"][stat] != null)
  13723. stats.c("stat", {name: stat, value: this.presMap["stats"][stat]}).up();
  13724. pres.up();
  13725. }
  13726. if (this.presMap['prezins']) {
  13727. pres.c('prezi',
  13728. {xmlns: this.presMap['prezins'],
  13729. 'url': this.presMap['preziurl']})
  13730. .c('current').t(this.presMap['prezicurrent']).up().up();
  13731. }
  13732. if (this.presMap['etherpadns']) {
  13733. pres.c('etherpad', {xmlns: this.presMap['etherpadns']})
  13734. .t(this.presMap['etherpadname']).up();
  13735. }
  13736. if (this.presMap['medians']) {
  13737. pres.c('media', {xmlns: this.presMap['medians']});
  13738. var sourceNumber = 0;
  13739. Object.keys(this.presMap).forEach(function (key) {
  13740. if (key.indexOf('source') >= 0) {
  13741. sourceNumber++;
  13742. }
  13743. });
  13744. if (sourceNumber > 0)
  13745. for (var i = 1; i <= sourceNumber / 3; i++) {
  13746. pres.c('source',
  13747. {type: this.presMap['source' + i + '_type'],
  13748. ssrc: this.presMap['source' + i + '_ssrc'],
  13749. direction: this.presMap['source' + i + '_direction']
  13750. || 'sendrecv' }
  13751. ).up();
  13752. }
  13753. }
  13754. pres.up();
  13755. this.connection.send(pres);
  13756. },
  13757. addDisplayNameToPresence: function (displayName) {
  13758. this.presMap['displayName'] = displayName;
  13759. },
  13760. addMediaToPresence: function (sourceNumber, mtype, ssrcs, direction) {
  13761. if (!this.presMap['medians'])
  13762. this.presMap['medians'] = 'http://estos.de/ns/mjs';
  13763. this.presMap['source' + sourceNumber + '_type'] = mtype;
  13764. this.presMap['source' + sourceNumber + '_ssrc'] = ssrcs;
  13765. this.presMap['source' + sourceNumber + '_direction'] = direction;
  13766. },
  13767. clearPresenceMedia: function () {
  13768. var self = this;
  13769. Object.keys(this.presMap).forEach(function (key) {
  13770. if (key.indexOf('source') != -1) {
  13771. delete self.presMap[key];
  13772. }
  13773. });
  13774. },
  13775. addPreziToPresence: function (url, currentSlide) {
  13776. this.presMap['prezins'] = 'http://jitsi.org/jitmeet/prezi';
  13777. this.presMap['preziurl'] = url;
  13778. this.presMap['prezicurrent'] = currentSlide;
  13779. },
  13780. removePreziFromPresence: function () {
  13781. delete this.presMap['prezins'];
  13782. delete this.presMap['preziurl'];
  13783. delete this.presMap['prezicurrent'];
  13784. },
  13785. addCurrentSlideToPresence: function (currentSlide) {
  13786. this.presMap['prezicurrent'] = currentSlide;
  13787. },
  13788. getPrezi: function (roomjid) {
  13789. return this.preziMap[roomjid];
  13790. },
  13791. addEtherpadToPresence: function (etherpadName) {
  13792. this.presMap['etherpadns'] = 'http://jitsi.org/jitmeet/etherpad';
  13793. this.presMap['etherpadname'] = etherpadName;
  13794. },
  13795. addAudioInfoToPresence: function (isMuted) {
  13796. this.presMap['audions'] = 'http://jitsi.org/jitmeet/audio';
  13797. this.presMap['audiomuted'] = isMuted.toString();
  13798. },
  13799. addVideoInfoToPresence: function (isMuted) {
  13800. this.presMap['videons'] = 'http://jitsi.org/jitmeet/video';
  13801. this.presMap['videomuted'] = isMuted.toString();
  13802. },
  13803. addConnectionInfoToPresence: function (stats) {
  13804. this.presMap['statsns'] = 'http://jitsi.org/jitmeet/stats';
  13805. this.presMap['stats'] = stats;
  13806. },
  13807. findJidFromResource: function (resourceJid) {
  13808. if (resourceJid &&
  13809. resourceJid === Strophe.getResourceFromJid(this.myroomjid)) {
  13810. return this.myroomjid;
  13811. }
  13812. var peerJid = null;
  13813. Object.keys(this.members).some(function (jid) {
  13814. peerJid = jid;
  13815. return Strophe.getResourceFromJid(jid) === resourceJid;
  13816. });
  13817. return peerJid;
  13818. },
  13819. addBridgeIsDownToPresence: function () {
  13820. this.presMap['bridgeIsDown'] = true;
  13821. },
  13822. addEmailToPresence: function (email) {
  13823. this.presMap['email'] = email;
  13824. },
  13825. addUserIdToPresence: function (userId) {
  13826. this.presMap['userId'] = userId;
  13827. },
  13828. isModerator: function () {
  13829. return this.role === 'moderator';
  13830. },
  13831. getMemberRole: function (peerJid) {
  13832. if (this.members[peerJid]) {
  13833. return this.members[peerJid].role;
  13834. }
  13835. return null;
  13836. },
  13837. onParticipantLeft: function (jid) {
  13838. eventEmitter.emit(XMPPEvents.MUC_LEFT, jid);
  13839. this.connection.jingle.terminateByJid(jid);
  13840. if (this.getPrezi(jid)) {
  13841. $(document).trigger('presentationremoved.muc',
  13842. [jid, this.getPrezi(jid)]);
  13843. }
  13844. Moderator.onMucLeft(jid);
  13845. },
  13846. parsePresence: function (from, memeber, pres) {
  13847. if($(pres).find(">bridgeIsDown").length > 0 && !bridgeIsDown) {
  13848. bridgeIsDown = true;
  13849. eventEmitter.emit(XMPPEvents.BRIDGE_DOWN);
  13850. }
  13851. if(memeber.isFocus)
  13852. return;
  13853. var self = this;
  13854. // Remove old ssrcs coming from the jid
  13855. Object.keys(this.ssrc2jid).forEach(function (ssrc) {
  13856. if (self.ssrc2jid[ssrc] == from) {
  13857. delete self.ssrc2jid[ssrc];
  13858. }
  13859. });
  13860. var changedStreams = [];
  13861. $(pres).find('>media[xmlns="http://estos.de/ns/mjs"]>source').each(function (idx, ssrc) {
  13862. //console.log(jid, 'assoc ssrc', ssrc.getAttribute('type'), ssrc.getAttribute('ssrc'));
  13863. var ssrcV = ssrc.getAttribute('ssrc');
  13864. self.ssrc2jid[ssrcV] = from;
  13865. JingleSession.notReceivedSSRCs.push(ssrcV);
  13866. var type = ssrc.getAttribute('type');
  13867. var direction = ssrc.getAttribute('direction');
  13868. changedStreams.push({type: type, direction: direction});
  13869. });
  13870. eventEmitter.emit(XMPPEvents.CHANGED_STREAMS, from, changedStreams);
  13871. var displayName = !config.displayJids
  13872. ? memeber.displayName : Strophe.getResourceFromJid(from);
  13873. if (displayName && displayName.length > 0)
  13874. {
  13875. eventEmitter.emit(XMPPEvents.DISPLAY_NAME_CHANGED, from, displayName);
  13876. }
  13877. var id = $(pres).find('>userID').text();
  13878. var email = $(pres).find('>email');
  13879. if(email.length > 0) {
  13880. id = email.text();
  13881. }
  13882. eventEmitter.emit(XMPPEvents.USER_ID_CHANGED, from, id);
  13883. }
  13884. });
  13885. };
  13886. },{"../../service/xmpp/XMPPEvents":96,"./JingleSession":47,"./moderator":52}],55:[function(require,module,exports){
  13887. /* jshint -W117 */
  13888. var JingleSession = require("./JingleSession");
  13889. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  13890. module.exports = function(XMPP, eventEmitter)
  13891. {
  13892. function CallIncomingJingle(sid, connection) {
  13893. var sess = connection.jingle.sessions[sid];
  13894. // TODO: do we check activecall == null?
  13895. connection.jingle.activecall = sess;
  13896. eventEmitter.emit(XMPPEvents.CALL_INCOMING, sess);
  13897. // TODO: check affiliation and/or role
  13898. console.log('emuc data for', sess.peerjid, connection.emuc.members[sess.peerjid]);
  13899. sess.usedrip = true; // not-so-naive trickle ice
  13900. sess.sendAnswer();
  13901. sess.accept();
  13902. };
  13903. Strophe.addConnectionPlugin('jingle', {
  13904. connection: null,
  13905. sessions: {},
  13906. jid2session: {},
  13907. ice_config: {iceServers: []},
  13908. pc_constraints: {},
  13909. activecall: null,
  13910. media_constraints: {
  13911. mandatory: {
  13912. 'OfferToReceiveAudio': true,
  13913. 'OfferToReceiveVideo': true
  13914. }
  13915. // MozDontOfferDataChannel: true when this is firefox
  13916. },
  13917. init: function (conn) {
  13918. this.connection = conn;
  13919. if (this.connection.disco) {
  13920. // http://xmpp.org/extensions/xep-0167.html#support
  13921. // http://xmpp.org/extensions/xep-0176.html#support
  13922. this.connection.disco.addFeature('urn:xmpp:jingle:1');
  13923. this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:1');
  13924. this.connection.disco.addFeature('urn:xmpp:jingle:transports:ice-udp:1');
  13925. this.connection.disco.addFeature('urn:xmpp:jingle:transports:dtls-sctp:1');
  13926. this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:audio');
  13927. this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:video');
  13928. // this is dealt with by SDP O/A so we don't need to annouce this
  13929. //this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:rtcp-fb:0'); // XEP-0293
  13930. //this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:rtp-hdrext:0'); // XEP-0294
  13931. if (config.useRtcpMux) {
  13932. this.connection.disco.addFeature('urn:ietf:rfc:5761'); // rtcp-mux
  13933. }
  13934. if (config.useBundle) {
  13935. this.connection.disco.addFeature('urn:ietf:rfc:5888'); // a=group, e.g. bundle
  13936. }
  13937. //this.connection.disco.addFeature('urn:ietf:rfc:5576'); // a=ssrc
  13938. }
  13939. this.connection.addHandler(this.onJingle.bind(this), 'urn:xmpp:jingle:1', 'iq', 'set', null, null);
  13940. },
  13941. onJingle: function (iq) {
  13942. var sid = $(iq).find('jingle').attr('sid');
  13943. var action = $(iq).find('jingle').attr('action');
  13944. var fromJid = iq.getAttribute('from');
  13945. // send ack first
  13946. var ack = $iq({type: 'result',
  13947. to: fromJid,
  13948. id: iq.getAttribute('id')
  13949. });
  13950. console.log('on jingle ' + action + ' from ' + fromJid, iq);
  13951. var sess = this.sessions[sid];
  13952. if ('session-initiate' != action) {
  13953. if (sess === null) {
  13954. ack.type = 'error';
  13955. ack.c('error', {type: 'cancel'})
  13956. .c('item-not-found', {xmlns: 'urn:ietf:params:xml:ns:xmpp-stanzas'}).up()
  13957. .c('unknown-session', {xmlns: 'urn:xmpp:jingle:errors:1'});
  13958. this.connection.send(ack);
  13959. return true;
  13960. }
  13961. // compare from to sess.peerjid (bare jid comparison for later compat with message-mode)
  13962. // local jid is not checked
  13963. if (Strophe.getBareJidFromJid(fromJid) != Strophe.getBareJidFromJid(sess.peerjid)) {
  13964. console.warn('jid mismatch for session id', sid, fromJid, sess.peerjid);
  13965. ack.type = 'error';
  13966. ack.c('error', {type: 'cancel'})
  13967. .c('item-not-found', {xmlns: 'urn:ietf:params:xml:ns:xmpp-stanzas'}).up()
  13968. .c('unknown-session', {xmlns: 'urn:xmpp:jingle:errors:1'});
  13969. this.connection.send(ack);
  13970. return true;
  13971. }
  13972. } else if (sess !== undefined) {
  13973. // existing session with same session id
  13974. // this might be out-of-order if the sess.peerjid is the same as from
  13975. ack.type = 'error';
  13976. ack.c('error', {type: 'cancel'})
  13977. .c('service-unavailable', {xmlns: 'urn:ietf:params:xml:ns:xmpp-stanzas'}).up();
  13978. console.warn('duplicate session id', sid);
  13979. this.connection.send(ack);
  13980. return true;
  13981. }
  13982. // FIXME: check for a defined action
  13983. this.connection.send(ack);
  13984. // see http://xmpp.org/extensions/xep-0166.html#concepts-session
  13985. switch (action) {
  13986. case 'session-initiate':
  13987. sess = new JingleSession(
  13988. $(iq).attr('to'), $(iq).find('jingle').attr('sid'),
  13989. this.connection, XMPP);
  13990. // configure session
  13991. sess.media_constraints = this.media_constraints;
  13992. sess.pc_constraints = this.pc_constraints;
  13993. sess.ice_config = this.ice_config;
  13994. sess.initiate(fromJid, false);
  13995. // FIXME: setRemoteDescription should only be done when this call is to be accepted
  13996. sess.setRemoteDescription($(iq).find('>jingle'), 'offer');
  13997. this.sessions[sess.sid] = sess;
  13998. this.jid2session[sess.peerjid] = sess;
  13999. // the callback should either
  14000. // .sendAnswer and .accept
  14001. // or .sendTerminate -- not necessarily synchronus
  14002. CallIncomingJingle(sess.sid, this.connection);
  14003. break;
  14004. case 'session-accept':
  14005. sess.setRemoteDescription($(iq).find('>jingle'), 'answer');
  14006. sess.accept();
  14007. $(document).trigger('callaccepted.jingle', [sess.sid]);
  14008. break;
  14009. case 'session-terminate':
  14010. // If this is not the focus sending the terminate, we have
  14011. // nothing more to do here.
  14012. if (Object.keys(this.sessions).length < 1
  14013. || !(this.sessions[Object.keys(this.sessions)[0]]
  14014. instanceof JingleSession))
  14015. {
  14016. break;
  14017. }
  14018. console.log('terminating...', sess.sid);
  14019. sess.terminate();
  14020. this.terminate(sess.sid);
  14021. if ($(iq).find('>jingle>reason').length) {
  14022. $(document).trigger('callterminated.jingle', [
  14023. sess.sid,
  14024. sess.peerjid,
  14025. $(iq).find('>jingle>reason>:first')[0].tagName,
  14026. $(iq).find('>jingle>reason>text').text()
  14027. ]);
  14028. } else {
  14029. $(document).trigger('callterminated.jingle',
  14030. [sess.sid, sess.peerjid]);
  14031. }
  14032. break;
  14033. case 'transport-info':
  14034. sess.addIceCandidate($(iq).find('>jingle>content'));
  14035. break;
  14036. case 'session-info':
  14037. var affected;
  14038. if ($(iq).find('>jingle>ringing[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').length) {
  14039. $(document).trigger('ringing.jingle', [sess.sid]);
  14040. } else if ($(iq).find('>jingle>mute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').length) {
  14041. affected = $(iq).find('>jingle>mute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').attr('name');
  14042. $(document).trigger('mute.jingle', [sess.sid, affected]);
  14043. } else if ($(iq).find('>jingle>unmute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').length) {
  14044. affected = $(iq).find('>jingle>unmute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').attr('name');
  14045. $(document).trigger('unmute.jingle', [sess.sid, affected]);
  14046. }
  14047. break;
  14048. case 'addsource': // FIXME: proprietary, un-jingleish
  14049. case 'source-add': // FIXME: proprietary
  14050. sess.addSource($(iq).find('>jingle>content'), fromJid);
  14051. break;
  14052. case 'removesource': // FIXME: proprietary, un-jingleish
  14053. case 'source-remove': // FIXME: proprietary
  14054. sess.removeSource($(iq).find('>jingle>content'), fromJid);
  14055. break;
  14056. default:
  14057. console.warn('jingle action not implemented', action);
  14058. break;
  14059. }
  14060. return true;
  14061. },
  14062. initiate: function (peerjid, myjid) { // initiate a new jinglesession to peerjid
  14063. var sess = new JingleSession(myjid || this.connection.jid,
  14064. Math.random().toString(36).substr(2, 12), // random string
  14065. this.connection, XMPP);
  14066. // configure session
  14067. sess.media_constraints = this.media_constraints;
  14068. sess.pc_constraints = this.pc_constraints;
  14069. sess.ice_config = this.ice_config;
  14070. sess.initiate(peerjid, true);
  14071. this.sessions[sess.sid] = sess;
  14072. this.jid2session[sess.peerjid] = sess;
  14073. sess.sendOffer();
  14074. return sess;
  14075. },
  14076. terminate: function (sid, reason, text) { // terminate by sessionid (or all sessions)
  14077. if (sid === null || sid === undefined) {
  14078. for (sid in this.sessions) {
  14079. if (this.sessions[sid].state != 'ended') {
  14080. this.sessions[sid].sendTerminate(reason || (!this.sessions[sid].active()) ? 'cancel' : null, text);
  14081. this.sessions[sid].terminate();
  14082. }
  14083. delete this.jid2session[this.sessions[sid].peerjid];
  14084. delete this.sessions[sid];
  14085. }
  14086. } else if (this.sessions.hasOwnProperty(sid)) {
  14087. if (this.sessions[sid].state != 'ended') {
  14088. this.sessions[sid].sendTerminate(reason || (!this.sessions[sid].active()) ? 'cancel' : null, text);
  14089. this.sessions[sid].terminate();
  14090. }
  14091. delete this.jid2session[this.sessions[sid].peerjid];
  14092. delete this.sessions[sid];
  14093. }
  14094. },
  14095. // Used to terminate a session when an unavailable presence is received.
  14096. terminateByJid: function (jid) {
  14097. if (this.jid2session.hasOwnProperty(jid)) {
  14098. var sess = this.jid2session[jid];
  14099. if (sess) {
  14100. sess.terminate();
  14101. console.log('peer went away silently', jid);
  14102. delete this.sessions[sess.sid];
  14103. delete this.jid2session[jid];
  14104. $(document).trigger('callterminated.jingle',
  14105. [sess.sid, jid], 'gone');
  14106. }
  14107. }
  14108. },
  14109. terminateRemoteByJid: function (jid, reason) {
  14110. if (this.jid2session.hasOwnProperty(jid)) {
  14111. var sess = this.jid2session[jid];
  14112. if (sess) {
  14113. sess.sendTerminate(reason || (!sess.active()) ? 'kick' : null);
  14114. sess.terminate();
  14115. console.log('terminate peer with jid', sess.sid, jid);
  14116. delete this.sessions[sess.sid];
  14117. delete this.jid2session[jid];
  14118. $(document).trigger('callterminated.jingle',
  14119. [sess.sid, jid, 'kicked']);
  14120. }
  14121. }
  14122. },
  14123. getStunAndTurnCredentials: function () {
  14124. // get stun and turn configuration from server via xep-0215
  14125. // uses time-limited credentials as described in
  14126. // http://tools.ietf.org/html/draft-uberti-behave-turn-rest-00
  14127. //
  14128. // see https://code.google.com/p/prosody-modules/source/browse/mod_turncredentials/mod_turncredentials.lua
  14129. // for a prosody module which implements this
  14130. //
  14131. // currently, this doesn't work with updateIce and therefore credentials with a long
  14132. // validity have to be fetched before creating the peerconnection
  14133. // TODO: implement refresh via updateIce as described in
  14134. // https://code.google.com/p/webrtc/issues/detail?id=1650
  14135. var self = this;
  14136. this.connection.sendIQ(
  14137. $iq({type: 'get', to: this.connection.domain})
  14138. .c('services', {xmlns: 'urn:xmpp:extdisco:1'}).c('service', {host: 'turn.' + this.connection.domain}),
  14139. function (res) {
  14140. var iceservers = [];
  14141. $(res).find('>services>service').each(function (idx, el) {
  14142. el = $(el);
  14143. var dict = {};
  14144. var type = el.attr('type');
  14145. switch (type) {
  14146. case 'stun':
  14147. dict.url = 'stun:' + el.attr('host');
  14148. if (el.attr('port')) {
  14149. dict.url += ':' + el.attr('port');
  14150. }
  14151. iceservers.push(dict);
  14152. break;
  14153. case 'turn':
  14154. case 'turns':
  14155. dict.url = type + ':';
  14156. if (el.attr('username')) { // https://code.google.com/p/webrtc/issues/detail?id=1508
  14157. if (navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./) && parseInt(navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./)[2], 10) < 28) {
  14158. dict.url += el.attr('username') + '@';
  14159. } else {
  14160. dict.username = el.attr('username'); // only works in M28
  14161. }
  14162. }
  14163. dict.url += el.attr('host');
  14164. if (el.attr('port') && el.attr('port') != '3478') {
  14165. dict.url += ':' + el.attr('port');
  14166. }
  14167. if (el.attr('transport') && el.attr('transport') != 'udp') {
  14168. dict.url += '?transport=' + el.attr('transport');
  14169. }
  14170. if (el.attr('password')) {
  14171. dict.credential = el.attr('password');
  14172. }
  14173. iceservers.push(dict);
  14174. break;
  14175. }
  14176. });
  14177. self.ice_config.iceServers = iceservers;
  14178. },
  14179. function (err) {
  14180. console.warn('getting turn credentials failed', err);
  14181. console.warn('is mod_turncredentials or similar installed?');
  14182. }
  14183. );
  14184. // implement push?
  14185. },
  14186. /**
  14187. * Populates the log data
  14188. */
  14189. populateData: function () {
  14190. var data = {};
  14191. Object.keys(this.sessions).forEach(function (sid) {
  14192. var session = this.sessions[sid];
  14193. if (session.peerconnection && session.peerconnection.updateLog) {
  14194. // FIXME: should probably be a .dump call
  14195. data["jingle_" + session.sid] = {
  14196. updateLog: session.peerconnection.updateLog,
  14197. stats: session.peerconnection.stats,
  14198. url: window.location.href
  14199. };
  14200. }
  14201. });
  14202. return data;
  14203. }
  14204. });
  14205. };
  14206. },{"../../service/xmpp/XMPPEvents":96,"./JingleSession":47}],56:[function(require,module,exports){
  14207. /* global Strophe */
  14208. module.exports = function () {
  14209. Strophe.addConnectionPlugin('logger', {
  14210. // logs raw stanzas and makes them available for download as JSON
  14211. connection: null,
  14212. log: [],
  14213. init: function (conn) {
  14214. this.connection = conn;
  14215. this.connection.rawInput = this.log_incoming.bind(this);
  14216. this.connection.rawOutput = this.log_outgoing.bind(this);
  14217. },
  14218. log_incoming: function (stanza) {
  14219. this.log.push([new Date().getTime(), 'incoming', stanza]);
  14220. },
  14221. log_outgoing: function (stanza) {
  14222. this.log.push([new Date().getTime(), 'outgoing', stanza]);
  14223. }
  14224. });
  14225. };
  14226. },{}],57:[function(require,module,exports){
  14227. /* global $, $iq, config, connection, focusMucJid, forceMuted,
  14228. setAudioMuted, Strophe */
  14229. /**
  14230. * Moderate connection plugin.
  14231. */
  14232. module.exports = function (XMPP) {
  14233. Strophe.addConnectionPlugin('moderate', {
  14234. connection: null,
  14235. init: function (conn) {
  14236. this.connection = conn;
  14237. this.connection.addHandler(this.onMute.bind(this),
  14238. 'http://jitsi.org/jitmeet/audio',
  14239. 'iq',
  14240. 'set',
  14241. null,
  14242. null);
  14243. },
  14244. setMute: function (jid, mute) {
  14245. console.info("set mute", mute);
  14246. var iqToFocus = $iq({to: this.connection.emuc.focusMucJid, type: 'set'})
  14247. .c('mute', {
  14248. xmlns: 'http://jitsi.org/jitmeet/audio',
  14249. jid: jid
  14250. })
  14251. .t(mute.toString())
  14252. .up();
  14253. this.connection.sendIQ(
  14254. iqToFocus,
  14255. function (result) {
  14256. console.log('set mute', result);
  14257. },
  14258. function (error) {
  14259. console.log('set mute error', error);
  14260. });
  14261. },
  14262. onMute: function (iq) {
  14263. var from = iq.getAttribute('from');
  14264. if (from !== this.connection.emuc.focusMucJid) {
  14265. console.warn("Ignored mute from non focus peer");
  14266. return false;
  14267. }
  14268. var mute = $(iq).find('mute');
  14269. if (mute.length) {
  14270. var doMuteAudio = mute.text() === "true";
  14271. APP.UI.setAudioMuted(doMuteAudio);
  14272. XMPP.forceMuted = doMuteAudio;
  14273. }
  14274. return true;
  14275. },
  14276. eject: function (jid) {
  14277. // We're not the focus, so can't terminate
  14278. //connection.jingle.terminateRemoteByJid(jid, 'kick');
  14279. this.connection.emuc.kick(jid);
  14280. }
  14281. });
  14282. }
  14283. },{}],58:[function(require,module,exports){
  14284. /* jshint -W117 */
  14285. module.exports = function() {
  14286. Strophe.addConnectionPlugin('rayo',
  14287. {
  14288. RAYO_XMLNS: 'urn:xmpp:rayo:1',
  14289. connection: null,
  14290. init: function (conn) {
  14291. this.connection = conn;
  14292. if (this.connection.disco) {
  14293. this.connection.disco.addFeature('urn:xmpp:rayo:client:1');
  14294. }
  14295. this.connection.addHandler(
  14296. this.onRayo.bind(this), this.RAYO_XMLNS, 'iq', 'set', null, null);
  14297. },
  14298. onRayo: function (iq) {
  14299. console.info("Rayo IQ", iq);
  14300. },
  14301. dial: function (to, from, roomName, roomPass) {
  14302. var self = this;
  14303. var req = $iq(
  14304. {
  14305. type: 'set',
  14306. to: this.connection.emuc.focusMucJid
  14307. }
  14308. );
  14309. req.c('dial',
  14310. {
  14311. xmlns: this.RAYO_XMLNS,
  14312. to: to,
  14313. from: from
  14314. });
  14315. req.c('header',
  14316. {
  14317. name: 'JvbRoomName',
  14318. value: roomName
  14319. }).up();
  14320. if (roomPass !== null && roomPass.length) {
  14321. req.c('header',
  14322. {
  14323. name: 'JvbRoomPassword',
  14324. value: roomPass
  14325. }).up();
  14326. }
  14327. this.connection.sendIQ(
  14328. req,
  14329. function (result) {
  14330. console.info('Dial result ', result);
  14331. var resource = $(result).find('ref').attr('uri');
  14332. this.call_resource = resource.substr('xmpp:'.length);
  14333. console.info(
  14334. "Received call resource: " + this.call_resource);
  14335. },
  14336. function (error) {
  14337. console.info('Dial error ', error);
  14338. }
  14339. );
  14340. },
  14341. hang_up: function () {
  14342. if (!this.call_resource) {
  14343. console.warn("No call in progress");
  14344. return;
  14345. }
  14346. var self = this;
  14347. var req = $iq(
  14348. {
  14349. type: 'set',
  14350. to: this.call_resource
  14351. }
  14352. );
  14353. req.c('hangup',
  14354. {
  14355. xmlns: this.RAYO_XMLNS
  14356. });
  14357. this.connection.sendIQ(
  14358. req,
  14359. function (result) {
  14360. console.info('Hangup result ', result);
  14361. self.call_resource = null;
  14362. },
  14363. function (error) {
  14364. console.info('Hangup error ', error);
  14365. self.call_resource = null;
  14366. }
  14367. );
  14368. }
  14369. }
  14370. );
  14371. };
  14372. },{}],59:[function(require,module,exports){
  14373. /**
  14374. * Strophe logger implementation. Logs from level WARN and above.
  14375. */
  14376. module.exports = function () {
  14377. Strophe.log = function (level, msg) {
  14378. switch (level) {
  14379. case Strophe.LogLevel.WARN:
  14380. console.warn("Strophe: " + msg);
  14381. break;
  14382. case Strophe.LogLevel.ERROR:
  14383. case Strophe.LogLevel.FATAL:
  14384. console.error("Strophe: " + msg);
  14385. break;
  14386. }
  14387. };
  14388. Strophe.getStatusString = function (status) {
  14389. switch (status) {
  14390. case Strophe.Status.ERROR:
  14391. return "ERROR";
  14392. case Strophe.Status.CONNECTING:
  14393. return "CONNECTING";
  14394. case Strophe.Status.CONNFAIL:
  14395. return "CONNFAIL";
  14396. case Strophe.Status.AUTHENTICATING:
  14397. return "AUTHENTICATING";
  14398. case Strophe.Status.AUTHFAIL:
  14399. return "AUTHFAIL";
  14400. case Strophe.Status.CONNECTED:
  14401. return "CONNECTED";
  14402. case Strophe.Status.DISCONNECTED:
  14403. return "DISCONNECTED";
  14404. case Strophe.Status.DISCONNECTING:
  14405. return "DISCONNECTING";
  14406. case Strophe.Status.ATTACHED:
  14407. return "ATTACHED";
  14408. default:
  14409. return "unknown";
  14410. }
  14411. };
  14412. };
  14413. },{}],60:[function(require,module,exports){
  14414. var Moderator = require("./moderator");
  14415. var EventEmitter = require("events");
  14416. var Recording = require("./recording");
  14417. var SDP = require("./SDP");
  14418. var Pako = require("pako");
  14419. var StreamEventTypes = require("../../service/RTC/StreamEventTypes");
  14420. var UIEvents = require("../../service/UI/UIEvents");
  14421. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  14422. var eventEmitter = new EventEmitter();
  14423. var connection = null;
  14424. var authenticatedUser = false;
  14425. function connect(jid, password, uiCredentials) {
  14426. var bosh
  14427. = (uiCredentials && uiCredentials.bosh? uiCredentials.bosh : null)
  14428. || config.bosh || '/http-bind';
  14429. connection = new Strophe.Connection(bosh);
  14430. Moderator.setConnection(connection);
  14431. if(uiCredentials) {
  14432. var email = uiCredentials.email;
  14433. var displayName = uiCredentials.displayName;
  14434. if (email) {
  14435. connection.emuc.addEmailToPresence(email);
  14436. } else {
  14437. connection.emuc.addUserIdToPresence(uiCredentials.uid);
  14438. }
  14439. if (displayName) {
  14440. connection.emuc.addDisplayNameToPresence(displayName);
  14441. }
  14442. }
  14443. if (connection.disco) {
  14444. // for chrome, add multistream cap
  14445. }
  14446. connection.jingle.pc_constraints = APP.RTC.getPCConstraints();
  14447. if (config.useIPv6) {
  14448. // https://code.google.com/p/webrtc/issues/detail?id=2828
  14449. if (!connection.jingle.pc_constraints.optional)
  14450. connection.jingle.pc_constraints.optional = [];
  14451. connection.jingle.pc_constraints.optional.push({googIPv6: true});
  14452. }
  14453. if(!password)
  14454. password = uiCredentials.password;
  14455. var anonymousConnectionFailed = false;
  14456. connection.connect(jid, password, function (status, msg) {
  14457. console.log('Strophe status changed to',
  14458. Strophe.getStatusString(status));
  14459. if (status === Strophe.Status.CONNECTED) {
  14460. if (config.useStunTurn) {
  14461. connection.jingle.getStunAndTurnCredentials();
  14462. }
  14463. APP.UI.disableConnect();
  14464. console.info("My Jabber ID: " + connection.jid);
  14465. if(password)
  14466. authenticatedUser = true;
  14467. maybeDoJoin();
  14468. } else if (status === Strophe.Status.CONNFAIL) {
  14469. if(msg === 'x-strophe-bad-non-anon-jid') {
  14470. anonymousConnectionFailed = true;
  14471. }
  14472. } else if (status === Strophe.Status.DISCONNECTED) {
  14473. if(anonymousConnectionFailed) {
  14474. // prompt user for username and password
  14475. XMPP.promptLogin();
  14476. }
  14477. } else if (status === Strophe.Status.AUTHFAIL) {
  14478. // wrong password or username, prompt user
  14479. XMPP.promptLogin();
  14480. }
  14481. });
  14482. }
  14483. function maybeDoJoin() {
  14484. if (connection && connection.connected &&
  14485. Strophe.getResourceFromJid(connection.jid)
  14486. && (APP.RTC.localAudio || APP.RTC.localVideo)) {
  14487. // .connected is true while connecting?
  14488. doJoin();
  14489. }
  14490. }
  14491. function doJoin() {
  14492. var roomName = APP.UI.generateRoomName();
  14493. Moderator.allocateConferenceFocus(
  14494. roomName, APP.UI.checkForNicknameAndJoin);
  14495. }
  14496. function initStrophePlugins()
  14497. {
  14498. require("./strophe.emuc")(XMPP, eventEmitter);
  14499. require("./strophe.jingle")(XMPP, eventEmitter);
  14500. require("./strophe.moderate")(XMPP);
  14501. require("./strophe.util")();
  14502. require("./strophe.rayo")();
  14503. require("./strophe.logger")();
  14504. }
  14505. function registerListeners() {
  14506. APP.RTC.addStreamListener(maybeDoJoin,
  14507. StreamEventTypes.EVENT_TYPE_LOCAL_CREATED);
  14508. APP.UI.addListener(UIEvents.NICKNAME_CHANGED, function (nickname) {
  14509. XMPP.addToPresence("displayName", nickname);
  14510. });
  14511. }
  14512. function setupEvents() {
  14513. $(window).bind('beforeunload', function () {
  14514. if (connection && connection.connected) {
  14515. // ensure signout
  14516. $.ajax({
  14517. type: 'POST',
  14518. url: config.bosh,
  14519. async: false,
  14520. cache: false,
  14521. contentType: 'application/xml',
  14522. data: "<body rid='" + (connection.rid || connection._proto.rid)
  14523. + "' xmlns='http://jabber.org/protocol/httpbind' sid='"
  14524. + (connection.sid || connection._proto.sid)
  14525. + "' type='terminate'>" +
  14526. "<presence xmlns='jabber:client' type='unavailable'/>" +
  14527. "</body>",
  14528. success: function (data) {
  14529. console.log('signed out');
  14530. console.log(data);
  14531. },
  14532. error: function (XMLHttpRequest, textStatus, errorThrown) {
  14533. console.log('signout error',
  14534. textStatus + ' (' + errorThrown + ')');
  14535. }
  14536. });
  14537. }
  14538. XMPP.disposeConference(true);
  14539. });
  14540. }
  14541. var XMPP = {
  14542. sessionTerminated: false,
  14543. /**
  14544. * Remembers if we were muted by the focus.
  14545. * @type {boolean}
  14546. */
  14547. forceMuted: false,
  14548. start: function (uiCredentials) {
  14549. setupEvents();
  14550. initStrophePlugins();
  14551. registerListeners();
  14552. Moderator.init(this, eventEmitter);
  14553. var configDomain = config.hosts.anonymousdomain || config.hosts.domain;
  14554. // Force authenticated domain if room is appended with '?login=true'
  14555. if (config.hosts.anonymousdomain &&
  14556. window.location.search.indexOf("login=true") !== -1) {
  14557. configDomain = config.hosts.domain;
  14558. }
  14559. var jid = uiCredentials.jid || configDomain || window.location.hostname;
  14560. connect(jid, null, uiCredentials);
  14561. },
  14562. promptLogin: function () {
  14563. APP.UI.showLoginPopup(connect);
  14564. },
  14565. joinRoom: function(roomName, useNicks, nick)
  14566. {
  14567. var roomjid;
  14568. roomjid = roomName;
  14569. if (useNicks) {
  14570. if (nick) {
  14571. roomjid += '/' + nick;
  14572. } else {
  14573. roomjid += '/' + Strophe.getNodeFromJid(connection.jid);
  14574. }
  14575. } else {
  14576. var tmpJid = Strophe.getNodeFromJid(connection.jid);
  14577. if(!authenticatedUser)
  14578. tmpJid = tmpJid.substr(0, 8);
  14579. roomjid += '/' + tmpJid;
  14580. }
  14581. connection.emuc.doJoin(roomjid);
  14582. },
  14583. myJid: function () {
  14584. if(!connection)
  14585. return null;
  14586. return connection.emuc.myroomjid;
  14587. },
  14588. myResource: function () {
  14589. if(!connection || ! connection.emuc.myroomjid)
  14590. return null;
  14591. return Strophe.getResourceFromJid(connection.emuc.myroomjid);
  14592. },
  14593. disposeConference: function (onUnload) {
  14594. eventEmitter.emit(XMPPEvents.DISPOSE_CONFERENCE, onUnload);
  14595. var handler = connection.jingle.activecall;
  14596. if (handler && handler.peerconnection) {
  14597. // FIXME: probably removing streams is not required and close() should
  14598. // be enough
  14599. if (APP.RTC.localAudio) {
  14600. handler.peerconnection.removeStream(APP.RTC.localAudio.getOriginalStream(), onUnload);
  14601. }
  14602. if (APP.RTC.localVideo) {
  14603. handler.peerconnection.removeStream(APP.RTC.localVideo.getOriginalStream(), onUnload);
  14604. }
  14605. handler.peerconnection.close();
  14606. }
  14607. connection.jingle.activecall = null;
  14608. if(!onUnload)
  14609. {
  14610. this.sessionTerminated = true;
  14611. connection.emuc.doLeave();
  14612. }
  14613. },
  14614. addListener: function(type, listener)
  14615. {
  14616. eventEmitter.on(type, listener);
  14617. },
  14618. removeListener: function (type, listener) {
  14619. eventEmitter.removeListener(type, listener);
  14620. },
  14621. allocateConferenceFocus: function(roomName, callback) {
  14622. Moderator.allocateConferenceFocus(roomName, callback);
  14623. },
  14624. getLoginUrl: function (roomName, callback) {
  14625. Moderator.getLoginUrl(roomName, callback);
  14626. },
  14627. getPopupLoginUrl: function (roomName, callback) {
  14628. Moderator.getPopupLoginUrl(roomName, callback);
  14629. },
  14630. isModerator: function () {
  14631. return Moderator.isModerator();
  14632. },
  14633. isSipGatewayEnabled: function () {
  14634. return Moderator.isSipGatewayEnabled();
  14635. },
  14636. isExternalAuthEnabled: function () {
  14637. return Moderator.isExternalAuthEnabled();
  14638. },
  14639. switchStreams: function (stream, oldStream, callback) {
  14640. if (connection && connection.jingle.activecall) {
  14641. // FIXME: will block switchInProgress on true value in case of exception
  14642. connection.jingle.activecall.switchStreams(stream, oldStream, callback);
  14643. } else {
  14644. // We are done immediately
  14645. console.warn("No conference handler or conference not started yet");
  14646. callback();
  14647. }
  14648. },
  14649. setVideoMute: function (mute, callback, options) {
  14650. if(connection && APP.RTC.localVideo && connection.jingle.activecall)
  14651. {
  14652. connection.jingle.activecall.setVideoMute(mute, callback, options);
  14653. }
  14654. },
  14655. setAudioMute: function (mute, callback) {
  14656. if (!(connection && APP.RTC.localAudio)) {
  14657. return false;
  14658. }
  14659. if (this.forceMuted && !mute) {
  14660. console.info("Asking focus for unmute");
  14661. connection.moderate.setMute(connection.emuc.myroomjid, mute);
  14662. // FIXME: wait for result before resetting muted status
  14663. this.forceMuted = false;
  14664. }
  14665. if (mute == APP.RTC.localAudio.isMuted()) {
  14666. // Nothing to do
  14667. return true;
  14668. }
  14669. // It is not clear what is the right way to handle multiple tracks.
  14670. // So at least make sure that they are all muted or all unmuted and
  14671. // that we send presence just once.
  14672. APP.RTC.localAudio.mute();
  14673. // isMuted is the opposite of audioEnabled
  14674. connection.emuc.addAudioInfoToPresence(mute);
  14675. connection.emuc.sendPresence();
  14676. callback();
  14677. return true;
  14678. },
  14679. // Really mute video, i.e. dont even send black frames
  14680. muteVideo: function (pc, unmute) {
  14681. // FIXME: this probably needs another of those lovely state safeguards...
  14682. // which checks for iceconn == connected and sigstate == stable
  14683. pc.setRemoteDescription(pc.remoteDescription,
  14684. function () {
  14685. pc.createAnswer(
  14686. function (answer) {
  14687. var sdp = new SDP(answer.sdp);
  14688. if (sdp.media.length > 1) {
  14689. if (unmute)
  14690. sdp.media[1] = sdp.media[1].replace('a=recvonly', 'a=sendrecv');
  14691. else
  14692. sdp.media[1] = sdp.media[1].replace('a=sendrecv', 'a=recvonly');
  14693. sdp.raw = sdp.session + sdp.media.join('');
  14694. answer.sdp = sdp.raw;
  14695. }
  14696. pc.setLocalDescription(answer,
  14697. function () {
  14698. console.log('mute SLD ok');
  14699. },
  14700. function (error) {
  14701. console.log('mute SLD error');
  14702. APP.UI.messageHandler.showError("dialog.error",
  14703. "dialog.SLDFailure");
  14704. }
  14705. );
  14706. },
  14707. function (error) {
  14708. console.log(error);
  14709. APP.UI.messageHandler.showError();
  14710. }
  14711. );
  14712. },
  14713. function (error) {
  14714. console.log('muteVideo SRD error');
  14715. APP.UI.messageHandler.showError("dialog.error",
  14716. "dialog.SRDFailure");
  14717. }
  14718. );
  14719. },
  14720. toggleRecording: function (tokenEmptyCallback,
  14721. startingCallback, startedCallback) {
  14722. Recording.toggleRecording(tokenEmptyCallback,
  14723. startingCallback, startedCallback, connection);
  14724. },
  14725. addToPresence: function (name, value, dontSend) {
  14726. switch (name)
  14727. {
  14728. case "displayName":
  14729. connection.emuc.addDisplayNameToPresence(value);
  14730. break;
  14731. case "etherpad":
  14732. connection.emuc.addEtherpadToPresence(value);
  14733. break;
  14734. case "prezi":
  14735. connection.emuc.addPreziToPresence(value, 0);
  14736. break;
  14737. case "preziSlide":
  14738. connection.emuc.addCurrentSlideToPresence(value);
  14739. break;
  14740. case "connectionQuality":
  14741. connection.emuc.addConnectionInfoToPresence(value);
  14742. break;
  14743. case "email":
  14744. connection.emuc.addEmailToPresence(value);
  14745. default :
  14746. console.log("Unknown tag for presence.");
  14747. return;
  14748. }
  14749. if(!dontSend)
  14750. connection.emuc.sendPresence();
  14751. },
  14752. /**
  14753. * Sends 'data' as a log message to the focus. Returns true iff a message
  14754. * was sent.
  14755. * @param data
  14756. * @returns {boolean} true iff a message was sent.
  14757. */
  14758. sendLogs: function (data) {
  14759. if(!connection.emuc.focusMucJid)
  14760. return false;
  14761. var deflate = true;
  14762. var content = JSON.stringify(data);
  14763. if (deflate) {
  14764. content = String.fromCharCode.apply(null, Pako.deflateRaw(content));
  14765. }
  14766. content = Base64.encode(content);
  14767. // XEP-0337-ish
  14768. var message = $msg({to: connection.emuc.focusMucJid, type: 'normal'});
  14769. message.c('log', { xmlns: 'urn:xmpp:eventlog',
  14770. id: 'PeerConnectionStats'});
  14771. message.c('message').t(content).up();
  14772. if (deflate) {
  14773. message.c('tag', {name: "deflated", value: "true"}).up();
  14774. }
  14775. message.up();
  14776. connection.send(message);
  14777. return true;
  14778. },
  14779. populateData: function () {
  14780. var data = {};
  14781. if (connection.jingle) {
  14782. data = connection.jingle.populateData();
  14783. }
  14784. return data;
  14785. },
  14786. getLogger: function () {
  14787. if(connection.logger)
  14788. return connection.logger.log;
  14789. return null;
  14790. },
  14791. getPrezi: function () {
  14792. return connection.emuc.getPrezi(this.myJid());
  14793. },
  14794. removePreziFromPresence: function () {
  14795. connection.emuc.removePreziFromPresence();
  14796. connection.emuc.sendPresence();
  14797. },
  14798. sendChatMessage: function (message, nickname) {
  14799. connection.emuc.sendMessage(message, nickname);
  14800. },
  14801. setSubject: function (topic) {
  14802. connection.emuc.setSubject(topic);
  14803. },
  14804. lockRoom: function (key, onSuccess, onError, onNotSupported) {
  14805. connection.emuc.lockRoom(key, onSuccess, onError, onNotSupported);
  14806. },
  14807. dial: function (to, from, roomName,roomPass) {
  14808. connection.rayo.dial(to, from, roomName,roomPass);
  14809. },
  14810. setMute: function (jid, mute) {
  14811. connection.moderate.setMute(jid, mute);
  14812. },
  14813. eject: function (jid) {
  14814. connection.moderate.eject(jid);
  14815. },
  14816. logout: function (callback) {
  14817. Moderator.logout(callback);
  14818. },
  14819. findJidFromResource: function (resource) {
  14820. return connection.emuc.findJidFromResource(resource);
  14821. },
  14822. getMembers: function () {
  14823. return connection.emuc.members;
  14824. },
  14825. getJidFromSSRC: function (ssrc) {
  14826. if(!connection)
  14827. return null;
  14828. return connection.emuc.ssrc2jid[ssrc];
  14829. },
  14830. getMUCJoined: function () {
  14831. return connection.emuc.joined;
  14832. },
  14833. getSessions: function () {
  14834. return connection.jingle.sessions;
  14835. }
  14836. };
  14837. module.exports = XMPP;
  14838. },{"../../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){
  14839. // i18next, v1.7.7
  14840. // Copyright (c)2014 Jan Mühlemann (jamuhl).
  14841. // Distributed under MIT license
  14842. // http://i18next.com
  14843. (function() {
  14844. // add indexOf to non ECMA-262 standard compliant browsers
  14845. if (!Array.prototype.indexOf) {
  14846. Array.prototype.indexOf = function (searchElement /*, fromIndex */ ) {
  14847. "use strict";
  14848. if (this == null) {
  14849. throw new TypeError();
  14850. }
  14851. var t = Object(this);
  14852. var len = t.length >>> 0;
  14853. if (len === 0) {
  14854. return -1;
  14855. }
  14856. var n = 0;
  14857. if (arguments.length > 0) {
  14858. n = Number(arguments[1]);
  14859. if (n != n) { // shortcut for verifying if it's NaN
  14860. n = 0;
  14861. } else if (n != 0 && n != Infinity && n != -Infinity) {
  14862. n = (n > 0 || -1) * Math.floor(Math.abs(n));
  14863. }
  14864. }
  14865. if (n >= len) {
  14866. return -1;
  14867. }
  14868. var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);
  14869. for (; k < len; k++) {
  14870. if (k in t && t[k] === searchElement) {
  14871. return k;
  14872. }
  14873. }
  14874. return -1;
  14875. }
  14876. }
  14877. // add lastIndexOf to non ECMA-262 standard compliant browsers
  14878. if (!Array.prototype.lastIndexOf) {
  14879. Array.prototype.lastIndexOf = function(searchElement /*, fromIndex*/) {
  14880. "use strict";
  14881. if (this == null) {
  14882. throw new TypeError();
  14883. }
  14884. var t = Object(this);
  14885. var len = t.length >>> 0;
  14886. if (len === 0) {
  14887. return -1;
  14888. }
  14889. var n = len;
  14890. if (arguments.length > 1) {
  14891. n = Number(arguments[1]);
  14892. if (n != n) {
  14893. n = 0;
  14894. } else if (n != 0 && n != (1 / 0) && n != -(1 / 0)) {
  14895. n = (n > 0 || -1) * Math.floor(Math.abs(n));
  14896. }
  14897. }
  14898. var k = n >= 0 ? Math.min(n, len - 1) : len - Math.abs(n);
  14899. for (; k >= 0; k--) {
  14900. if (k in t && t[k] === searchElement) {
  14901. return k;
  14902. }
  14903. }
  14904. return -1;
  14905. };
  14906. }
  14907. // Add string trim for IE8.
  14908. if (typeof String.prototype.trim !== 'function') {
  14909. String.prototype.trim = function() {
  14910. return this.replace(/^\s+|\s+$/g, '');
  14911. }
  14912. }
  14913. var root = this
  14914. , $ = root.jQuery || root.Zepto
  14915. , i18n = {}
  14916. , resStore = {}
  14917. , currentLng
  14918. , replacementCounter = 0
  14919. , languages = []
  14920. , initialized = false
  14921. , sync = {};
  14922. // Export the i18next object for **CommonJS**.
  14923. // If we're not in CommonJS, add `i18n` to the
  14924. // global object or to jquery.
  14925. if (typeof module !== 'undefined' && module.exports) {
  14926. if (!$) {
  14927. try {
  14928. $ = require('jquery');
  14929. } catch(e) {
  14930. // just ignore
  14931. }
  14932. }
  14933. if ($) {
  14934. $.i18n = $.i18n || i18n;
  14935. }
  14936. module.exports = i18n;
  14937. } else {
  14938. if ($) {
  14939. $.i18n = $.i18n || i18n;
  14940. }
  14941. root.i18n = root.i18n || i18n;
  14942. }
  14943. sync = {
  14944. load: function(lngs, options, cb) {
  14945. if (options.useLocalStorage) {
  14946. sync._loadLocal(lngs, options, function(err, store) {
  14947. var missingLngs = [];
  14948. for (var i = 0, len = lngs.length; i < len; i++) {
  14949. if (!store[lngs[i]]) missingLngs.push(lngs[i]);
  14950. }
  14951. if (missingLngs.length > 0) {
  14952. sync._fetch(missingLngs, options, function(err, fetched) {
  14953. f.extend(store, fetched);
  14954. sync._storeLocal(fetched);
  14955. cb(null, store);
  14956. });
  14957. } else {
  14958. cb(null, store);
  14959. }
  14960. });
  14961. } else {
  14962. sync._fetch(lngs, options, function(err, store){
  14963. cb(null, store);
  14964. });
  14965. }
  14966. },
  14967. _loadLocal: function(lngs, options, cb) {
  14968. var store = {}
  14969. , nowMS = new Date().getTime();
  14970. if(window.localStorage) {
  14971. var todo = lngs.length;
  14972. f.each(lngs, function(key, lng) {
  14973. var local = window.localStorage.getItem('res_' + lng);
  14974. if (local) {
  14975. local = JSON.parse(local);
  14976. if (local.i18nStamp && local.i18nStamp + options.localStorageExpirationTime > nowMS) {
  14977. store[lng] = local;
  14978. }
  14979. }
  14980. todo--; // wait for all done befor callback
  14981. if (todo === 0) cb(null, store);
  14982. });
  14983. }
  14984. },
  14985. _storeLocal: function(store) {
  14986. if(window.localStorage) {
  14987. for (var m in store) {
  14988. store[m].i18nStamp = new Date().getTime();
  14989. f.localStorage.setItem('res_' + m, JSON.stringify(store[m]));
  14990. }
  14991. }
  14992. return;
  14993. },
  14994. _fetch: function(lngs, options, cb) {
  14995. var ns = options.ns
  14996. , store = {};
  14997. if (!options.dynamicLoad) {
  14998. var todo = ns.namespaces.length * lngs.length
  14999. , errors;
  15000. // load each file individual
  15001. f.each(ns.namespaces, function(nsIndex, nsValue) {
  15002. f.each(lngs, function(lngIndex, lngValue) {
  15003. // Call this once our translation has returned.
  15004. var loadComplete = function(err, data) {
  15005. if (err) {
  15006. errors = errors || [];
  15007. errors.push(err);
  15008. }
  15009. store[lngValue] = store[lngValue] || {};
  15010. store[lngValue][nsValue] = data;
  15011. todo--; // wait for all done befor callback
  15012. if (todo === 0) cb(errors, store);
  15013. };
  15014. if(typeof options.customLoad == 'function'){
  15015. // Use the specified custom callback.
  15016. options.customLoad(lngValue, nsValue, options, loadComplete);
  15017. } else {
  15018. //~ // Use our inbuilt sync.
  15019. sync._fetchOne(lngValue, nsValue, options, loadComplete);
  15020. }
  15021. });
  15022. });
  15023. } else {
  15024. // Call this once our translation has returned.
  15025. var loadComplete = function(err, data) {
  15026. cb(null, data);
  15027. };
  15028. if(typeof options.customLoad == 'function'){
  15029. // Use the specified custom callback.
  15030. options.customLoad(lngs, ns.namespaces, options, loadComplete);
  15031. } else {
  15032. var url = applyReplacement(options.resGetPath, { lng: lngs.join('+'), ns: ns.namespaces.join('+') });
  15033. // load all needed stuff once
  15034. f.ajax({
  15035. url: url,
  15036. success: function(data, status, xhr) {
  15037. f.log('loaded: ' + url);
  15038. loadComplete(null, data);
  15039. },
  15040. error : function(xhr, status, error) {
  15041. f.log('failed loading: ' + url);
  15042. loadComplete('failed loading resource.json error: ' + error);
  15043. },
  15044. dataType: "json",
  15045. async : options.getAsync
  15046. });
  15047. }
  15048. }
  15049. },
  15050. _fetchOne: function(lng, ns, options, done) {
  15051. var url = applyReplacement(options.resGetPath, { lng: lng, ns: ns });
  15052. f.ajax({
  15053. url: url,
  15054. success: function(data, status, xhr) {
  15055. f.log('loaded: ' + url);
  15056. done(null, data);
  15057. },
  15058. error : function(xhr, status, error) {
  15059. if ((status && status == 200) || (xhr && xhr.status && xhr.status == 200)) {
  15060. // file loaded but invalid json, stop waste time !
  15061. f.error('There is a typo in: ' + url);
  15062. } else if ((status && status == 404) || (xhr && xhr.status && xhr.status == 404)) {
  15063. f.log('Does not exist: ' + url);
  15064. } else {
  15065. var theStatus = status ? status : ((xhr && xhr.status) ? xhr.status : null);
  15066. f.log(theStatus + ' when loading ' + url);
  15067. }
  15068. done(error, {});
  15069. },
  15070. dataType: "json",
  15071. async : options.getAsync
  15072. });
  15073. },
  15074. postMissing: function(lng, ns, key, defaultValue, lngs) {
  15075. var payload = {};
  15076. payload[key] = defaultValue;
  15077. var urls = [];
  15078. if (o.sendMissingTo === 'fallback' && o.fallbackLng[0] !== false) {
  15079. for (var i = 0; i < o.fallbackLng.length; i++) {
  15080. urls.push({lng: o.fallbackLng[i], url: applyReplacement(o.resPostPath, { lng: o.fallbackLng[i], ns: ns })});
  15081. }
  15082. } else if (o.sendMissingTo === 'current' || (o.sendMissingTo === 'fallback' && o.fallbackLng[0] === false) ) {
  15083. urls.push({lng: lng, url: applyReplacement(o.resPostPath, { lng: lng, ns: ns })});
  15084. } else if (o.sendMissingTo === 'all') {
  15085. for (var i = 0, l = lngs.length; i < l; i++) {
  15086. urls.push({lng: lngs[i], url: applyReplacement(o.resPostPath, { lng: lngs[i], ns: ns })});
  15087. }
  15088. }
  15089. for (var y = 0, len = urls.length; y < len; y++) {
  15090. var item = urls[y];
  15091. f.ajax({
  15092. url: item.url,
  15093. type: o.sendType,
  15094. data: payload,
  15095. success: function(data, status, xhr) {
  15096. f.log('posted missing key \'' + key + '\' to: ' + item.url);
  15097. // add key to resStore
  15098. var keys = key.split('.');
  15099. var x = 0;
  15100. var value = resStore[item.lng][ns];
  15101. while (keys[x]) {
  15102. if (x === keys.length - 1) {
  15103. value = value[keys[x]] = defaultValue;
  15104. } else {
  15105. value = value[keys[x]] = value[keys[x]] || {};
  15106. }
  15107. x++;
  15108. }
  15109. },
  15110. error : function(xhr, status, error) {
  15111. f.log('failed posting missing key \'' + key + '\' to: ' + item.url);
  15112. },
  15113. dataType: "json",
  15114. async : o.postAsync
  15115. });
  15116. }
  15117. },
  15118. reload: reload
  15119. };
  15120. // defaults
  15121. var o = {
  15122. lng: undefined,
  15123. load: 'all',
  15124. preload: [],
  15125. lowerCaseLng: false,
  15126. returnObjectTrees: false,
  15127. fallbackLng: ['dev'],
  15128. fallbackNS: [],
  15129. detectLngQS: 'setLng',
  15130. detectLngFromLocalStorage: false,
  15131. ns: 'translation',
  15132. fallbackOnNull: true,
  15133. fallbackOnEmpty: false,
  15134. fallbackToDefaultNS: false,
  15135. nsseparator: ':',
  15136. keyseparator: '.',
  15137. selectorAttr: 'data-i18n',
  15138. debug: false,
  15139. resGetPath: 'locales/__lng__/__ns__.json',
  15140. resPostPath: 'locales/add/__lng__/__ns__',
  15141. getAsync: true,
  15142. postAsync: true,
  15143. resStore: undefined,
  15144. useLocalStorage: false,
  15145. localStorageExpirationTime: 7*24*60*60*1000,
  15146. dynamicLoad: false,
  15147. sendMissing: false,
  15148. sendMissingTo: 'fallback', // current | all
  15149. sendType: 'POST',
  15150. interpolationPrefix: '__',
  15151. interpolationSuffix: '__',
  15152. defaultVariables: false,
  15153. reusePrefix: '$t(',
  15154. reuseSuffix: ')',
  15155. pluralSuffix: '_plural',
  15156. pluralNotFound: ['plural_not_found', Math.random()].join(''),
  15157. contextNotFound: ['context_not_found', Math.random()].join(''),
  15158. escapeInterpolation: false,
  15159. indefiniteSuffix: '_indefinite',
  15160. indefiniteNotFound: ['indefinite_not_found', Math.random()].join(''),
  15161. setJqueryExt: true,
  15162. defaultValueFromContent: true,
  15163. useDataAttrOptions: false,
  15164. cookieExpirationTime: undefined,
  15165. useCookie: true,
  15166. cookieName: 'i18next',
  15167. cookieDomain: undefined,
  15168. objectTreeKeyHandler: undefined,
  15169. postProcess: undefined,
  15170. parseMissingKey: undefined,
  15171. missingKeyHandler: sync.postMissing,
  15172. shortcutFunction: 'sprintf' // or: defaultValue
  15173. };
  15174. function _extend(target, source) {
  15175. if (!source || typeof source === 'function') {
  15176. return target;
  15177. }
  15178. for (var attr in source) { target[attr] = source[attr]; }
  15179. return target;
  15180. }
  15181. function _deepExtend(target, source) {
  15182. for (var prop in source)
  15183. if (prop in target)
  15184. _deepExtend(target[prop], source[prop]);
  15185. else
  15186. target[prop] = source[prop];
  15187. return target;
  15188. }
  15189. function _each(object, callback, args) {
  15190. var name, i = 0,
  15191. length = object.length,
  15192. isObj = length === undefined || Object.prototype.toString.apply(object) !== '[object Array]' || typeof object === "function";
  15193. if (args) {
  15194. if (isObj) {
  15195. for (name in object) {
  15196. if (callback.apply(object[name], args) === false) {
  15197. break;
  15198. }
  15199. }
  15200. } else {
  15201. for ( ; i < length; ) {
  15202. if (callback.apply(object[i++], args) === false) {
  15203. break;
  15204. }
  15205. }
  15206. }
  15207. // A special, fast, case for the most common use of each
  15208. } else {
  15209. if (isObj) {
  15210. for (name in object) {
  15211. if (callback.call(object[name], name, object[name]) === false) {
  15212. break;
  15213. }
  15214. }
  15215. } else {
  15216. for ( ; i < length; ) {
  15217. if (callback.call(object[i], i, object[i++]) === false) {
  15218. break;
  15219. }
  15220. }
  15221. }
  15222. }
  15223. return object;
  15224. }
  15225. var _entityMap = {
  15226. "&": "&amp;",
  15227. "<": "&lt;",
  15228. ">": "&gt;",
  15229. '"': '&quot;',
  15230. "'": '&#39;',
  15231. "/": '&#x2F;'
  15232. };
  15233. function _escape(data) {
  15234. if (typeof data === 'string') {
  15235. return data.replace(/[&<>"'\/]/g, function (s) {
  15236. return _entityMap[s];
  15237. });
  15238. }else{
  15239. return data;
  15240. }
  15241. }
  15242. function _ajax(options) {
  15243. // v0.5.0 of https://github.com/goloroden/http.js
  15244. var getXhr = function (callback) {
  15245. // Use the native XHR object if the browser supports it.
  15246. if (window.XMLHttpRequest) {
  15247. return callback(null, new XMLHttpRequest());
  15248. } else if (window.ActiveXObject) {
  15249. // In Internet Explorer check for ActiveX versions of the XHR object.
  15250. try {
  15251. return callback(null, new ActiveXObject("Msxml2.XMLHTTP"));
  15252. } catch (e) {
  15253. return callback(null, new ActiveXObject("Microsoft.XMLHTTP"));
  15254. }
  15255. }
  15256. // If no XHR support was found, throw an error.
  15257. return callback(new Error());
  15258. };
  15259. var encodeUsingUrlEncoding = function (data) {
  15260. if(typeof data === 'string') {
  15261. return data;
  15262. }
  15263. var result = [];
  15264. for(var dataItem in data) {
  15265. if(data.hasOwnProperty(dataItem)) {
  15266. result.push(encodeURIComponent(dataItem) + '=' + encodeURIComponent(data[dataItem]));
  15267. }
  15268. }
  15269. return result.join('&');
  15270. };
  15271. var utf8 = function (text) {
  15272. text = text.replace(/\r\n/g, '\n');
  15273. var result = '';
  15274. for(var i = 0; i < text.length; i++) {
  15275. var c = text.charCodeAt(i);
  15276. if(c < 128) {
  15277. result += String.fromCharCode(c);
  15278. } else if((c > 127) && (c < 2048)) {
  15279. result += String.fromCharCode((c >> 6) | 192);
  15280. result += String.fromCharCode((c & 63) | 128);
  15281. } else {
  15282. result += String.fromCharCode((c >> 12) | 224);
  15283. result += String.fromCharCode(((c >> 6) & 63) | 128);
  15284. result += String.fromCharCode((c & 63) | 128);
  15285. }
  15286. }
  15287. return result;
  15288. };
  15289. var base64 = function (text) {
  15290. var keyStr = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
  15291. text = utf8(text);
  15292. var result = '',
  15293. chr1, chr2, chr3,
  15294. enc1, enc2, enc3, enc4,
  15295. i = 0;
  15296. do {
  15297. chr1 = text.charCodeAt(i++);
  15298. chr2 = text.charCodeAt(i++);
  15299. chr3 = text.charCodeAt(i++);
  15300. enc1 = chr1 >> 2;
  15301. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  15302. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  15303. enc4 = chr3 & 63;
  15304. if(isNaN(chr2)) {
  15305. enc3 = enc4 = 64;
  15306. } else if(isNaN(chr3)) {
  15307. enc4 = 64;
  15308. }
  15309. result +=
  15310. keyStr.charAt(enc1) +
  15311. keyStr.charAt(enc2) +
  15312. keyStr.charAt(enc3) +
  15313. keyStr.charAt(enc4);
  15314. chr1 = chr2 = chr3 = '';
  15315. enc1 = enc2 = enc3 = enc4 = '';
  15316. } while(i < text.length);
  15317. return result;
  15318. };
  15319. var mergeHeaders = function () {
  15320. // Use the first header object as base.
  15321. var result = arguments[0];
  15322. // Iterate through the remaining header objects and add them.
  15323. for(var i = 1; i < arguments.length; i++) {
  15324. var currentHeaders = arguments[i];
  15325. for(var header in currentHeaders) {
  15326. if(currentHeaders.hasOwnProperty(header)) {
  15327. result[header] = currentHeaders[header];
  15328. }
  15329. }
  15330. }
  15331. // Return the merged headers.
  15332. return result;
  15333. };
  15334. var ajax = function (method, url, options, callback) {
  15335. // Adjust parameters.
  15336. if(typeof options === 'function') {
  15337. callback = options;
  15338. options = {};
  15339. }
  15340. // Set default parameter values.
  15341. options.cache = options.cache || false;
  15342. options.data = options.data || {};
  15343. options.headers = options.headers || {};
  15344. options.jsonp = options.jsonp || false;
  15345. options.async = options.async === undefined ? true : options.async;
  15346. // Merge the various header objects.
  15347. var headers = mergeHeaders({
  15348. 'accept': '*/*',
  15349. 'content-type': 'application/x-www-form-urlencoded;charset=UTF-8'
  15350. }, ajax.headers, options.headers);
  15351. // Encode the data according to the content-type.
  15352. var payload;
  15353. if (headers['content-type'] === 'application/json') {
  15354. payload = JSON.stringify(options.data);
  15355. } else {
  15356. payload = encodeUsingUrlEncoding(options.data);
  15357. }
  15358. // Specially prepare GET requests: Setup the query string, handle caching and make a JSONP call
  15359. // if neccessary.
  15360. if(method === 'GET') {
  15361. // Setup the query string.
  15362. var queryString = [];
  15363. if(payload) {
  15364. queryString.push(payload);
  15365. payload = null;
  15366. }
  15367. // Handle caching.
  15368. if(!options.cache) {
  15369. queryString.push('_=' + (new Date()).getTime());
  15370. }
  15371. // If neccessary prepare the query string for a JSONP call.
  15372. if(options.jsonp) {
  15373. queryString.push('callback=' + options.jsonp);
  15374. queryString.push('jsonp=' + options.jsonp);
  15375. }
  15376. // Merge the query string and attach it to the url.
  15377. queryString = queryString.join('&');
  15378. if (queryString.length > 1) {
  15379. if (url.indexOf('?') > -1) {
  15380. url += '&' + queryString;
  15381. } else {
  15382. url += '?' + queryString;
  15383. }
  15384. }
  15385. // Make a JSONP call if neccessary.
  15386. if(options.jsonp) {
  15387. var head = document.getElementsByTagName('head')[0];
  15388. var script = document.createElement('script');
  15389. script.type = 'text/javascript';
  15390. script.src = url;
  15391. head.appendChild(script);
  15392. return;
  15393. }
  15394. }
  15395. // Since we got here, it is no JSONP request, so make a normal XHR request.
  15396. getXhr(function (err, xhr) {
  15397. if(err) return callback(err);
  15398. // Open the request.
  15399. xhr.open(method, url, options.async);
  15400. // Set the request headers.
  15401. for(var header in headers) {
  15402. if(headers.hasOwnProperty(header)) {
  15403. xhr.setRequestHeader(header, headers[header]);
  15404. }
  15405. }
  15406. // Handle the request events.
  15407. xhr.onreadystatechange = function () {
  15408. if(xhr.readyState === 4) {
  15409. var data = xhr.responseText || '';
  15410. // If no callback is given, return.
  15411. if(!callback) {
  15412. return;
  15413. }
  15414. // Return an object that provides access to the data as text and JSON.
  15415. callback(xhr.status, {
  15416. text: function () {
  15417. return data;
  15418. },
  15419. json: function () {
  15420. try {
  15421. return JSON.parse(data)
  15422. } catch (e) {
  15423. f.error('Can not parse JSON. URL: ' + url);
  15424. return {};
  15425. }
  15426. }
  15427. });
  15428. }
  15429. };
  15430. // Actually send the XHR request.
  15431. xhr.send(payload);
  15432. });
  15433. };
  15434. // Define the external interface.
  15435. var http = {
  15436. authBasic: function (username, password) {
  15437. ajax.headers['Authorization'] = 'Basic ' + base64(username + ':' + password);
  15438. },
  15439. connect: function (url, options, callback) {
  15440. return ajax('CONNECT', url, options, callback);
  15441. },
  15442. del: function (url, options, callback) {
  15443. return ajax('DELETE', url, options, callback);
  15444. },
  15445. get: function (url, options, callback) {
  15446. return ajax('GET', url, options, callback);
  15447. },
  15448. head: function (url, options, callback) {
  15449. return ajax('HEAD', url, options, callback);
  15450. },
  15451. headers: function (headers) {
  15452. ajax.headers = headers || {};
  15453. },
  15454. isAllowed: function (url, verb, callback) {
  15455. this.options(url, function (status, data) {
  15456. callback(data.text().indexOf(verb) !== -1);
  15457. });
  15458. },
  15459. options: function (url, options, callback) {
  15460. return ajax('OPTIONS', url, options, callback);
  15461. },
  15462. patch: function (url, options, callback) {
  15463. return ajax('PATCH', url, options, callback);
  15464. },
  15465. post: function (url, options, callback) {
  15466. return ajax('POST', url, options, callback);
  15467. },
  15468. put: function (url, options, callback) {
  15469. return ajax('PUT', url, options, callback);
  15470. },
  15471. trace: function (url, options, callback) {
  15472. return ajax('TRACE', url, options, callback);
  15473. }
  15474. };
  15475. var methode = options.type ? options.type.toLowerCase() : 'get';
  15476. http[methode](options.url, options, function (status, data) {
  15477. // file: protocol always gives status code 0, so check for data
  15478. if (status === 200 || (status === 0 && data.text())) {
  15479. options.success(data.json(), status, null);
  15480. } else {
  15481. options.error(data.text(), status, null);
  15482. }
  15483. });
  15484. }
  15485. var _cookie = {
  15486. create: function(name,value,minutes,domain) {
  15487. var expires;
  15488. if (minutes) {
  15489. var date = new Date();
  15490. date.setTime(date.getTime()+(minutes*60*1000));
  15491. expires = "; expires="+date.toGMTString();
  15492. }
  15493. else expires = "";
  15494. domain = (domain)? "domain="+domain+";" : "";
  15495. document.cookie = name+"="+value+expires+";"+domain+"path=/";
  15496. },
  15497. read: function(name) {
  15498. var nameEQ = name + "=";
  15499. var ca = document.cookie.split(';');
  15500. for(var i=0;i < ca.length;i++) {
  15501. var c = ca[i];
  15502. while (c.charAt(0)==' ') c = c.substring(1,c.length);
  15503. if (c.indexOf(nameEQ) === 0) return c.substring(nameEQ.length,c.length);
  15504. }
  15505. return null;
  15506. },
  15507. remove: function(name) {
  15508. this.create(name,"",-1);
  15509. }
  15510. };
  15511. var cookie_noop = {
  15512. create: function(name,value,minutes,domain) {},
  15513. read: function(name) { return null; },
  15514. remove: function(name) {}
  15515. };
  15516. // move dependent functions to a container so that
  15517. // they can be overriden easier in no jquery environment (node.js)
  15518. var f = {
  15519. extend: $ ? $.extend : _extend,
  15520. deepExtend: _deepExtend,
  15521. each: $ ? $.each : _each,
  15522. ajax: $ ? $.ajax : (typeof document !== 'undefined' ? _ajax : function() {}),
  15523. cookie: typeof document !== 'undefined' ? _cookie : cookie_noop,
  15524. detectLanguage: detectLanguage,
  15525. escape: _escape,
  15526. log: function(str) {
  15527. if (o.debug && typeof console !== "undefined") console.log(str);
  15528. },
  15529. error: function(str) {
  15530. if (typeof console !== "undefined") console.error(str);
  15531. },
  15532. getCountyIndexOfLng: function(lng) {
  15533. var lng_index = 0;
  15534. if (lng === 'nb-NO' || lng === 'nn-NO' || lng === 'nb-no' || lng === 'nn-no') lng_index = 1;
  15535. return lng_index;
  15536. },
  15537. toLanguages: function(lng) {
  15538. var log = this.log;
  15539. function applyCase(l) {
  15540. var ret = l;
  15541. if (typeof l === 'string' && l.indexOf('-') > -1) {
  15542. var parts = l.split('-');
  15543. ret = o.lowerCaseLng ?
  15544. parts[0].toLowerCase() + '-' + parts[1].toLowerCase() :
  15545. parts[0].toLowerCase() + '-' + parts[1].toUpperCase();
  15546. } else {
  15547. ret = o.lowerCaseLng ? l.toLowerCase() : l;
  15548. }
  15549. return ret;
  15550. }
  15551. var languages = [];
  15552. var whitelist = o.lngWhitelist || false;
  15553. var addLanguage = function(language){
  15554. //reject langs not whitelisted
  15555. if(!whitelist || whitelist.indexOf(language) > -1){
  15556. languages.push(language);
  15557. }else{
  15558. log('rejecting non-whitelisted language: ' + language);
  15559. }
  15560. };
  15561. if (typeof lng === 'string' && lng.indexOf('-') > -1) {
  15562. var parts = lng.split('-');
  15563. if (o.load !== 'unspecific') addLanguage(applyCase(lng));
  15564. if (o.load !== 'current') addLanguage(applyCase(parts[this.getCountyIndexOfLng(lng)]));
  15565. } else {
  15566. addLanguage(applyCase(lng));
  15567. }
  15568. for (var i = 0; i < o.fallbackLng.length; i++) {
  15569. if (languages.indexOf(o.fallbackLng[i]) === -1 && o.fallbackLng[i]) languages.push(applyCase(o.fallbackLng[i]));
  15570. }
  15571. return languages;
  15572. },
  15573. regexEscape: function(str) {
  15574. return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
  15575. },
  15576. regexReplacementEscape: function(strOrFn) {
  15577. if (typeof strOrFn === 'string') {
  15578. return strOrFn.replace(/\$/g, "$$$$");
  15579. } else {
  15580. return strOrFn;
  15581. }
  15582. },
  15583. localStorage: {
  15584. setItem: function(key, value) {
  15585. if (window.localStorage) {
  15586. try {
  15587. window.localStorage.setItem(key, value);
  15588. } catch (e) {
  15589. f.log('failed to set value for key "' + key + '" to localStorage.');
  15590. }
  15591. }
  15592. }
  15593. }
  15594. };
  15595. function init(options, cb) {
  15596. if (typeof options === 'function') {
  15597. cb = options;
  15598. options = {};
  15599. }
  15600. options = options || {};
  15601. // override defaults with passed in options
  15602. f.extend(o, options);
  15603. delete o.fixLng; /* passed in each time */
  15604. // override functions: .log(), .detectLanguage(), etc
  15605. if (o.functions) {
  15606. delete o.functions;
  15607. f.extend(f, options.functions);
  15608. }
  15609. // create namespace object if namespace is passed in as string
  15610. if (typeof o.ns == 'string') {
  15611. o.ns = { namespaces: [o.ns], defaultNs: o.ns};
  15612. }
  15613. // fallback namespaces
  15614. if (typeof o.fallbackNS == 'string') {
  15615. o.fallbackNS = [o.fallbackNS];
  15616. }
  15617. // fallback languages
  15618. if (typeof o.fallbackLng == 'string' || typeof o.fallbackLng == 'boolean') {
  15619. o.fallbackLng = [o.fallbackLng];
  15620. }
  15621. // escape prefix/suffix
  15622. o.interpolationPrefixEscaped = f.regexEscape(o.interpolationPrefix);
  15623. o.interpolationSuffixEscaped = f.regexEscape(o.interpolationSuffix);
  15624. if (!o.lng) o.lng = f.detectLanguage();
  15625. languages = f.toLanguages(o.lng);
  15626. currentLng = languages[0];
  15627. f.log('currentLng set to: ' + currentLng);
  15628. if (o.useCookie && f.cookie.read(o.cookieName) !== currentLng){ //cookie is unset or invalid
  15629. f.cookie.create(o.cookieName, currentLng, o.cookieExpirationTime, o.cookieDomain);
  15630. }
  15631. if (o.detectLngFromLocalStorage && typeof document !== 'undefined' && window.localStorage) {
  15632. f.localStorage.setItem('i18next_lng', currentLng);
  15633. }
  15634. var lngTranslate = translate;
  15635. if (options.fixLng) {
  15636. lngTranslate = function(key, options) {
  15637. options = options || {};
  15638. options.lng = options.lng || lngTranslate.lng;
  15639. return translate(key, options);
  15640. };
  15641. lngTranslate.lng = currentLng;
  15642. }
  15643. pluralExtensions.setCurrentLng(currentLng);
  15644. // add JQuery extensions
  15645. if ($ && o.setJqueryExt) addJqueryFunct();
  15646. // jQuery deferred
  15647. var deferred;
  15648. if ($ && $.Deferred) {
  15649. deferred = $.Deferred();
  15650. }
  15651. // return immidiatly if res are passed in
  15652. if (o.resStore) {
  15653. resStore = o.resStore;
  15654. initialized = true;
  15655. if (cb) cb(lngTranslate);
  15656. if (deferred) deferred.resolve(lngTranslate);
  15657. if (deferred) return deferred.promise();
  15658. return;
  15659. }
  15660. // languages to load
  15661. var lngsToLoad = f.toLanguages(o.lng);
  15662. if (typeof o.preload === 'string') o.preload = [o.preload];
  15663. for (var i = 0, l = o.preload.length; i < l; i++) {
  15664. var pres = f.toLanguages(o.preload[i]);
  15665. for (var y = 0, len = pres.length; y < len; y++) {
  15666. if (lngsToLoad.indexOf(pres[y]) < 0) {
  15667. lngsToLoad.push(pres[y]);
  15668. }
  15669. }
  15670. }
  15671. // else load them
  15672. i18n.sync.load(lngsToLoad, o, function(err, store) {
  15673. resStore = store;
  15674. initialized = true;
  15675. if (cb) cb(lngTranslate);
  15676. if (deferred) deferred.resolve(lngTranslate);
  15677. });
  15678. if (deferred) return deferred.promise();
  15679. }
  15680. function preload(lngs, cb) {
  15681. if (typeof lngs === 'string') lngs = [lngs];
  15682. for (var i = 0, l = lngs.length; i < l; i++) {
  15683. if (o.preload.indexOf(lngs[i]) < 0) {
  15684. o.preload.push(lngs[i]);
  15685. }
  15686. }
  15687. return init(cb);
  15688. }
  15689. function addResourceBundle(lng, ns, resources, deep) {
  15690. if (typeof ns !== 'string') {
  15691. resources = ns;
  15692. ns = o.ns.defaultNs;
  15693. } else if (o.ns.namespaces.indexOf(ns) < 0) {
  15694. o.ns.namespaces.push(ns);
  15695. }
  15696. resStore[lng] = resStore[lng] || {};
  15697. resStore[lng][ns] = resStore[lng][ns] || {};
  15698. if (deep) {
  15699. f.deepExtend(resStore[lng][ns], resources);
  15700. } else {
  15701. f.extend(resStore[lng][ns], resources);
  15702. }
  15703. }
  15704. function hasResourceBundle(lng, ns) {
  15705. if (typeof ns !== 'string') {
  15706. ns = o.ns.defaultNs;
  15707. }
  15708. resStore[lng] = resStore[lng] || {};
  15709. var res = resStore[lng][ns] || {};
  15710. var hasValues = false;
  15711. for(var prop in res) {
  15712. if (res.hasOwnProperty(prop)) {
  15713. hasValues = true;
  15714. }
  15715. }
  15716. return hasValues;
  15717. }
  15718. function removeResourceBundle(lng, ns) {
  15719. if (typeof ns !== 'string') {
  15720. ns = o.ns.defaultNs;
  15721. }
  15722. resStore[lng] = resStore[lng] || {};
  15723. resStore[lng][ns] = {};
  15724. }
  15725. function addResource(lng, ns, key, value) {
  15726. if (typeof ns !== 'string') {
  15727. resource = ns;
  15728. ns = o.ns.defaultNs;
  15729. } else if (o.ns.namespaces.indexOf(ns) < 0) {
  15730. o.ns.namespaces.push(ns);
  15731. }
  15732. resStore[lng] = resStore[lng] || {};
  15733. resStore[lng][ns] = resStore[lng][ns] || {};
  15734. var keys = key.split(o.keyseparator);
  15735. var x = 0;
  15736. var node = resStore[lng][ns];
  15737. var origRef = node;
  15738. while (keys[x]) {
  15739. if (x == keys.length - 1)
  15740. node[keys[x]] = value;
  15741. else {
  15742. if (node[keys[x]] == null)
  15743. node[keys[x]] = {};
  15744. node = node[keys[x]];
  15745. }
  15746. x++;
  15747. }
  15748. }
  15749. function addResources(lng, ns, resources) {
  15750. if (typeof ns !== 'string') {
  15751. resource = ns;
  15752. ns = o.ns.defaultNs;
  15753. } else if (o.ns.namespaces.indexOf(ns) < 0) {
  15754. o.ns.namespaces.push(ns);
  15755. }
  15756. for (var m in resources) {
  15757. if (typeof resources[m] === 'string') addResource(lng, ns, m, resources[m]);
  15758. }
  15759. }
  15760. function setDefaultNamespace(ns) {
  15761. o.ns.defaultNs = ns;
  15762. }
  15763. function loadNamespace(namespace, cb) {
  15764. loadNamespaces([namespace], cb);
  15765. }
  15766. function loadNamespaces(namespaces, cb) {
  15767. var opts = {
  15768. dynamicLoad: o.dynamicLoad,
  15769. resGetPath: o.resGetPath,
  15770. getAsync: o.getAsync,
  15771. customLoad: o.customLoad,
  15772. ns: { namespaces: namespaces, defaultNs: ''} /* new namespaces to load */
  15773. };
  15774. // languages to load
  15775. var lngsToLoad = f.toLanguages(o.lng);
  15776. if (typeof o.preload === 'string') o.preload = [o.preload];
  15777. for (var i = 0, l = o.preload.length; i < l; i++) {
  15778. var pres = f.toLanguages(o.preload[i]);
  15779. for (var y = 0, len = pres.length; y < len; y++) {
  15780. if (lngsToLoad.indexOf(pres[y]) < 0) {
  15781. lngsToLoad.push(pres[y]);
  15782. }
  15783. }
  15784. }
  15785. // check if we have to load
  15786. var lngNeedLoad = [];
  15787. for (var a = 0, lenA = lngsToLoad.length; a < lenA; a++) {
  15788. var needLoad = false;
  15789. var resSet = resStore[lngsToLoad[a]];
  15790. if (resSet) {
  15791. for (var b = 0, lenB = namespaces.length; b < lenB; b++) {
  15792. if (!resSet[namespaces[b]]) needLoad = true;
  15793. }
  15794. } else {
  15795. needLoad = true;
  15796. }
  15797. if (needLoad) lngNeedLoad.push(lngsToLoad[a]);
  15798. }
  15799. if (lngNeedLoad.length) {
  15800. i18n.sync._fetch(lngNeedLoad, opts, function(err, store) {
  15801. var todo = namespaces.length * lngNeedLoad.length;
  15802. // load each file individual
  15803. f.each(namespaces, function(nsIndex, nsValue) {
  15804. // append namespace to namespace array
  15805. if (o.ns.namespaces.indexOf(nsValue) < 0) {
  15806. o.ns.namespaces.push(nsValue);
  15807. }
  15808. f.each(lngNeedLoad, function(lngIndex, lngValue) {
  15809. resStore[lngValue] = resStore[lngValue] || {};
  15810. resStore[lngValue][nsValue] = store[lngValue][nsValue];
  15811. todo--; // wait for all done befor callback
  15812. if (todo === 0 && cb) {
  15813. if (o.useLocalStorage) i18n.sync._storeLocal(resStore);
  15814. cb();
  15815. }
  15816. });
  15817. });
  15818. });
  15819. } else {
  15820. if (cb) cb();
  15821. }
  15822. }
  15823. function setLng(lng, options, cb) {
  15824. if (typeof options === 'function') {
  15825. cb = options;
  15826. options = {};
  15827. } else if (!options) {
  15828. options = {};
  15829. }
  15830. options.lng = lng;
  15831. return init(options, cb);
  15832. }
  15833. function lng() {
  15834. return currentLng;
  15835. }
  15836. function reload(cb) {
  15837. resStore = {};
  15838. setLng(currentLng, cb);
  15839. }
  15840. function addJqueryFunct() {
  15841. // $.t shortcut
  15842. $.t = $.t || translate;
  15843. function parse(ele, key, options) {
  15844. if (key.length === 0) return;
  15845. var attr = 'text';
  15846. if (key.indexOf('[') === 0) {
  15847. var parts = key.split(']');
  15848. key = parts[1];
  15849. attr = parts[0].substr(1, parts[0].length-1);
  15850. }
  15851. if (key.indexOf(';') === key.length-1) {
  15852. key = key.substr(0, key.length-2);
  15853. }
  15854. var optionsToUse;
  15855. if (attr === 'html') {
  15856. optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.html() }, options) : options;
  15857. ele.html($.t(key, optionsToUse));
  15858. } else if (attr === 'text') {
  15859. optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.text() }, options) : options;
  15860. ele.text($.t(key, optionsToUse));
  15861. } else if (attr === 'prepend') {
  15862. optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.html() }, options) : options;
  15863. ele.prepend($.t(key, optionsToUse));
  15864. } else if (attr === 'append') {
  15865. optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.html() }, options) : options;
  15866. ele.append($.t(key, optionsToUse));
  15867. } else if (attr.indexOf("data-") === 0) {
  15868. var dataAttr = attr.substr(("data-").length);
  15869. optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.data(dataAttr) }, options) : options;
  15870. var translated = $.t(key, optionsToUse);
  15871. //we change into the data cache
  15872. ele.data(dataAttr, translated);
  15873. //we change into the dom
  15874. ele.attr(attr, translated);
  15875. } else {
  15876. optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.attr(attr) }, options) : options;
  15877. ele.attr(attr, $.t(key, optionsToUse));
  15878. }
  15879. }
  15880. function localize(ele, options) {
  15881. var key = ele.attr(o.selectorAttr);
  15882. if (!key && typeof key !== 'undefined' && key !== false) key = ele.text() || ele.val();
  15883. if (!key) return;
  15884. var target = ele
  15885. , targetSelector = ele.data("i18n-target");
  15886. if (targetSelector) {
  15887. target = ele.find(targetSelector) || ele;
  15888. }
  15889. if (!options && o.useDataAttrOptions === true) {
  15890. options = ele.data("i18n-options");
  15891. }
  15892. options = options || {};
  15893. if (key.indexOf(';') >= 0) {
  15894. var keys = key.split(';');
  15895. $.each(keys, function(m, k) {
  15896. if (k !== '') parse(target, k, options);
  15897. });
  15898. } else {
  15899. parse(target, key, options);
  15900. }
  15901. if (o.useDataAttrOptions === true) ele.data("i18n-options", options);
  15902. }
  15903. // fn
  15904. $.fn.i18n = function (options) {
  15905. return this.each(function() {
  15906. // localize element itself
  15907. localize($(this), options);
  15908. // localize childs
  15909. var elements = $(this).find('[' + o.selectorAttr + ']');
  15910. elements.each(function() {
  15911. localize($(this), options);
  15912. });
  15913. });
  15914. };
  15915. }
  15916. function applyReplacement(str, replacementHash, nestedKey, options) {
  15917. if (!str) return str;
  15918. options = options || replacementHash; // first call uses replacement hash combined with options
  15919. if (str.indexOf(options.interpolationPrefix || o.interpolationPrefix) < 0) return str;
  15920. var prefix = options.interpolationPrefix ? f.regexEscape(options.interpolationPrefix) : o.interpolationPrefixEscaped
  15921. , suffix = options.interpolationSuffix ? f.regexEscape(options.interpolationSuffix) : o.interpolationSuffixEscaped
  15922. , unEscapingSuffix = 'HTML'+suffix;
  15923. var hash = replacementHash.replace && typeof replacementHash.replace === 'object' ? replacementHash.replace : replacementHash;
  15924. f.each(hash, function(key, value) {
  15925. var nextKey = nestedKey ? nestedKey + o.keyseparator + key : key;
  15926. if (typeof value === 'object' && value !== null) {
  15927. str = applyReplacement(str, value, nextKey, options);
  15928. } else {
  15929. if (options.escapeInterpolation || o.escapeInterpolation) {
  15930. str = str.replace(new RegExp([prefix, nextKey, unEscapingSuffix].join(''), 'g'), f.regexReplacementEscape(value));
  15931. str = str.replace(new RegExp([prefix, nextKey, suffix].join(''), 'g'), f.regexReplacementEscape(f.escape(value)));
  15932. } else {
  15933. str = str.replace(new RegExp([prefix, nextKey, suffix].join(''), 'g'), f.regexReplacementEscape(value));
  15934. }
  15935. // str = options.escapeInterpolation;
  15936. }
  15937. });
  15938. return str;
  15939. }
  15940. // append it to functions
  15941. f.applyReplacement = applyReplacement;
  15942. function applyReuse(translated, options) {
  15943. var comma = ',';
  15944. var options_open = '{';
  15945. var options_close = '}';
  15946. var opts = f.extend({}, options);
  15947. delete opts.postProcess;
  15948. while (translated.indexOf(o.reusePrefix) != -1) {
  15949. replacementCounter++;
  15950. if (replacementCounter > o.maxRecursion) { break; } // safety net for too much recursion
  15951. var index_of_opening = translated.lastIndexOf(o.reusePrefix);
  15952. var index_of_end_of_closing = translated.indexOf(o.reuseSuffix, index_of_opening) + o.reuseSuffix.length;
  15953. var token = translated.substring(index_of_opening, index_of_end_of_closing);
  15954. var token_without_symbols = token.replace(o.reusePrefix, '').replace(o.reuseSuffix, '');
  15955. if (index_of_end_of_closing <= index_of_opening) {
  15956. f.error('there is an missing closing in following translation value', translated);
  15957. return '';
  15958. }
  15959. if (token_without_symbols.indexOf(comma) != -1) {
  15960. var index_of_token_end_of_closing = token_without_symbols.indexOf(comma);
  15961. 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) {
  15962. var index_of_opts_opening = token_without_symbols.indexOf(options_open, index_of_token_end_of_closing);
  15963. var index_of_opts_end_of_closing = token_without_symbols.indexOf(options_close, index_of_opts_opening) + options_close.length;
  15964. try {
  15965. opts = f.extend(opts, JSON.parse(token_without_symbols.substring(index_of_opts_opening, index_of_opts_end_of_closing)));
  15966. token_without_symbols = token_without_symbols.substring(0, index_of_token_end_of_closing);
  15967. } catch (e) {
  15968. }
  15969. }
  15970. }
  15971. var translated_token = _translate(token_without_symbols, opts);
  15972. translated = translated.replace(token, f.regexReplacementEscape(translated_token));
  15973. }
  15974. return translated;
  15975. }
  15976. function hasContext(options) {
  15977. return (options.context && (typeof options.context == 'string' || typeof options.context == 'number'));
  15978. }
  15979. function needsPlural(options, lng) {
  15980. return (options.count !== undefined && typeof options.count != 'string'/* && pluralExtensions.needsPlural(lng, options.count)*/);
  15981. }
  15982. function needsIndefiniteArticle(options) {
  15983. return (options.indefinite_article !== undefined && typeof options.indefinite_article != 'string' && options.indefinite_article);
  15984. }
  15985. function exists(key, options) {
  15986. options = options || {};
  15987. var notFound = _getDefaultValue(key, options)
  15988. , found = _find(key, options);
  15989. return found !== undefined || found === notFound;
  15990. }
  15991. function translate(key, options) {
  15992. options = options || {};
  15993. if (!initialized) {
  15994. f.log('i18next not finished initialization. you might have called t function before loading resources finished.')
  15995. return options.defaultValue || '';
  15996. };
  15997. replacementCounter = 0;
  15998. return _translate.apply(null, arguments);
  15999. }
  16000. function _getDefaultValue(key, options) {
  16001. return (options.defaultValue !== undefined) ? options.defaultValue : key;
  16002. }
  16003. function _injectSprintfProcessor() {
  16004. var values = [];
  16005. // mh: build array from second argument onwards
  16006. for (var i = 1; i < arguments.length; i++) {
  16007. values.push(arguments[i]);
  16008. }
  16009. return {
  16010. postProcess: 'sprintf',
  16011. sprintf: values
  16012. };
  16013. }
  16014. function _translate(potentialKeys, options) {
  16015. if (options && typeof options !== 'object') {
  16016. if (o.shortcutFunction === 'sprintf') {
  16017. // mh: gettext like sprintf syntax found, automatically create sprintf processor
  16018. options = _injectSprintfProcessor.apply(null, arguments);
  16019. } else if (o.shortcutFunction === 'defaultValue') {
  16020. options = {
  16021. defaultValue: options
  16022. }
  16023. }
  16024. } else {
  16025. options = options || {};
  16026. }
  16027. if (typeof o.defaultVariables === 'object') {
  16028. options = f.extend({}, o.defaultVariables, options);
  16029. }
  16030. if (potentialKeys === undefined || potentialKeys === null || potentialKeys === '') return '';
  16031. if (typeof potentialKeys === 'string') {
  16032. potentialKeys = [potentialKeys];
  16033. }
  16034. var key = potentialKeys[0];
  16035. if (potentialKeys.length > 1) {
  16036. for (var i = 0; i < potentialKeys.length; i++) {
  16037. key = potentialKeys[i];
  16038. if (exists(key, options)) {
  16039. break;
  16040. }
  16041. }
  16042. }
  16043. var notFound = _getDefaultValue(key, options)
  16044. , found = _find(key, options)
  16045. , lngs = options.lng ? f.toLanguages(options.lng, options.fallbackLng) : languages
  16046. , ns = options.ns || o.ns.defaultNs
  16047. , parts;
  16048. // split ns and key
  16049. if (key.indexOf(o.nsseparator) > -1) {
  16050. parts = key.split(o.nsseparator);
  16051. ns = parts[0];
  16052. key = parts[1];
  16053. }
  16054. if (found === undefined && o.sendMissing && typeof o.missingKeyHandler === 'function') {
  16055. if (options.lng) {
  16056. o.missingKeyHandler(lngs[0], ns, key, notFound, lngs);
  16057. } else {
  16058. o.missingKeyHandler(o.lng, ns, key, notFound, lngs);
  16059. }
  16060. }
  16061. var postProcessor = options.postProcess || o.postProcess;
  16062. if (found !== undefined && postProcessor) {
  16063. if (postProcessors[postProcessor]) {
  16064. found = postProcessors[postProcessor](found, key, options);
  16065. }
  16066. }
  16067. // process notFound if function exists
  16068. var splitNotFound = notFound;
  16069. if (notFound.indexOf(o.nsseparator) > -1) {
  16070. parts = notFound.split(o.nsseparator);
  16071. splitNotFound = parts[1];
  16072. }
  16073. if (splitNotFound === key && o.parseMissingKey) {
  16074. notFound = o.parseMissingKey(notFound);
  16075. }
  16076. if (found === undefined) {
  16077. notFound = applyReplacement(notFound, options);
  16078. notFound = applyReuse(notFound, options);
  16079. if (postProcessor && postProcessors[postProcessor]) {
  16080. var val = _getDefaultValue(key, options);
  16081. found = postProcessors[postProcessor](val, key, options);
  16082. }
  16083. }
  16084. return (found !== undefined) ? found : notFound;
  16085. }
  16086. function _find(key, options) {
  16087. options = options || {};
  16088. var optionWithoutCount, translated
  16089. , notFound = _getDefaultValue(key, options)
  16090. , lngs = languages;
  16091. if (!resStore) { return notFound; } // no resStore to translate from
  16092. // CI mode
  16093. if (lngs[0].toLowerCase() === 'cimode') return notFound;
  16094. // passed in lng
  16095. if (options.lngs) lngs = options.lngs;
  16096. if (options.lng) {
  16097. lngs = f.toLanguages(options.lng, options.fallbackLng);
  16098. if (!resStore[lngs[0]]) {
  16099. var oldAsync = o.getAsync;
  16100. o.getAsync = false;
  16101. i18n.sync.load(lngs, o, function(err, store) {
  16102. f.extend(resStore, store);
  16103. o.getAsync = oldAsync;
  16104. });
  16105. }
  16106. }
  16107. var ns = options.ns || o.ns.defaultNs;
  16108. if (key.indexOf(o.nsseparator) > -1) {
  16109. var parts = key.split(o.nsseparator);
  16110. ns = parts[0];
  16111. key = parts[1];
  16112. }
  16113. if (hasContext(options)) {
  16114. optionWithoutCount = f.extend({}, options);
  16115. delete optionWithoutCount.context;
  16116. optionWithoutCount.defaultValue = o.contextNotFound;
  16117. var contextKey = ns + o.nsseparator + key + '_' + options.context;
  16118. translated = translate(contextKey, optionWithoutCount);
  16119. if (translated != o.contextNotFound) {
  16120. return applyReplacement(translated, { context: options.context }); // apply replacement for context only
  16121. } // else continue translation with original/nonContext key
  16122. }
  16123. if (needsPlural(options, lngs[0])) {
  16124. optionWithoutCount = f.extend({ lngs: [lngs[0]]}, options);
  16125. delete optionWithoutCount.count;
  16126. delete optionWithoutCount.lng;
  16127. optionWithoutCount.defaultValue = o.pluralNotFound;
  16128. var pluralKey;
  16129. if (!pluralExtensions.needsPlural(lngs[0], options.count)) {
  16130. pluralKey = ns + o.nsseparator + key;
  16131. } else {
  16132. pluralKey = ns + o.nsseparator + key + o.pluralSuffix;
  16133. var pluralExtension = pluralExtensions.get(lngs[0], options.count);
  16134. if (pluralExtension >= 0) {
  16135. pluralKey = pluralKey + '_' + pluralExtension;
  16136. } else if (pluralExtension === 1) {
  16137. pluralKey = ns + o.nsseparator + key; // singular
  16138. }
  16139. }
  16140. translated = translate(pluralKey, optionWithoutCount);
  16141. if (translated != o.pluralNotFound) {
  16142. return applyReplacement(translated, {
  16143. count: options.count,
  16144. interpolationPrefix: options.interpolationPrefix,
  16145. interpolationSuffix: options.interpolationSuffix
  16146. }); // apply replacement for count only
  16147. } else if (lngs.length > 1) {
  16148. // remove failed lng
  16149. var clone = lngs.slice();
  16150. clone.shift();
  16151. options = f.extend(options, { lngs: clone });
  16152. delete options.lng;
  16153. // retry with fallbacks
  16154. translated = translate(ns + o.nsseparator + key, options);
  16155. if (translated != o.pluralNotFound) return translated;
  16156. } else {
  16157. return translated;
  16158. }
  16159. }
  16160. if (needsIndefiniteArticle(options)) {
  16161. var optionsWithoutIndef = f.extend({}, options);
  16162. delete optionsWithoutIndef.indefinite_article;
  16163. optionsWithoutIndef.defaultValue = o.indefiniteNotFound;
  16164. // If we don't have a count, we want the indefinite, if we do have a count, and needsPlural is false
  16165. var indefiniteKey = ns + o.nsseparator + key + (((options.count && !needsPlural(options, lngs[0])) || !options.count) ? o.indefiniteSuffix : "");
  16166. translated = translate(indefiniteKey, optionsWithoutIndef);
  16167. if (translated != o.indefiniteNotFound) {
  16168. return translated;
  16169. }
  16170. }
  16171. var found;
  16172. var keys = key.split(o.keyseparator);
  16173. for (var i = 0, len = lngs.length; i < len; i++ ) {
  16174. if (found !== undefined) break;
  16175. var l = lngs[i];
  16176. var x = 0;
  16177. var value = resStore[l] && resStore[l][ns];
  16178. while (keys[x]) {
  16179. value = value && value[keys[x]];
  16180. x++;
  16181. }
  16182. if (value !== undefined) {
  16183. var valueType = Object.prototype.toString.apply(value);
  16184. if (typeof value === 'string') {
  16185. value = applyReplacement(value, options);
  16186. value = applyReuse(value, options);
  16187. } else if (valueType === '[object Array]' && !o.returnObjectTrees && !options.returnObjectTrees) {
  16188. value = value.join('\n');
  16189. value = applyReplacement(value, options);
  16190. value = applyReuse(value, options);
  16191. } else if (value === null && o.fallbackOnNull === true) {
  16192. value = undefined;
  16193. } else if (value !== null) {
  16194. if (!o.returnObjectTrees && !options.returnObjectTrees) {
  16195. if (o.objectTreeKeyHandler && typeof o.objectTreeKeyHandler == 'function') {
  16196. value = o.objectTreeKeyHandler(key, value, l, ns, options);
  16197. } else {
  16198. value = 'key \'' + ns + ':' + key + ' (' + l + ')\' ' +
  16199. 'returned an object instead of string.';
  16200. f.log(value);
  16201. }
  16202. } else if (valueType !== '[object Number]' && valueType !== '[object Function]' && valueType !== '[object RegExp]') {
  16203. var copy = (valueType === '[object Array]') ? [] : {}; // apply child translation on a copy
  16204. f.each(value, function(m) {
  16205. copy[m] = _translate(ns + o.nsseparator + key + o.keyseparator + m, options);
  16206. });
  16207. value = copy;
  16208. }
  16209. }
  16210. if (typeof value === 'string' && value.trim() === '' && o.fallbackOnEmpty === true)
  16211. value = undefined;
  16212. found = value;
  16213. }
  16214. }
  16215. if (found === undefined && !options.isFallbackLookup && (o.fallbackToDefaultNS === true || (o.fallbackNS && o.fallbackNS.length > 0))) {
  16216. // set flag for fallback lookup - avoid recursion
  16217. options.isFallbackLookup = true;
  16218. if (o.fallbackNS.length) {
  16219. for (var y = 0, lenY = o.fallbackNS.length; y < lenY; y++) {
  16220. found = _find(o.fallbackNS[y] + o.nsseparator + key, options);
  16221. if (found || (found==="" && o.fallbackOnEmpty === false)) {
  16222. /* compare value without namespace */
  16223. var foundValue = found.indexOf(o.nsseparator) > -1 ? found.split(o.nsseparator)[1] : found
  16224. , notFoundValue = notFound.indexOf(o.nsseparator) > -1 ? notFound.split(o.nsseparator)[1] : notFound;
  16225. if (foundValue !== notFoundValue) break;
  16226. }
  16227. }
  16228. } else {
  16229. found = _find(key, options); // fallback to default NS
  16230. }
  16231. options.isFallbackLookup = false;
  16232. }
  16233. return found;
  16234. }
  16235. function detectLanguage() {
  16236. var detectedLng;
  16237. var whitelist = o.lngWhitelist || [];
  16238. var userLngChoices = [];
  16239. // get from qs
  16240. var qsParm = [];
  16241. if (typeof window !== 'undefined') {
  16242. (function() {
  16243. var query = window.location.search.substring(1);
  16244. var params = query.split('&');
  16245. for (var i=0; i<params.length; i++) {
  16246. var pos = params[i].indexOf('=');
  16247. if (pos > 0) {
  16248. var key = params[i].substring(0,pos);
  16249. if (key == o.detectLngQS) {
  16250. userLngChoices.push(params[i].substring(pos+1));
  16251. }
  16252. }
  16253. }
  16254. })();
  16255. }
  16256. // get from cookie
  16257. if (o.useCookie && typeof document !== 'undefined') {
  16258. var c = f.cookie.read(o.cookieName);
  16259. if (c) userLngChoices.push(c);
  16260. }
  16261. // get from localStorage
  16262. if (o.detectLngFromLocalStorage && typeof window !== 'undefined' && window.localStorage) {
  16263. userLngChoices.push(window.localStorage.getItem('i18next_lng'));
  16264. }
  16265. // get from navigator
  16266. if (typeof navigator !== 'undefined') {
  16267. if (navigator.languages) { // chrome only; not an array, so can't use .push.apply instead of iterating
  16268. for (var i=0;i<navigator.languages.length;i++) {
  16269. userLngChoices.push(navigator.languages[i]);
  16270. }
  16271. }
  16272. if (navigator.userLanguage) {
  16273. userLngChoices.push(navigator.userLanguage);
  16274. }
  16275. if (navigator.language) {
  16276. userLngChoices.push(navigator.language);
  16277. }
  16278. }
  16279. (function() {
  16280. for (var i=0;i<userLngChoices.length;i++) {
  16281. var lng = userLngChoices[i];
  16282. if (lng.indexOf('-') > -1) {
  16283. var parts = lng.split('-');
  16284. lng = o.lowerCaseLng ?
  16285. parts[0].toLowerCase() + '-' + parts[1].toLowerCase() :
  16286. parts[0].toLowerCase() + '-' + parts[1].toUpperCase();
  16287. }
  16288. if (whitelist.length === 0 || whitelist.indexOf(lng) > -1) {
  16289. detectedLng = lng;
  16290. break;
  16291. }
  16292. }
  16293. })();
  16294. //fallback
  16295. if (!detectedLng){
  16296. detectedLng = o.fallbackLng[0];
  16297. }
  16298. return detectedLng;
  16299. }
  16300. // definition http://translate.sourceforge.net/wiki/l10n/pluralforms
  16301. /* [code, name, numbers, pluralsType] */
  16302. var _rules = [
  16303. ["ach", "Acholi", [1,2], 1],
  16304. ["af", "Afrikaans",[1,2], 2],
  16305. ["ak", "Akan", [1,2], 1],
  16306. ["am", "Amharic", [1,2], 1],
  16307. ["an", "Aragonese",[1,2], 2],
  16308. ["ar", "Arabic", [0,1,2,3,11,100],5],
  16309. ["arn", "Mapudungun",[1,2], 1],
  16310. ["ast", "Asturian", [1,2], 2],
  16311. ["ay", "Aymará", [1], 3],
  16312. ["az", "Azerbaijani",[1,2],2],
  16313. ["be", "Belarusian",[1,2,5],4],
  16314. ["bg", "Bulgarian",[1,2], 2],
  16315. ["bn", "Bengali", [1,2], 2],
  16316. ["bo", "Tibetan", [1], 3],
  16317. ["br", "Breton", [1,2], 1],
  16318. ["bs", "Bosnian", [1,2,5],4],
  16319. ["ca", "Catalan", [1,2], 2],
  16320. ["cgg", "Chiga", [1], 3],
  16321. ["cs", "Czech", [1,2,5],6],
  16322. ["csb", "Kashubian",[1,2,5],7],
  16323. ["cy", "Welsh", [1,2,3,8],8],
  16324. ["da", "Danish", [1,2], 2],
  16325. ["de", "German", [1,2], 2],
  16326. ["dev", "Development Fallback", [1,2], 2],
  16327. ["dz", "Dzongkha", [1], 3],
  16328. ["el", "Greek", [1,2], 2],
  16329. ["en", "English", [1,2], 2],
  16330. ["eo", "Esperanto",[1,2], 2],
  16331. ["es", "Spanish", [1,2], 2],
  16332. ["es_ar","Argentinean Spanish", [1,2], 2],
  16333. ["et", "Estonian", [1,2], 2],
  16334. ["eu", "Basque", [1,2], 2],
  16335. ["fa", "Persian", [1], 3],
  16336. ["fi", "Finnish", [1,2], 2],
  16337. ["fil", "Filipino", [1,2], 1],
  16338. ["fo", "Faroese", [1,2], 2],
  16339. ["fr", "French", [1,2], 9],
  16340. ["fur", "Friulian", [1,2], 2],
  16341. ["fy", "Frisian", [1,2], 2],
  16342. ["ga", "Irish", [1,2,3,7,11],10],
  16343. ["gd", "Scottish Gaelic",[1,2,3,20],11],
  16344. ["gl", "Galician", [1,2], 2],
  16345. ["gu", "Gujarati", [1,2], 2],
  16346. ["gun", "Gun", [1,2], 1],
  16347. ["ha", "Hausa", [1,2], 2],
  16348. ["he", "Hebrew", [1,2], 2],
  16349. ["hi", "Hindi", [1,2], 2],
  16350. ["hr", "Croatian", [1,2,5],4],
  16351. ["hu", "Hungarian",[1,2], 2],
  16352. ["hy", "Armenian", [1,2], 2],
  16353. ["ia", "Interlingua",[1,2],2],
  16354. ["id", "Indonesian",[1], 3],
  16355. ["is", "Icelandic",[1,2], 12],
  16356. ["it", "Italian", [1,2], 2],
  16357. ["ja", "Japanese", [1], 3],
  16358. ["jbo", "Lojban", [1], 3],
  16359. ["jv", "Javanese", [0,1], 13],
  16360. ["ka", "Georgian", [1], 3],
  16361. ["kk", "Kazakh", [1], 3],
  16362. ["km", "Khmer", [1], 3],
  16363. ["kn", "Kannada", [1,2], 2],
  16364. ["ko", "Korean", [1], 3],
  16365. ["ku", "Kurdish", [1,2], 2],
  16366. ["kw", "Cornish", [1,2,3,4],14],
  16367. ["ky", "Kyrgyz", [1], 3],
  16368. ["lb", "Letzeburgesch",[1,2],2],
  16369. ["ln", "Lingala", [1,2], 1],
  16370. ["lo", "Lao", [1], 3],
  16371. ["lt", "Lithuanian",[1,2,10],15],
  16372. ["lv", "Latvian", [1,2,0],16],
  16373. ["mai", "Maithili", [1,2], 2],
  16374. ["mfe", "Mauritian Creole",[1,2],1],
  16375. ["mg", "Malagasy", [1,2], 1],
  16376. ["mi", "Maori", [1,2], 1],
  16377. ["mk", "Macedonian",[1,2],17],
  16378. ["ml", "Malayalam",[1,2], 2],
  16379. ["mn", "Mongolian",[1,2], 2],
  16380. ["mnk", "Mandinka", [0,1,2],18],
  16381. ["mr", "Marathi", [1,2], 2],
  16382. ["ms", "Malay", [1], 3],
  16383. ["mt", "Maltese", [1,2,11,20],19],
  16384. ["nah", "Nahuatl", [1,2], 2],
  16385. ["nap", "Neapolitan",[1,2], 2],
  16386. ["nb", "Norwegian Bokmal",[1,2],2],
  16387. ["ne", "Nepali", [1,2], 2],
  16388. ["nl", "Dutch", [1,2], 2],
  16389. ["nn", "Norwegian Nynorsk",[1,2],2],
  16390. ["no", "Norwegian",[1,2], 2],
  16391. ["nso", "Northern Sotho",[1,2],2],
  16392. ["oc", "Occitan", [1,2], 1],
  16393. ["or", "Oriya", [2,1], 2],
  16394. ["pa", "Punjabi", [1,2], 2],
  16395. ["pap", "Papiamento",[1,2], 2],
  16396. ["pl", "Polish", [1,2,5],7],
  16397. ["pms", "Piemontese",[1,2], 2],
  16398. ["ps", "Pashto", [1,2], 2],
  16399. ["pt", "Portuguese",[1,2], 2],
  16400. ["pt_br","Brazilian Portuguese",[1,2], 2],
  16401. ["rm", "Romansh", [1,2], 2],
  16402. ["ro", "Romanian", [1,2,20],20],
  16403. ["ru", "Russian", [1,2,5],4],
  16404. ["sah", "Yakut", [1], 3],
  16405. ["sco", "Scots", [1,2], 2],
  16406. ["se", "Northern Sami",[1,2], 2],
  16407. ["si", "Sinhala", [1,2], 2],
  16408. ["sk", "Slovak", [1,2,5],6],
  16409. ["sl", "Slovenian",[5,1,2,3],21],
  16410. ["so", "Somali", [1,2], 2],
  16411. ["son", "Songhay", [1,2], 2],
  16412. ["sq", "Albanian", [1,2], 2],
  16413. ["sr", "Serbian", [1,2,5],4],
  16414. ["su", "Sundanese",[1], 3],
  16415. ["sv", "Swedish", [1,2], 2],
  16416. ["sw", "Swahili", [1,2], 2],
  16417. ["ta", "Tamil", [1,2], 2],
  16418. ["te", "Telugu", [1,2], 2],
  16419. ["tg", "Tajik", [1,2], 1],
  16420. ["th", "Thai", [1], 3],
  16421. ["ti", "Tigrinya", [1,2], 1],
  16422. ["tk", "Turkmen", [1,2], 2],
  16423. ["tr", "Turkish", [1,2], 1],
  16424. ["tt", "Tatar", [1], 3],
  16425. ["ug", "Uyghur", [1], 3],
  16426. ["uk", "Ukrainian",[1,2,5],4],
  16427. ["ur", "Urdu", [1,2], 2],
  16428. ["uz", "Uzbek", [1,2], 1],
  16429. ["vi", "Vietnamese",[1], 3],
  16430. ["wa", "Walloon", [1,2], 1],
  16431. ["wo", "Wolof", [1], 3],
  16432. ["yo", "Yoruba", [1,2], 2],
  16433. ["zh", "Chinese", [1], 3]
  16434. ];
  16435. var _rulesPluralsTypes = {
  16436. 1: function(n) {return Number(n > 1);},
  16437. 2: function(n) {return Number(n != 1);},
  16438. 3: function(n) {return 0;},
  16439. 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);},
  16440. 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);},
  16441. 6: function(n) {return Number((n==1) ? 0 : (n>=2 && n<=4) ? 1 : 2);},
  16442. 7: function(n) {return Number(n==1 ? 0 : n%10>=2 && n%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2);},
  16443. 8: function(n) {return Number((n==1) ? 0 : (n==2) ? 1 : (n != 8 && n != 11) ? 2 : 3);},
  16444. 9: function(n) {return Number(n >= 2);},
  16445. 10: function(n) {return Number(n==1 ? 0 : n==2 ? 1 : n<7 ? 2 : n<11 ? 3 : 4) ;},
  16446. 11: function(n) {return Number((n==1 || n==11) ? 0 : (n==2 || n==12) ? 1 : (n > 2 && n < 20) ? 2 : 3);},
  16447. 12: function(n) {return Number(n%10!=1 || n%100==11);},
  16448. 13: function(n) {return Number(n !== 0);},
  16449. 14: function(n) {return Number((n==1) ? 0 : (n==2) ? 1 : (n == 3) ? 2 : 3);},
  16450. 15: function(n) {return Number(n%10==1 && n%100!=11 ? 0 : n%10>=2 && (n%100<10 || n%100>=20) ? 1 : 2);},
  16451. 16: function(n) {return Number(n%10==1 && n%100!=11 ? 0 : n !== 0 ? 1 : 2);},
  16452. 17: function(n) {return Number(n==1 || n%10==1 ? 0 : 1);},
  16453. 18: function(n) {return Number(0 ? 0 : n==1 ? 1 : 2);},
  16454. 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);},
  16455. 20: function(n) {return Number(n==1 ? 0 : (n===0 || (n%100 > 0 && n%100 < 20)) ? 1 : 2);},
  16456. 21: function(n) {return Number(n%100==1 ? 1 : n%100==2 ? 2 : n%100==3 || n%100==4 ? 3 : 0); }
  16457. };
  16458. var pluralExtensions = {
  16459. rules: (function () {
  16460. var l, rules = {};
  16461. for (l=_rules.length; l-- ;) {
  16462. rules[_rules[l][0]] = {
  16463. name: _rules[l][1],
  16464. numbers: _rules[l][2],
  16465. plurals: _rulesPluralsTypes[_rules[l][3]]
  16466. }
  16467. }
  16468. return rules;
  16469. }()),
  16470. // you can add your own pluralExtensions
  16471. addRule: function(lng, obj) {
  16472. pluralExtensions.rules[lng] = obj;
  16473. },
  16474. setCurrentLng: function(lng) {
  16475. if (!pluralExtensions.currentRule || pluralExtensions.currentRule.lng !== lng) {
  16476. var parts = lng.split('-');
  16477. pluralExtensions.currentRule = {
  16478. lng: lng,
  16479. rule: pluralExtensions.rules[parts[0]]
  16480. };
  16481. }
  16482. },
  16483. needsPlural: function(lng, count) {
  16484. var parts = lng.split('-');
  16485. var ext;
  16486. if (pluralExtensions.currentRule && pluralExtensions.currentRule.lng === lng) {
  16487. ext = pluralExtensions.currentRule.rule;
  16488. } else {
  16489. ext = pluralExtensions.rules[parts[f.getCountyIndexOfLng(lng)]];
  16490. }
  16491. if (ext && ext.numbers.length <= 1) {
  16492. return false;
  16493. } else {
  16494. return this.get(lng, count) !== 1;
  16495. }
  16496. },
  16497. get: function(lng, count) {
  16498. var parts = lng.split('-');
  16499. function getResult(l, c) {
  16500. var ext;
  16501. if (pluralExtensions.currentRule && pluralExtensions.currentRule.lng === lng) {
  16502. ext = pluralExtensions.currentRule.rule;
  16503. } else {
  16504. ext = pluralExtensions.rules[l];
  16505. }
  16506. if (ext) {
  16507. var i;
  16508. if (ext.noAbs) {
  16509. i = ext.plurals(c);
  16510. } else {
  16511. i = ext.plurals(Math.abs(c));
  16512. }
  16513. var number = ext.numbers[i];
  16514. if (ext.numbers.length === 2 && ext.numbers[0] === 1) {
  16515. if (number === 2) {
  16516. number = -1; // regular plural
  16517. } else if (number === 1) {
  16518. number = 1; // singular
  16519. }
  16520. }//console.log(count + '-' + number);
  16521. return number;
  16522. } else {
  16523. return c === 1 ? '1' : '-1';
  16524. }
  16525. }
  16526. return getResult(parts[f.getCountyIndexOfLng(lng)], count);
  16527. }
  16528. };
  16529. var postProcessors = {};
  16530. var addPostProcessor = function(name, fc) {
  16531. postProcessors[name] = fc;
  16532. };
  16533. // sprintf support
  16534. var sprintf = (function() {
  16535. function get_type(variable) {
  16536. return Object.prototype.toString.call(variable).slice(8, -1).toLowerCase();
  16537. }
  16538. function str_repeat(input, multiplier) {
  16539. for (var output = []; multiplier > 0; output[--multiplier] = input) {/* do nothing */}
  16540. return output.join('');
  16541. }
  16542. var str_format = function() {
  16543. if (!str_format.cache.hasOwnProperty(arguments[0])) {
  16544. str_format.cache[arguments[0]] = str_format.parse(arguments[0]);
  16545. }
  16546. return str_format.format.call(null, str_format.cache[arguments[0]], arguments);
  16547. };
  16548. str_format.format = function(parse_tree, argv) {
  16549. var cursor = 1, tree_length = parse_tree.length, node_type = '', arg, output = [], i, k, match, pad, pad_character, pad_length;
  16550. for (i = 0; i < tree_length; i++) {
  16551. node_type = get_type(parse_tree[i]);
  16552. if (node_type === 'string') {
  16553. output.push(parse_tree[i]);
  16554. }
  16555. else if (node_type === 'array') {
  16556. match = parse_tree[i]; // convenience purposes only
  16557. if (match[2]) { // keyword argument
  16558. arg = argv[cursor];
  16559. for (k = 0; k < match[2].length; k++) {
  16560. if (!arg.hasOwnProperty(match[2][k])) {
  16561. throw(sprintf('[sprintf] property "%s" does not exist', match[2][k]));
  16562. }
  16563. arg = arg[match[2][k]];
  16564. }
  16565. }
  16566. else if (match[1]) { // positional argument (explicit)
  16567. arg = argv[match[1]];
  16568. }
  16569. else { // positional argument (implicit)
  16570. arg = argv[cursor++];
  16571. }
  16572. if (/[^s]/.test(match[8]) && (get_type(arg) != 'number')) {
  16573. throw(sprintf('[sprintf] expecting number but found %s', get_type(arg)));
  16574. }
  16575. switch (match[8]) {
  16576. case 'b': arg = arg.toString(2); break;
  16577. case 'c': arg = String.fromCharCode(arg); break;
  16578. case 'd': arg = parseInt(arg, 10); break;
  16579. case 'e': arg = match[7] ? arg.toExponential(match[7]) : arg.toExponential(); break;
  16580. case 'f': arg = match[7] ? parseFloat(arg).toFixed(match[7]) : parseFloat(arg); break;
  16581. case 'o': arg = arg.toString(8); break;
  16582. case 's': arg = ((arg = String(arg)) && match[7] ? arg.substring(0, match[7]) : arg); break;
  16583. case 'u': arg = Math.abs(arg); break;
  16584. case 'x': arg = arg.toString(16); break;
  16585. case 'X': arg = arg.toString(16).toUpperCase(); break;
  16586. }
  16587. arg = (/[def]/.test(match[8]) && match[3] && arg >= 0 ? '+'+ arg : arg);
  16588. pad_character = match[4] ? match[4] == '0' ? '0' : match[4].charAt(1) : ' ';
  16589. pad_length = match[6] - String(arg).length;
  16590. pad = match[6] ? str_repeat(pad_character, pad_length) : '';
  16591. output.push(match[5] ? arg + pad : pad + arg);
  16592. }
  16593. }
  16594. return output.join('');
  16595. };
  16596. str_format.cache = {};
  16597. str_format.parse = function(fmt) {
  16598. var _fmt = fmt, match = [], parse_tree = [], arg_names = 0;
  16599. while (_fmt) {
  16600. if ((match = /^[^\x25]+/.exec(_fmt)) !== null) {
  16601. parse_tree.push(match[0]);
  16602. }
  16603. else if ((match = /^\x25{2}/.exec(_fmt)) !== null) {
  16604. parse_tree.push('%');
  16605. }
  16606. else if ((match = /^\x25(?:([1-9]\d*)\$|\(([^\)]+)\))?(\+)?(0|'[^$])?(-)?(\d+)?(?:\.(\d+))?([b-fosuxX])/.exec(_fmt)) !== null) {
  16607. if (match[2]) {
  16608. arg_names |= 1;
  16609. var field_list = [], replacement_field = match[2], field_match = [];
  16610. if ((field_match = /^([a-z_][a-z_\d]*)/i.exec(replacement_field)) !== null) {
  16611. field_list.push(field_match[1]);
  16612. while ((replacement_field = replacement_field.substring(field_match[0].length)) !== '') {
  16613. if ((field_match = /^\.([a-z_][a-z_\d]*)/i.exec(replacement_field)) !== null) {
  16614. field_list.push(field_match[1]);
  16615. }
  16616. else if ((field_match = /^\[(\d+)\]/.exec(replacement_field)) !== null) {
  16617. field_list.push(field_match[1]);
  16618. }
  16619. else {
  16620. throw('[sprintf] huh?');
  16621. }
  16622. }
  16623. }
  16624. else {
  16625. throw('[sprintf] huh?');
  16626. }
  16627. match[2] = field_list;
  16628. }
  16629. else {
  16630. arg_names |= 2;
  16631. }
  16632. if (arg_names === 3) {
  16633. throw('[sprintf] mixing positional and named placeholders is not (yet) supported');
  16634. }
  16635. parse_tree.push(match);
  16636. }
  16637. else {
  16638. throw('[sprintf] huh?');
  16639. }
  16640. _fmt = _fmt.substring(match[0].length);
  16641. }
  16642. return parse_tree;
  16643. };
  16644. return str_format;
  16645. })();
  16646. var vsprintf = function(fmt, argv) {
  16647. argv.unshift(fmt);
  16648. return sprintf.apply(null, argv);
  16649. };
  16650. addPostProcessor("sprintf", function(val, key, opts) {
  16651. if (!opts.sprintf) return val;
  16652. if (Object.prototype.toString.apply(opts.sprintf) === '[object Array]') {
  16653. return vsprintf(val, opts.sprintf);
  16654. } else if (typeof opts.sprintf === 'object') {
  16655. return sprintf(val, opts.sprintf);
  16656. }
  16657. return val;
  16658. });
  16659. // public api interface
  16660. i18n.init = init;
  16661. i18n.setLng = setLng;
  16662. i18n.preload = preload;
  16663. i18n.addResourceBundle = addResourceBundle;
  16664. i18n.hasResourceBundle = hasResourceBundle;
  16665. i18n.addResource = addResource;
  16666. i18n.addResources = addResources;
  16667. i18n.removeResourceBundle = removeResourceBundle;
  16668. i18n.loadNamespace = loadNamespace;
  16669. i18n.loadNamespaces = loadNamespaces;
  16670. i18n.setDefaultNamespace = setDefaultNamespace;
  16671. i18n.t = translate;
  16672. i18n.translate = translate;
  16673. i18n.exists = exists;
  16674. i18n.detectLanguage = f.detectLanguage;
  16675. i18n.pluralExtensions = pluralExtensions;
  16676. i18n.sync = sync;
  16677. i18n.functions = f;
  16678. i18n.lng = lng;
  16679. i18n.addPostProcessor = addPostProcessor;
  16680. i18n.options = o;
  16681. })();
  16682. },{"jquery":"jquery"}],62:[function(require,module,exports){
  16683. // Top level file is just a mixin of submodules & constants
  16684. 'use strict';
  16685. var assign = require('./lib/utils/common').assign;
  16686. var deflate = require('./lib/deflate');
  16687. var inflate = require('./lib/inflate');
  16688. var constants = require('./lib/zlib/constants');
  16689. var pako = {};
  16690. assign(pako, deflate, inflate, constants);
  16691. module.exports = pako;
  16692. },{"./lib/deflate":63,"./lib/inflate":64,"./lib/utils/common":65,"./lib/zlib/constants":68}],63:[function(require,module,exports){
  16693. 'use strict';
  16694. var zlib_deflate = require('./zlib/deflate.js');
  16695. var utils = require('./utils/common');
  16696. var strings = require('./utils/strings');
  16697. var msg = require('./zlib/messages');
  16698. var zstream = require('./zlib/zstream');
  16699. /* Public constants ==========================================================*/
  16700. /* ===========================================================================*/
  16701. var Z_NO_FLUSH = 0;
  16702. var Z_FINISH = 4;
  16703. var Z_OK = 0;
  16704. var Z_STREAM_END = 1;
  16705. var Z_DEFAULT_COMPRESSION = -1;
  16706. var Z_DEFAULT_STRATEGY = 0;
  16707. var Z_DEFLATED = 8;
  16708. /* ===========================================================================*/
  16709. /**
  16710. * class Deflate
  16711. *
  16712. * Generic JS-style wrapper for zlib calls. If you don't need
  16713. * streaming behaviour - use more simple functions: [[deflate]],
  16714. * [[deflateRaw]] and [[gzip]].
  16715. **/
  16716. /* internal
  16717. * Deflate.chunks -> Array
  16718. *
  16719. * Chunks of output data, if [[Deflate#onData]] not overriden.
  16720. **/
  16721. /**
  16722. * Deflate.result -> Uint8Array|Array
  16723. *
  16724. * Compressed result, generated by default [[Deflate#onData]]
  16725. * and [[Deflate#onEnd]] handlers. Filled after you push last chunk
  16726. * (call [[Deflate#push]] with `Z_FINISH` / `true` param).
  16727. **/
  16728. /**
  16729. * Deflate.err -> Number
  16730. *
  16731. * Error code after deflate finished. 0 (Z_OK) on success.
  16732. * You will not need it in real life, because deflate errors
  16733. * are possible only on wrong options or bad `onData` / `onEnd`
  16734. * custom handlers.
  16735. **/
  16736. /**
  16737. * Deflate.msg -> String
  16738. *
  16739. * Error message, if [[Deflate.err]] != 0
  16740. **/
  16741. /**
  16742. * new Deflate(options)
  16743. * - options (Object): zlib deflate options.
  16744. *
  16745. * Creates new deflator instance with specified params. Throws exception
  16746. * on bad params. Supported options:
  16747. *
  16748. * - `level`
  16749. * - `windowBits`
  16750. * - `memLevel`
  16751. * - `strategy`
  16752. *
  16753. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  16754. * for more information on these.
  16755. *
  16756. * Additional options, for internal needs:
  16757. *
  16758. * - `chunkSize` - size of generated data chunks (16K by default)
  16759. * - `raw` (Boolean) - do raw deflate
  16760. * - `gzip` (Boolean) - create gzip wrapper
  16761. * - `to` (String) - if equal to 'string', then result will be "binary string"
  16762. * (each char code [0..255])
  16763. * - `header` (Object) - custom header for gzip
  16764. * - `text` (Boolean) - true if compressed data believed to be text
  16765. * - `time` (Number) - modification time, unix timestamp
  16766. * - `os` (Number) - operation system code
  16767. * - `extra` (Array) - array of bytes with extra data (max 65536)
  16768. * - `name` (String) - file name (binary string)
  16769. * - `comment` (String) - comment (binary string)
  16770. * - `hcrc` (Boolean) - true if header crc should be added
  16771. *
  16772. * ##### Example:
  16773. *
  16774. * ```javascript
  16775. * var pako = require('pako')
  16776. * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
  16777. * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
  16778. *
  16779. * var deflate = new pako.Deflate({ level: 3});
  16780. *
  16781. * deflate.push(chunk1, false);
  16782. * deflate.push(chunk2, true); // true -> last chunk
  16783. *
  16784. * if (deflate.err) { throw new Error(deflate.err); }
  16785. *
  16786. * console.log(deflate.result);
  16787. * ```
  16788. **/
  16789. var Deflate = function(options) {
  16790. this.options = utils.assign({
  16791. level: Z_DEFAULT_COMPRESSION,
  16792. method: Z_DEFLATED,
  16793. chunkSize: 16384,
  16794. windowBits: 15,
  16795. memLevel: 8,
  16796. strategy: Z_DEFAULT_STRATEGY,
  16797. to: ''
  16798. }, options || {});
  16799. var opt = this.options;
  16800. if (opt.raw && (opt.windowBits > 0)) {
  16801. opt.windowBits = -opt.windowBits;
  16802. }
  16803. else if (opt.gzip && (opt.windowBits > 0) && (opt.windowBits < 16)) {
  16804. opt.windowBits += 16;
  16805. }
  16806. this.err = 0; // error code, if happens (0 = Z_OK)
  16807. this.msg = ''; // error message
  16808. this.ended = false; // used to avoid multiple onEnd() calls
  16809. this.chunks = []; // chunks of compressed data
  16810. this.strm = new zstream();
  16811. this.strm.avail_out = 0;
  16812. var status = zlib_deflate.deflateInit2(
  16813. this.strm,
  16814. opt.level,
  16815. opt.method,
  16816. opt.windowBits,
  16817. opt.memLevel,
  16818. opt.strategy
  16819. );
  16820. if (status !== Z_OK) {
  16821. throw new Error(msg[status]);
  16822. }
  16823. if (opt.header) {
  16824. zlib_deflate.deflateSetHeader(this.strm, opt.header);
  16825. }
  16826. };
  16827. /**
  16828. * Deflate#push(data[, mode]) -> Boolean
  16829. * - data (Uint8Array|Array|String): input data. Strings will be converted to
  16830. * utf8 byte sequence.
  16831. * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
  16832. * See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH.
  16833. *
  16834. * Sends input data to deflate pipe, generating [[Deflate#onData]] calls with
  16835. * new compressed chunks. Returns `true` on success. The last data block must have
  16836. * mode Z_FINISH (or `true`). That flush internal pending buffers and call
  16837. * [[Deflate#onEnd]].
  16838. *
  16839. * On fail call [[Deflate#onEnd]] with error code and return false.
  16840. *
  16841. * We strongly recommend to use `Uint8Array` on input for best speed (output
  16842. * array format is detected automatically). Also, don't skip last param and always
  16843. * use the same type in your code (boolean or number). That will improve JS speed.
  16844. *
  16845. * For regular `Array`-s make sure all elements are [0..255].
  16846. *
  16847. * ##### Example
  16848. *
  16849. * ```javascript
  16850. * push(chunk, false); // push one of data chunks
  16851. * ...
  16852. * push(chunk, true); // push last chunk
  16853. * ```
  16854. **/
  16855. Deflate.prototype.push = function(data, mode) {
  16856. var strm = this.strm;
  16857. var chunkSize = this.options.chunkSize;
  16858. var status, _mode;
  16859. if (this.ended) { return false; }
  16860. _mode = (mode === ~~mode) ? mode : ((mode === true) ? Z_FINISH : Z_NO_FLUSH);
  16861. // Convert data if needed
  16862. if (typeof data === 'string') {
  16863. // If we need to compress text, change encoding to utf8.
  16864. strm.input = strings.string2buf(data);
  16865. } else {
  16866. strm.input = data;
  16867. }
  16868. strm.next_in = 0;
  16869. strm.avail_in = strm.input.length;
  16870. do {
  16871. if (strm.avail_out === 0) {
  16872. strm.output = new utils.Buf8(chunkSize);
  16873. strm.next_out = 0;
  16874. strm.avail_out = chunkSize;
  16875. }
  16876. status = zlib_deflate.deflate(strm, _mode); /* no bad return value */
  16877. if (status !== Z_STREAM_END && status !== Z_OK) {
  16878. this.onEnd(status);
  16879. this.ended = true;
  16880. return false;
  16881. }
  16882. if (strm.avail_out === 0 || (strm.avail_in === 0 && _mode === Z_FINISH)) {
  16883. if (this.options.to === 'string') {
  16884. this.onData(strings.buf2binstring(utils.shrinkBuf(strm.output, strm.next_out)));
  16885. } else {
  16886. this.onData(utils.shrinkBuf(strm.output, strm.next_out));
  16887. }
  16888. }
  16889. } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== Z_STREAM_END);
  16890. // Finalize on the last chunk.
  16891. if (_mode === Z_FINISH) {
  16892. status = zlib_deflate.deflateEnd(this.strm);
  16893. this.onEnd(status);
  16894. this.ended = true;
  16895. return status === Z_OK;
  16896. }
  16897. return true;
  16898. };
  16899. /**
  16900. * Deflate#onData(chunk) -> Void
  16901. * - chunk (Uint8Array|Array|String): ouput data. Type of array depends
  16902. * on js engine support. When string output requested, each chunk
  16903. * will be string.
  16904. *
  16905. * By default, stores data blocks in `chunks[]` property and glue
  16906. * those in `onEnd`. Override this handler, if you need another behaviour.
  16907. **/
  16908. Deflate.prototype.onData = function(chunk) {
  16909. this.chunks.push(chunk);
  16910. };
  16911. /**
  16912. * Deflate#onEnd(status) -> Void
  16913. * - status (Number): deflate status. 0 (Z_OK) on success,
  16914. * other if not.
  16915. *
  16916. * Called once after you tell deflate that input stream complete
  16917. * or error happenned. By default - join collected chunks,
  16918. * free memory and fill `results` / `err` properties.
  16919. **/
  16920. Deflate.prototype.onEnd = function(status) {
  16921. // On success - join
  16922. if (status === Z_OK) {
  16923. if (this.options.to === 'string') {
  16924. this.result = this.chunks.join('');
  16925. } else {
  16926. this.result = utils.flattenChunks(this.chunks);
  16927. }
  16928. }
  16929. this.chunks = [];
  16930. this.err = status;
  16931. this.msg = this.strm.msg;
  16932. };
  16933. /**
  16934. * deflate(data[, options]) -> Uint8Array|Array|String
  16935. * - data (Uint8Array|Array|String): input data to compress.
  16936. * - options (Object): zlib deflate options.
  16937. *
  16938. * Compress `data` with deflate alrorythm and `options`.
  16939. *
  16940. * Supported options are:
  16941. *
  16942. * - level
  16943. * - windowBits
  16944. * - memLevel
  16945. * - strategy
  16946. *
  16947. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  16948. * for more information on these.
  16949. *
  16950. * Sugar (options):
  16951. *
  16952. * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
  16953. * negative windowBits implicitly.
  16954. * - `to` (String) - if equal to 'string', then result will be "binary string"
  16955. * (each char code [0..255])
  16956. *
  16957. * ##### Example:
  16958. *
  16959. * ```javascript
  16960. * var pako = require('pako')
  16961. * , data = Uint8Array([1,2,3,4,5,6,7,8,9]);
  16962. *
  16963. * console.log(pako.deflate(data));
  16964. * ```
  16965. **/
  16966. function deflate(input, options) {
  16967. var deflator = new Deflate(options);
  16968. deflator.push(input, true);
  16969. // That will never happens, if you don't cheat with options :)
  16970. if (deflator.err) { throw deflator.msg; }
  16971. return deflator.result;
  16972. }
  16973. /**
  16974. * deflateRaw(data[, options]) -> Uint8Array|Array|String
  16975. * - data (Uint8Array|Array|String): input data to compress.
  16976. * - options (Object): zlib deflate options.
  16977. *
  16978. * The same as [[deflate]], but creates raw data, without wrapper
  16979. * (header and adler32 crc).
  16980. **/
  16981. function deflateRaw(input, options) {
  16982. options = options || {};
  16983. options.raw = true;
  16984. return deflate(input, options);
  16985. }
  16986. /**
  16987. * gzip(data[, options]) -> Uint8Array|Array|String
  16988. * - data (Uint8Array|Array|String): input data to compress.
  16989. * - options (Object): zlib deflate options.
  16990. *
  16991. * The same as [[deflate]], but create gzip wrapper instead of
  16992. * deflate one.
  16993. **/
  16994. function gzip(input, options) {
  16995. options = options || {};
  16996. options.gzip = true;
  16997. return deflate(input, options);
  16998. }
  16999. exports.Deflate = Deflate;
  17000. exports.deflate = deflate;
  17001. exports.deflateRaw = deflateRaw;
  17002. exports.gzip = gzip;
  17003. },{"./utils/common":65,"./utils/strings":66,"./zlib/deflate.js":70,"./zlib/messages":75,"./zlib/zstream":77}],64:[function(require,module,exports){
  17004. 'use strict';
  17005. var zlib_inflate = require('./zlib/inflate.js');
  17006. var utils = require('./utils/common');
  17007. var strings = require('./utils/strings');
  17008. var c = require('./zlib/constants');
  17009. var msg = require('./zlib/messages');
  17010. var zstream = require('./zlib/zstream');
  17011. var gzheader = require('./zlib/gzheader');
  17012. /**
  17013. * class Inflate
  17014. *
  17015. * Generic JS-style wrapper for zlib calls. If you don't need
  17016. * streaming behaviour - use more simple functions: [[inflate]]
  17017. * and [[inflateRaw]].
  17018. **/
  17019. /* internal
  17020. * inflate.chunks -> Array
  17021. *
  17022. * Chunks of output data, if [[Inflate#onData]] not overriden.
  17023. **/
  17024. /**
  17025. * Inflate.result -> Uint8Array|Array|String
  17026. *
  17027. * Uncompressed result, generated by default [[Inflate#onData]]
  17028. * and [[Inflate#onEnd]] handlers. Filled after you push last chunk
  17029. * (call [[Inflate#push]] with `Z_FINISH` / `true` param).
  17030. **/
  17031. /**
  17032. * Inflate.err -> Number
  17033. *
  17034. * Error code after inflate finished. 0 (Z_OK) on success.
  17035. * Should be checked if broken data possible.
  17036. **/
  17037. /**
  17038. * Inflate.msg -> String
  17039. *
  17040. * Error message, if [[Inflate.err]] != 0
  17041. **/
  17042. /**
  17043. * new Inflate(options)
  17044. * - options (Object): zlib inflate options.
  17045. *
  17046. * Creates new inflator instance with specified params. Throws exception
  17047. * on bad params. Supported options:
  17048. *
  17049. * - `windowBits`
  17050. *
  17051. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  17052. * for more information on these.
  17053. *
  17054. * Additional options, for internal needs:
  17055. *
  17056. * - `chunkSize` - size of generated data chunks (16K by default)
  17057. * - `raw` (Boolean) - do raw inflate
  17058. * - `to` (String) - if equal to 'string', then result will be converted
  17059. * from utf8 to utf16 (javascript) string. When string output requested,
  17060. * chunk length can differ from `chunkSize`, depending on content.
  17061. *
  17062. * By default, when no options set, autodetect deflate/gzip data format via
  17063. * wrapper header.
  17064. *
  17065. * ##### Example:
  17066. *
  17067. * ```javascript
  17068. * var pako = require('pako')
  17069. * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
  17070. * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
  17071. *
  17072. * var inflate = new pako.Inflate({ level: 3});
  17073. *
  17074. * inflate.push(chunk1, false);
  17075. * inflate.push(chunk2, true); // true -> last chunk
  17076. *
  17077. * if (inflate.err) { throw new Error(inflate.err); }
  17078. *
  17079. * console.log(inflate.result);
  17080. * ```
  17081. **/
  17082. var Inflate = function(options) {
  17083. this.options = utils.assign({
  17084. chunkSize: 16384,
  17085. windowBits: 0,
  17086. to: ''
  17087. }, options || {});
  17088. var opt = this.options;
  17089. // Force window size for `raw` data, if not set directly,
  17090. // because we have no header for autodetect.
  17091. if (opt.raw && (opt.windowBits >= 0) && (opt.windowBits < 16)) {
  17092. opt.windowBits = -opt.windowBits;
  17093. if (opt.windowBits === 0) { opt.windowBits = -15; }
  17094. }
  17095. // If `windowBits` not defined (and mode not raw) - set autodetect flag for gzip/deflate
  17096. if ((opt.windowBits >= 0) && (opt.windowBits < 16) &&
  17097. !(options && options.windowBits)) {
  17098. opt.windowBits += 32;
  17099. }
  17100. // Gzip header has no info about windows size, we can do autodetect only
  17101. // for deflate. So, if window size not set, force it to max when gzip possible
  17102. if ((opt.windowBits > 15) && (opt.windowBits < 48)) {
  17103. // bit 3 (16) -> gzipped data
  17104. // bit 4 (32) -> autodetect gzip/deflate
  17105. if ((opt.windowBits & 15) === 0) {
  17106. opt.windowBits |= 15;
  17107. }
  17108. }
  17109. this.err = 0; // error code, if happens (0 = Z_OK)
  17110. this.msg = ''; // error message
  17111. this.ended = false; // used to avoid multiple onEnd() calls
  17112. this.chunks = []; // chunks of compressed data
  17113. this.strm = new zstream();
  17114. this.strm.avail_out = 0;
  17115. var status = zlib_inflate.inflateInit2(
  17116. this.strm,
  17117. opt.windowBits
  17118. );
  17119. if (status !== c.Z_OK) {
  17120. throw new Error(msg[status]);
  17121. }
  17122. this.header = new gzheader();
  17123. zlib_inflate.inflateGetHeader(this.strm, this.header);
  17124. };
  17125. /**
  17126. * Inflate#push(data[, mode]) -> Boolean
  17127. * - data (Uint8Array|Array|String): input data
  17128. * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
  17129. * See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH.
  17130. *
  17131. * Sends input data to inflate pipe, generating [[Inflate#onData]] calls with
  17132. * new output chunks. Returns `true` on success. The last data block must have
  17133. * mode Z_FINISH (or `true`). That flush internal pending buffers and call
  17134. * [[Inflate#onEnd]].
  17135. *
  17136. * On fail call [[Inflate#onEnd]] with error code and return false.
  17137. *
  17138. * We strongly recommend to use `Uint8Array` on input for best speed (output
  17139. * format is detected automatically). Also, don't skip last param and always
  17140. * use the same type in your code (boolean or number). That will improve JS speed.
  17141. *
  17142. * For regular `Array`-s make sure all elements are [0..255].
  17143. *
  17144. * ##### Example
  17145. *
  17146. * ```javascript
  17147. * push(chunk, false); // push one of data chunks
  17148. * ...
  17149. * push(chunk, true); // push last chunk
  17150. * ```
  17151. **/
  17152. Inflate.prototype.push = function(data, mode) {
  17153. var strm = this.strm;
  17154. var chunkSize = this.options.chunkSize;
  17155. var status, _mode;
  17156. var next_out_utf8, tail, utf8str;
  17157. if (this.ended) { return false; }
  17158. _mode = (mode === ~~mode) ? mode : ((mode === true) ? c.Z_FINISH : c.Z_NO_FLUSH);
  17159. // Convert data if needed
  17160. if (typeof data === 'string') {
  17161. // Only binary strings can be decompressed on practice
  17162. strm.input = strings.binstring2buf(data);
  17163. } else {
  17164. strm.input = data;
  17165. }
  17166. strm.next_in = 0;
  17167. strm.avail_in = strm.input.length;
  17168. do {
  17169. if (strm.avail_out === 0) {
  17170. strm.output = new utils.Buf8(chunkSize);
  17171. strm.next_out = 0;
  17172. strm.avail_out = chunkSize;
  17173. }
  17174. status = zlib_inflate.inflate(strm, c.Z_NO_FLUSH); /* no bad return value */
  17175. if (status !== c.Z_STREAM_END && status !== c.Z_OK) {
  17176. this.onEnd(status);
  17177. this.ended = true;
  17178. return false;
  17179. }
  17180. if (strm.next_out) {
  17181. if (strm.avail_out === 0 || status === c.Z_STREAM_END || (strm.avail_in === 0 && _mode === c.Z_FINISH)) {
  17182. if (this.options.to === 'string') {
  17183. next_out_utf8 = strings.utf8border(strm.output, strm.next_out);
  17184. tail = strm.next_out - next_out_utf8;
  17185. utf8str = strings.buf2string(strm.output, next_out_utf8);
  17186. // move tail
  17187. strm.next_out = tail;
  17188. strm.avail_out = chunkSize - tail;
  17189. if (tail) { utils.arraySet(strm.output, strm.output, next_out_utf8, tail, 0); }
  17190. this.onData(utf8str);
  17191. } else {
  17192. this.onData(utils.shrinkBuf(strm.output, strm.next_out));
  17193. }
  17194. }
  17195. }
  17196. } while ((strm.avail_in > 0) && status !== c.Z_STREAM_END);
  17197. if (status === c.Z_STREAM_END) {
  17198. _mode = c.Z_FINISH;
  17199. }
  17200. // Finalize on the last chunk.
  17201. if (_mode === c.Z_FINISH) {
  17202. status = zlib_inflate.inflateEnd(this.strm);
  17203. this.onEnd(status);
  17204. this.ended = true;
  17205. return status === c.Z_OK;
  17206. }
  17207. return true;
  17208. };
  17209. /**
  17210. * Inflate#onData(chunk) -> Void
  17211. * - chunk (Uint8Array|Array|String): ouput data. Type of array depends
  17212. * on js engine support. When string output requested, each chunk
  17213. * will be string.
  17214. *
  17215. * By default, stores data blocks in `chunks[]` property and glue
  17216. * those in `onEnd`. Override this handler, if you need another behaviour.
  17217. **/
  17218. Inflate.prototype.onData = function(chunk) {
  17219. this.chunks.push(chunk);
  17220. };
  17221. /**
  17222. * Inflate#onEnd(status) -> Void
  17223. * - status (Number): inflate status. 0 (Z_OK) on success,
  17224. * other if not.
  17225. *
  17226. * Called once after you tell inflate that input stream complete
  17227. * or error happenned. By default - join collected chunks,
  17228. * free memory and fill `results` / `err` properties.
  17229. **/
  17230. Inflate.prototype.onEnd = function(status) {
  17231. // On success - join
  17232. if (status === c.Z_OK) {
  17233. if (this.options.to === 'string') {
  17234. // Glue & convert here, until we teach pako to send
  17235. // utf8 alligned strings to onData
  17236. this.result = this.chunks.join('');
  17237. } else {
  17238. this.result = utils.flattenChunks(this.chunks);
  17239. }
  17240. }
  17241. this.chunks = [];
  17242. this.err = status;
  17243. this.msg = this.strm.msg;
  17244. };
  17245. /**
  17246. * inflate(data[, options]) -> Uint8Array|Array|String
  17247. * - data (Uint8Array|Array|String): input data to decompress.
  17248. * - options (Object): zlib inflate options.
  17249. *
  17250. * Decompress `data` with inflate/ungzip and `options`. Autodetect
  17251. * format via wrapper header by default. That's why we don't provide
  17252. * separate `ungzip` method.
  17253. *
  17254. * Supported options are:
  17255. *
  17256. * - windowBits
  17257. *
  17258. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  17259. * for more information.
  17260. *
  17261. * Sugar (options):
  17262. *
  17263. * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
  17264. * negative windowBits implicitly.
  17265. * - `to` (String) - if equal to 'string', then result will be converted
  17266. * from utf8 to utf16 (javascript) string. When string output requested,
  17267. * chunk length can differ from `chunkSize`, depending on content.
  17268. *
  17269. *
  17270. * ##### Example:
  17271. *
  17272. * ```javascript
  17273. * var pako = require('pako')
  17274. * , input = pako.deflate([1,2,3,4,5,6,7,8,9])
  17275. * , output;
  17276. *
  17277. * try {
  17278. * output = pako.inflate(input);
  17279. * } catch (err)
  17280. * console.log(err);
  17281. * }
  17282. * ```
  17283. **/
  17284. function inflate(input, options) {
  17285. var inflator = new Inflate(options);
  17286. inflator.push(input, true);
  17287. // That will never happens, if you don't cheat with options :)
  17288. if (inflator.err) { throw inflator.msg; }
  17289. return inflator.result;
  17290. }
  17291. /**
  17292. * inflateRaw(data[, options]) -> Uint8Array|Array|String
  17293. * - data (Uint8Array|Array|String): input data to decompress.
  17294. * - options (Object): zlib inflate options.
  17295. *
  17296. * The same as [[inflate]], but creates raw data, without wrapper
  17297. * (header and adler32 crc).
  17298. **/
  17299. function inflateRaw(input, options) {
  17300. options = options || {};
  17301. options.raw = true;
  17302. return inflate(input, options);
  17303. }
  17304. /**
  17305. * ungzip(data[, options]) -> Uint8Array|Array|String
  17306. * - data (Uint8Array|Array|String): input data to decompress.
  17307. * - options (Object): zlib inflate options.
  17308. *
  17309. * Just shortcut to [[inflate]], because it autodetects format
  17310. * by header.content. Done for convenience.
  17311. **/
  17312. exports.Inflate = Inflate;
  17313. exports.inflate = inflate;
  17314. exports.inflateRaw = inflateRaw;
  17315. exports.ungzip = inflate;
  17316. },{"./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){
  17317. 'use strict';
  17318. var TYPED_OK = (typeof Uint8Array !== 'undefined') &&
  17319. (typeof Uint16Array !== 'undefined') &&
  17320. (typeof Int32Array !== 'undefined');
  17321. exports.assign = function (obj /*from1, from2, from3, ...*/) {
  17322. var sources = Array.prototype.slice.call(arguments, 1);
  17323. while (sources.length) {
  17324. var source = sources.shift();
  17325. if (!source) { continue; }
  17326. if (typeof(source) !== 'object') {
  17327. throw new TypeError(source + 'must be non-object');
  17328. }
  17329. for (var p in source) {
  17330. if (source.hasOwnProperty(p)) {
  17331. obj[p] = source[p];
  17332. }
  17333. }
  17334. }
  17335. return obj;
  17336. };
  17337. // reduce buffer size, avoiding mem copy
  17338. exports.shrinkBuf = function (buf, size) {
  17339. if (buf.length === size) { return buf; }
  17340. if (buf.subarray) { return buf.subarray(0, size); }
  17341. buf.length = size;
  17342. return buf;
  17343. };
  17344. var fnTyped = {
  17345. arraySet: function (dest, src, src_offs, len, dest_offs) {
  17346. if (src.subarray && dest.subarray) {
  17347. dest.set(src.subarray(src_offs, src_offs+len), dest_offs);
  17348. return;
  17349. }
  17350. // Fallback to ordinary array
  17351. for(var i=0; i<len; i++) {
  17352. dest[dest_offs + i] = src[src_offs + i];
  17353. }
  17354. },
  17355. // Join array of chunks to single array.
  17356. flattenChunks: function(chunks) {
  17357. var i, l, len, pos, chunk, result;
  17358. // calculate data length
  17359. len = 0;
  17360. for (i=0, l=chunks.length; i<l; i++) {
  17361. len += chunks[i].length;
  17362. }
  17363. // join chunks
  17364. result = new Uint8Array(len);
  17365. pos = 0;
  17366. for (i=0, l=chunks.length; i<l; i++) {
  17367. chunk = chunks[i];
  17368. result.set(chunk, pos);
  17369. pos += chunk.length;
  17370. }
  17371. return result;
  17372. }
  17373. };
  17374. var fnUntyped = {
  17375. arraySet: function (dest, src, src_offs, len, dest_offs) {
  17376. for(var i=0; i<len; i++) {
  17377. dest[dest_offs + i] = src[src_offs + i];
  17378. }
  17379. },
  17380. // Join array of chunks to single array.
  17381. flattenChunks: function(chunks) {
  17382. return [].concat.apply([], chunks);
  17383. }
  17384. };
  17385. // Enable/Disable typed arrays use, for testing
  17386. //
  17387. exports.setTyped = function (on) {
  17388. if (on) {
  17389. exports.Buf8 = Uint8Array;
  17390. exports.Buf16 = Uint16Array;
  17391. exports.Buf32 = Int32Array;
  17392. exports.assign(exports, fnTyped);
  17393. } else {
  17394. exports.Buf8 = Array;
  17395. exports.Buf16 = Array;
  17396. exports.Buf32 = Array;
  17397. exports.assign(exports, fnUntyped);
  17398. }
  17399. };
  17400. exports.setTyped(TYPED_OK);
  17401. },{}],66:[function(require,module,exports){
  17402. // String encode/decode helpers
  17403. 'use strict';
  17404. var utils = require('./common');
  17405. // Quick check if we can use fast array to bin string conversion
  17406. //
  17407. // - apply(Array) can fail on Android 2.2
  17408. // - apply(Uint8Array) can fail on iOS 5.1 Safary
  17409. //
  17410. var STR_APPLY_OK = true;
  17411. var STR_APPLY_UIA_OK = true;
  17412. try { String.fromCharCode.apply(null, [0]); } catch(__) { STR_APPLY_OK = false; }
  17413. try { String.fromCharCode.apply(null, new Uint8Array(1)); } catch(__) { STR_APPLY_UIA_OK = false; }
  17414. // Table with utf8 lengths (calculated by first byte of sequence)
  17415. // Note, that 5 & 6-byte values and some 4-byte values can not be represented in JS,
  17416. // because max possible codepoint is 0x10ffff
  17417. var _utf8len = new utils.Buf8(256);
  17418. for (var i=0; i<256; i++) {
  17419. _utf8len[i] = (i >= 252 ? 6 : i >= 248 ? 5 : i >= 240 ? 4 : i >= 224 ? 3 : i >= 192 ? 2 : 1);
  17420. }
  17421. _utf8len[254]=_utf8len[254]=1; // Invalid sequence start
  17422. // convert string to array (typed, when possible)
  17423. exports.string2buf = function (str) {
  17424. var buf, c, c2, m_pos, i, str_len = str.length, buf_len = 0;
  17425. // count binary size
  17426. for (m_pos = 0; m_pos < str_len; m_pos++) {
  17427. c = str.charCodeAt(m_pos);
  17428. if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) {
  17429. c2 = str.charCodeAt(m_pos+1);
  17430. if ((c2 & 0xfc00) === 0xdc00) {
  17431. c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
  17432. m_pos++;
  17433. }
  17434. }
  17435. buf_len += c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4;
  17436. }
  17437. // allocate buffer
  17438. buf = new utils.Buf8(buf_len);
  17439. // convert
  17440. for (i=0, m_pos = 0; i < buf_len; m_pos++) {
  17441. c = str.charCodeAt(m_pos);
  17442. if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) {
  17443. c2 = str.charCodeAt(m_pos+1);
  17444. if ((c2 & 0xfc00) === 0xdc00) {
  17445. c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
  17446. m_pos++;
  17447. }
  17448. }
  17449. if (c < 0x80) {
  17450. /* one byte */
  17451. buf[i++] = c;
  17452. } else if (c < 0x800) {
  17453. /* two bytes */
  17454. buf[i++] = 0xC0 | (c >>> 6);
  17455. buf[i++] = 0x80 | (c & 0x3f);
  17456. } else if (c < 0x10000) {
  17457. /* three bytes */
  17458. buf[i++] = 0xE0 | (c >>> 12);
  17459. buf[i++] = 0x80 | (c >>> 6 & 0x3f);
  17460. buf[i++] = 0x80 | (c & 0x3f);
  17461. } else {
  17462. /* four bytes */
  17463. buf[i++] = 0xf0 | (c >>> 18);
  17464. buf[i++] = 0x80 | (c >>> 12 & 0x3f);
  17465. buf[i++] = 0x80 | (c >>> 6 & 0x3f);
  17466. buf[i++] = 0x80 | (c & 0x3f);
  17467. }
  17468. }
  17469. return buf;
  17470. };
  17471. // Helper (used in 2 places)
  17472. function buf2binstring(buf, len) {
  17473. // use fallback for big arrays to avoid stack overflow
  17474. if (len < 65537) {
  17475. if ((buf.subarray && STR_APPLY_UIA_OK) || (!buf.subarray && STR_APPLY_OK)) {
  17476. return String.fromCharCode.apply(null, utils.shrinkBuf(buf, len));
  17477. }
  17478. }
  17479. var result = '';
  17480. for(var i=0; i < len; i++) {
  17481. result += String.fromCharCode(buf[i]);
  17482. }
  17483. return result;
  17484. }
  17485. // Convert byte array to binary string
  17486. exports.buf2binstring = function(buf) {
  17487. return buf2binstring(buf, buf.length);
  17488. };
  17489. // Convert binary string (typed, when possible)
  17490. exports.binstring2buf = function(str) {
  17491. var buf = new utils.Buf8(str.length);
  17492. for(var i=0, len=buf.length; i < len; i++) {
  17493. buf[i] = str.charCodeAt(i);
  17494. }
  17495. return buf;
  17496. };
  17497. // convert array to string
  17498. exports.buf2string = function (buf, max) {
  17499. var i, out, c, c_len;
  17500. var len = max || buf.length;
  17501. // Reserve max possible length (2 words per char)
  17502. // NB: by unknown reasons, Array is significantly faster for
  17503. // String.fromCharCode.apply than Uint16Array.
  17504. var utf16buf = new Array(len*2);
  17505. for (out=0, i=0; i<len;) {
  17506. c = buf[i++];
  17507. // quick process ascii
  17508. if (c < 0x80) { utf16buf[out++] = c; continue; }
  17509. c_len = _utf8len[c];
  17510. // skip 5 & 6 byte codes
  17511. if (c_len > 4) { utf16buf[out++] = 0xfffd; i += c_len-1; continue; }
  17512. // apply mask on first byte
  17513. c &= c_len === 2 ? 0x1f : c_len === 3 ? 0x0f : 0x07;
  17514. // join the rest
  17515. while (c_len > 1 && i < len) {
  17516. c = (c << 6) | (buf[i++] & 0x3f);
  17517. c_len--;
  17518. }
  17519. // terminated by end of string?
  17520. if (c_len > 1) { utf16buf[out++] = 0xfffd; continue; }
  17521. if (c < 0x10000) {
  17522. utf16buf[out++] = c;
  17523. } else {
  17524. c -= 0x10000;
  17525. utf16buf[out++] = 0xd800 | ((c >> 10) & 0x3ff);
  17526. utf16buf[out++] = 0xdc00 | (c & 0x3ff);
  17527. }
  17528. }
  17529. return buf2binstring(utf16buf, out);
  17530. };
  17531. // Calculate max possible position in utf8 buffer,
  17532. // that will not break sequence. If that's not possible
  17533. // - (very small limits) return max size as is.
  17534. //
  17535. // buf[] - utf8 bytes array
  17536. // max - length limit (mandatory);
  17537. exports.utf8border = function(buf, max) {
  17538. var pos;
  17539. max = max || buf.length;
  17540. if (max > buf.length) { max = buf.length; }
  17541. // go back from last position, until start of sequence found
  17542. pos = max-1;
  17543. while (pos >= 0 && (buf[pos] & 0xC0) === 0x80) { pos--; }
  17544. // Fuckup - very small and broken sequence,
  17545. // return max, because we should return something anyway.
  17546. if (pos < 0) { return max; }
  17547. // If we came to start of buffer - that means vuffer is too small,
  17548. // return max too.
  17549. if (pos === 0) { return max; }
  17550. return (pos + _utf8len[buf[pos]] > max) ? pos : max;
  17551. };
  17552. },{"./common":65}],67:[function(require,module,exports){
  17553. 'use strict';
  17554. // Note: adler32 takes 12% for level 0 and 2% for level 6.
  17555. // It doesn't worth to make additional optimizationa as in original.
  17556. // Small size is preferable.
  17557. function adler32(adler, buf, len, pos) {
  17558. var s1 = (adler & 0xffff) |0
  17559. , s2 = ((adler >>> 16) & 0xffff) |0
  17560. , n = 0;
  17561. while (len !== 0) {
  17562. // Set limit ~ twice less than 5552, to keep
  17563. // s2 in 31-bits, because we force signed ints.
  17564. // in other case %= will fail.
  17565. n = len > 2000 ? 2000 : len;
  17566. len -= n;
  17567. do {
  17568. s1 = (s1 + buf[pos++]) |0;
  17569. s2 = (s2 + s1) |0;
  17570. } while (--n);
  17571. s1 %= 65521;
  17572. s2 %= 65521;
  17573. }
  17574. return (s1 | (s2 << 16)) |0;
  17575. }
  17576. module.exports = adler32;
  17577. },{}],68:[function(require,module,exports){
  17578. module.exports = {
  17579. /* Allowed flush values; see deflate() and inflate() below for details */
  17580. Z_NO_FLUSH: 0,
  17581. Z_PARTIAL_FLUSH: 1,
  17582. Z_SYNC_FLUSH: 2,
  17583. Z_FULL_FLUSH: 3,
  17584. Z_FINISH: 4,
  17585. Z_BLOCK: 5,
  17586. Z_TREES: 6,
  17587. /* Return codes for the compression/decompression functions. Negative values
  17588. * are errors, positive values are used for special but normal events.
  17589. */
  17590. Z_OK: 0,
  17591. Z_STREAM_END: 1,
  17592. Z_NEED_DICT: 2,
  17593. Z_ERRNO: -1,
  17594. Z_STREAM_ERROR: -2,
  17595. Z_DATA_ERROR: -3,
  17596. //Z_MEM_ERROR: -4,
  17597. Z_BUF_ERROR: -5,
  17598. //Z_VERSION_ERROR: -6,
  17599. /* compression levels */
  17600. Z_NO_COMPRESSION: 0,
  17601. Z_BEST_SPEED: 1,
  17602. Z_BEST_COMPRESSION: 9,
  17603. Z_DEFAULT_COMPRESSION: -1,
  17604. Z_FILTERED: 1,
  17605. Z_HUFFMAN_ONLY: 2,
  17606. Z_RLE: 3,
  17607. Z_FIXED: 4,
  17608. Z_DEFAULT_STRATEGY: 0,
  17609. /* Possible values of the data_type field (though see inflate()) */
  17610. Z_BINARY: 0,
  17611. Z_TEXT: 1,
  17612. //Z_ASCII: 1, // = Z_TEXT (deprecated)
  17613. Z_UNKNOWN: 2,
  17614. /* The deflate compression method */
  17615. Z_DEFLATED: 8
  17616. //Z_NULL: null // Use -1 or null inline, depending on var type
  17617. };
  17618. },{}],69:[function(require,module,exports){
  17619. 'use strict';
  17620. // Note: we can't get significant speed boost here.
  17621. // So write code to minimize size - no pregenerated tables
  17622. // and array tools dependencies.
  17623. // Use ordinary array, since untyped makes no boost here
  17624. function makeTable() {
  17625. var c, table = [];
  17626. for(var n =0; n < 256; n++){
  17627. c = n;
  17628. for(var k =0; k < 8; k++){
  17629. c = ((c&1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1));
  17630. }
  17631. table[n] = c;
  17632. }
  17633. return table;
  17634. }
  17635. // Create table on load. Just 255 signed longs. Not a problem.
  17636. var crcTable = makeTable();
  17637. function crc32(crc, buf, len, pos) {
  17638. var t = crcTable
  17639. , end = pos + len;
  17640. crc = crc ^ (-1);
  17641. for (var i = pos; i < end; i++ ) {
  17642. crc = (crc >>> 8) ^ t[(crc ^ buf[i]) & 0xFF];
  17643. }
  17644. return (crc ^ (-1)); // >>> 0;
  17645. }
  17646. module.exports = crc32;
  17647. },{}],70:[function(require,module,exports){
  17648. 'use strict';
  17649. var utils = require('../utils/common');
  17650. var trees = require('./trees');
  17651. var adler32 = require('./adler32');
  17652. var crc32 = require('./crc32');
  17653. var msg = require('./messages');
  17654. /* Public constants ==========================================================*/
  17655. /* ===========================================================================*/
  17656. /* Allowed flush values; see deflate() and inflate() below for details */
  17657. var Z_NO_FLUSH = 0;
  17658. var Z_PARTIAL_FLUSH = 1;
  17659. //var Z_SYNC_FLUSH = 2;
  17660. var Z_FULL_FLUSH = 3;
  17661. var Z_FINISH = 4;
  17662. var Z_BLOCK = 5;
  17663. //var Z_TREES = 6;
  17664. /* Return codes for the compression/decompression functions. Negative values
  17665. * are errors, positive values are used for special but normal events.
  17666. */
  17667. var Z_OK = 0;
  17668. var Z_STREAM_END = 1;
  17669. //var Z_NEED_DICT = 2;
  17670. //var Z_ERRNO = -1;
  17671. var Z_STREAM_ERROR = -2;
  17672. var Z_DATA_ERROR = -3;
  17673. //var Z_MEM_ERROR = -4;
  17674. var Z_BUF_ERROR = -5;
  17675. //var Z_VERSION_ERROR = -6;
  17676. /* compression levels */
  17677. //var Z_NO_COMPRESSION = 0;
  17678. //var Z_BEST_SPEED = 1;
  17679. //var Z_BEST_COMPRESSION = 9;
  17680. var Z_DEFAULT_COMPRESSION = -1;
  17681. var Z_FILTERED = 1;
  17682. var Z_HUFFMAN_ONLY = 2;
  17683. var Z_RLE = 3;
  17684. var Z_FIXED = 4;
  17685. var Z_DEFAULT_STRATEGY = 0;
  17686. /* Possible values of the data_type field (though see inflate()) */
  17687. //var Z_BINARY = 0;
  17688. //var Z_TEXT = 1;
  17689. //var Z_ASCII = 1; // = Z_TEXT
  17690. var Z_UNKNOWN = 2;
  17691. /* The deflate compression method */
  17692. var Z_DEFLATED = 8;
  17693. /*============================================================================*/
  17694. var MAX_MEM_LEVEL = 9;
  17695. /* Maximum value for memLevel in deflateInit2 */
  17696. var MAX_WBITS = 15;
  17697. /* 32K LZ77 window */
  17698. var DEF_MEM_LEVEL = 8;
  17699. var LENGTH_CODES = 29;
  17700. /* number of length codes, not counting the special END_BLOCK code */
  17701. var LITERALS = 256;
  17702. /* number of literal bytes 0..255 */
  17703. var L_CODES = LITERALS + 1 + LENGTH_CODES;
  17704. /* number of Literal or Length codes, including the END_BLOCK code */
  17705. var D_CODES = 30;
  17706. /* number of distance codes */
  17707. var BL_CODES = 19;
  17708. /* number of codes used to transfer the bit lengths */
  17709. var HEAP_SIZE = 2*L_CODES + 1;
  17710. /* maximum heap size */
  17711. var MAX_BITS = 15;
  17712. /* All codes must not exceed MAX_BITS bits */
  17713. var MIN_MATCH = 3;
  17714. var MAX_MATCH = 258;
  17715. var MIN_LOOKAHEAD = (MAX_MATCH + MIN_MATCH + 1);
  17716. var PRESET_DICT = 0x20;
  17717. var INIT_STATE = 42;
  17718. var EXTRA_STATE = 69;
  17719. var NAME_STATE = 73;
  17720. var COMMENT_STATE = 91;
  17721. var HCRC_STATE = 103;
  17722. var BUSY_STATE = 113;
  17723. var FINISH_STATE = 666;
  17724. var BS_NEED_MORE = 1; /* block not completed, need more input or more output */
  17725. var BS_BLOCK_DONE = 2; /* block flush performed */
  17726. var BS_FINISH_STARTED = 3; /* finish started, need only more output at next deflate */
  17727. var BS_FINISH_DONE = 4; /* finish done, accept no more input or output */
  17728. var OS_CODE = 0x03; // Unix :) . Don't detect, use this default.
  17729. function err(strm, errorCode) {
  17730. strm.msg = msg[errorCode];
  17731. return errorCode;
  17732. }
  17733. function rank(f) {
  17734. return ((f) << 1) - ((f) > 4 ? 9 : 0);
  17735. }
  17736. function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
  17737. /* =========================================================================
  17738. * Flush as much pending output as possible. All deflate() output goes
  17739. * through this function so some applications may wish to modify it
  17740. * to avoid allocating a large strm->output buffer and copying into it.
  17741. * (See also read_buf()).
  17742. */
  17743. function flush_pending(strm) {
  17744. var s = strm.state;
  17745. //_tr_flush_bits(s);
  17746. var len = s.pending;
  17747. if (len > strm.avail_out) {
  17748. len = strm.avail_out;
  17749. }
  17750. if (len === 0) { return; }
  17751. utils.arraySet(strm.output, s.pending_buf, s.pending_out, len, strm.next_out);
  17752. strm.next_out += len;
  17753. s.pending_out += len;
  17754. strm.total_out += len;
  17755. strm.avail_out -= len;
  17756. s.pending -= len;
  17757. if (s.pending === 0) {
  17758. s.pending_out = 0;
  17759. }
  17760. }
  17761. function flush_block_only (s, last) {
  17762. trees._tr_flush_block(s, (s.block_start >= 0 ? s.block_start : -1), s.strstart - s.block_start, last);
  17763. s.block_start = s.strstart;
  17764. flush_pending(s.strm);
  17765. }
  17766. function put_byte(s, b) {
  17767. s.pending_buf[s.pending++] = b;
  17768. }
  17769. /* =========================================================================
  17770. * Put a short in the pending buffer. The 16-bit value is put in MSB order.
  17771. * IN assertion: the stream state is correct and there is enough room in
  17772. * pending_buf.
  17773. */
  17774. function putShortMSB(s, b) {
  17775. // put_byte(s, (Byte)(b >> 8));
  17776. // put_byte(s, (Byte)(b & 0xff));
  17777. s.pending_buf[s.pending++] = (b >>> 8) & 0xff;
  17778. s.pending_buf[s.pending++] = b & 0xff;
  17779. }
  17780. /* ===========================================================================
  17781. * Read a new buffer from the current input stream, update the adler32
  17782. * and total number of bytes read. All deflate() input goes through
  17783. * this function so some applications may wish to modify it to avoid
  17784. * allocating a large strm->input buffer and copying from it.
  17785. * (See also flush_pending()).
  17786. */
  17787. function read_buf(strm, buf, start, size) {
  17788. var len = strm.avail_in;
  17789. if (len > size) { len = size; }
  17790. if (len === 0) { return 0; }
  17791. strm.avail_in -= len;
  17792. utils.arraySet(buf, strm.input, strm.next_in, len, start);
  17793. if (strm.state.wrap === 1) {
  17794. strm.adler = adler32(strm.adler, buf, len, start);
  17795. }
  17796. else if (strm.state.wrap === 2) {
  17797. strm.adler = crc32(strm.adler, buf, len, start);
  17798. }
  17799. strm.next_in += len;
  17800. strm.total_in += len;
  17801. return len;
  17802. }
  17803. /* ===========================================================================
  17804. * Set match_start to the longest match starting at the given string and
  17805. * return its length. Matches shorter or equal to prev_length are discarded,
  17806. * in which case the result is equal to prev_length and match_start is
  17807. * garbage.
  17808. * IN assertions: cur_match is the head of the hash chain for the current
  17809. * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
  17810. * OUT assertion: the match length is not greater than s->lookahead.
  17811. */
  17812. function longest_match(s, cur_match) {
  17813. var chain_length = s.max_chain_length; /* max hash chain length */
  17814. var scan = s.strstart; /* current string */
  17815. var match; /* matched string */
  17816. var len; /* length of current match */
  17817. var best_len = s.prev_length; /* best match length so far */
  17818. var nice_match = s.nice_match; /* stop if match long enough */
  17819. var limit = (s.strstart > (s.w_size - MIN_LOOKAHEAD)) ?
  17820. s.strstart - (s.w_size - MIN_LOOKAHEAD) : 0/*NIL*/;
  17821. var _win = s.window; // shortcut
  17822. var wmask = s.w_mask;
  17823. var prev = s.prev;
  17824. /* Stop when cur_match becomes <= limit. To simplify the code,
  17825. * we prevent matches with the string of window index 0.
  17826. */
  17827. var strend = s.strstart + MAX_MATCH;
  17828. var scan_end1 = _win[scan + best_len - 1];
  17829. var scan_end = _win[scan + best_len];
  17830. /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
  17831. * It is easy to get rid of this optimization if necessary.
  17832. */
  17833. // Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
  17834. /* Do not waste too much time if we already have a good match: */
  17835. if (s.prev_length >= s.good_match) {
  17836. chain_length >>= 2;
  17837. }
  17838. /* Do not look for matches beyond the end of the input. This is necessary
  17839. * to make deflate deterministic.
  17840. */
  17841. if (nice_match > s.lookahead) { nice_match = s.lookahead; }
  17842. // Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
  17843. do {
  17844. // Assert(cur_match < s->strstart, "no future");
  17845. match = cur_match;
  17846. /* Skip to next match if the match length cannot increase
  17847. * or if the match length is less than 2. Note that the checks below
  17848. * for insufficient lookahead only occur occasionally for performance
  17849. * reasons. Therefore uninitialized memory will be accessed, and
  17850. * conditional jumps will be made that depend on those values.
  17851. * However the length of the match is limited to the lookahead, so
  17852. * the output of deflate is not affected by the uninitialized values.
  17853. */
  17854. if (_win[match + best_len] !== scan_end ||
  17855. _win[match + best_len - 1] !== scan_end1 ||
  17856. _win[match] !== _win[scan] ||
  17857. _win[++match] !== _win[scan + 1]) {
  17858. continue;
  17859. }
  17860. /* The check at best_len-1 can be removed because it will be made
  17861. * again later. (This heuristic is not always a win.)
  17862. * It is not necessary to compare scan[2] and match[2] since they
  17863. * are always equal when the other bytes match, given that
  17864. * the hash keys are equal and that HASH_BITS >= 8.
  17865. */
  17866. scan += 2;
  17867. match++;
  17868. // Assert(*scan == *match, "match[2]?");
  17869. /* We check for insufficient lookahead only every 8th comparison;
  17870. * the 256th check will be made at strstart+258.
  17871. */
  17872. do {
  17873. /*jshint noempty:false*/
  17874. } while (_win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  17875. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  17876. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  17877. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  17878. scan < strend);
  17879. // Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  17880. len = MAX_MATCH - (strend - scan);
  17881. scan = strend - MAX_MATCH;
  17882. if (len > best_len) {
  17883. s.match_start = cur_match;
  17884. best_len = len;
  17885. if (len >= nice_match) {
  17886. break;
  17887. }
  17888. scan_end1 = _win[scan + best_len - 1];
  17889. scan_end = _win[scan + best_len];
  17890. }
  17891. } while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length !== 0);
  17892. if (best_len <= s.lookahead) {
  17893. return best_len;
  17894. }
  17895. return s.lookahead;
  17896. }
  17897. /* ===========================================================================
  17898. * Fill the window when the lookahead becomes insufficient.
  17899. * Updates strstart and lookahead.
  17900. *
  17901. * IN assertion: lookahead < MIN_LOOKAHEAD
  17902. * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
  17903. * At least one byte has been read, or avail_in == 0; reads are
  17904. * performed for at least two bytes (required for the zip translate_eol
  17905. * option -- not supported here).
  17906. */
  17907. function fill_window(s) {
  17908. var _w_size = s.w_size;
  17909. var p, n, m, more, str;
  17910. //Assert(s->lookahead < MIN_LOOKAHEAD, "already enough lookahead");
  17911. do {
  17912. more = s.window_size - s.lookahead - s.strstart;
  17913. // JS ints have 32 bit, block below not needed
  17914. /* Deal with !@#$% 64K limit: */
  17915. //if (sizeof(int) <= 2) {
  17916. // if (more == 0 && s->strstart == 0 && s->lookahead == 0) {
  17917. // more = wsize;
  17918. //
  17919. // } else if (more == (unsigned)(-1)) {
  17920. // /* Very unlikely, but possible on 16 bit machine if
  17921. // * strstart == 0 && lookahead == 1 (input done a byte at time)
  17922. // */
  17923. // more--;
  17924. // }
  17925. //}
  17926. /* If the window is almost full and there is insufficient lookahead,
  17927. * move the upper half to the lower one to make room in the upper half.
  17928. */
  17929. if (s.strstart >= _w_size + (_w_size - MIN_LOOKAHEAD)) {
  17930. utils.arraySet(s.window, s.window, _w_size, _w_size, 0);
  17931. s.match_start -= _w_size;
  17932. s.strstart -= _w_size;
  17933. /* we now have strstart >= MAX_DIST */
  17934. s.block_start -= _w_size;
  17935. /* Slide the hash table (could be avoided with 32 bit values
  17936. at the expense of memory usage). We slide even when level == 0
  17937. to keep the hash table consistent if we switch back to level > 0
  17938. later. (Using level 0 permanently is not an optimal usage of
  17939. zlib, so we don't care about this pathological case.)
  17940. */
  17941. n = s.hash_size;
  17942. p = n;
  17943. do {
  17944. m = s.head[--p];
  17945. s.head[p] = (m >= _w_size ? m - _w_size : 0);
  17946. } while (--n);
  17947. n = _w_size;
  17948. p = n;
  17949. do {
  17950. m = s.prev[--p];
  17951. s.prev[p] = (m >= _w_size ? m - _w_size : 0);
  17952. /* If n is not on any hash chain, prev[n] is garbage but
  17953. * its value will never be used.
  17954. */
  17955. } while (--n);
  17956. more += _w_size;
  17957. }
  17958. if (s.strm.avail_in === 0) {
  17959. break;
  17960. }
  17961. /* If there was no sliding:
  17962. * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
  17963. * more == window_size - lookahead - strstart
  17964. * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
  17965. * => more >= window_size - 2*WSIZE + 2
  17966. * In the BIG_MEM or MMAP case (not yet supported),
  17967. * window_size == input_size + MIN_LOOKAHEAD &&
  17968. * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
  17969. * Otherwise, window_size == 2*WSIZE so more >= 2.
  17970. * If there was sliding, more >= WSIZE. So in all cases, more >= 2.
  17971. */
  17972. //Assert(more >= 2, "more < 2");
  17973. n = read_buf(s.strm, s.window, s.strstart + s.lookahead, more);
  17974. s.lookahead += n;
  17975. /* Initialize the hash value now that we have some input: */
  17976. if (s.lookahead + s.insert >= MIN_MATCH) {
  17977. str = s.strstart - s.insert;
  17978. s.ins_h = s.window[str];
  17979. /* UPDATE_HASH(s, s->ins_h, s->window[str + 1]); */
  17980. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + 1]) & s.hash_mask;
  17981. //#if MIN_MATCH != 3
  17982. // Call update_hash() MIN_MATCH-3 more times
  17983. //#endif
  17984. while (s.insert) {
  17985. /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */
  17986. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH-1]) & s.hash_mask;
  17987. s.prev[str & s.w_mask] = s.head[s.ins_h];
  17988. s.head[s.ins_h] = str;
  17989. str++;
  17990. s.insert--;
  17991. if (s.lookahead + s.insert < MIN_MATCH) {
  17992. break;
  17993. }
  17994. }
  17995. }
  17996. /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,
  17997. * but this is not important since only literal bytes will be emitted.
  17998. */
  17999. } while (s.lookahead < MIN_LOOKAHEAD && s.strm.avail_in !== 0);
  18000. /* If the WIN_INIT bytes after the end of the current data have never been
  18001. * written, then zero those bytes in order to avoid memory check reports of
  18002. * the use of uninitialized (or uninitialised as Julian writes) bytes by
  18003. * the longest match routines. Update the high water mark for the next
  18004. * time through here. WIN_INIT is set to MAX_MATCH since the longest match
  18005. * routines allow scanning to strstart + MAX_MATCH, ignoring lookahead.
  18006. */
  18007. // if (s.high_water < s.window_size) {
  18008. // var curr = s.strstart + s.lookahead;
  18009. // var init = 0;
  18010. //
  18011. // if (s.high_water < curr) {
  18012. // /* Previous high water mark below current data -- zero WIN_INIT
  18013. // * bytes or up to end of window, whichever is less.
  18014. // */
  18015. // init = s.window_size - curr;
  18016. // if (init > WIN_INIT)
  18017. // init = WIN_INIT;
  18018. // zmemzero(s->window + curr, (unsigned)init);
  18019. // s->high_water = curr + init;
  18020. // }
  18021. // else if (s->high_water < (ulg)curr + WIN_INIT) {
  18022. // /* High water mark at or above current data, but below current data
  18023. // * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up
  18024. // * to end of window, whichever is less.
  18025. // */
  18026. // init = (ulg)curr + WIN_INIT - s->high_water;
  18027. // if (init > s->window_size - s->high_water)
  18028. // init = s->window_size - s->high_water;
  18029. // zmemzero(s->window + s->high_water, (unsigned)init);
  18030. // s->high_water += init;
  18031. // }
  18032. // }
  18033. //
  18034. // Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD,
  18035. // "not enough room for search");
  18036. }
  18037. /* ===========================================================================
  18038. * Copy without compression as much as possible from the input stream, return
  18039. * the current block state.
  18040. * This function does not insert new strings in the dictionary since
  18041. * uncompressible data is probably not useful. This function is used
  18042. * only for the level=0 compression option.
  18043. * NOTE: this function should be optimized to avoid extra copying from
  18044. * window to pending_buf.
  18045. */
  18046. function deflate_stored(s, flush) {
  18047. /* Stored blocks are limited to 0xffff bytes, pending_buf is limited
  18048. * to pending_buf_size, and each stored block has a 5 byte header:
  18049. */
  18050. var max_block_size = 0xffff;
  18051. if (max_block_size > s.pending_buf_size - 5) {
  18052. max_block_size = s.pending_buf_size - 5;
  18053. }
  18054. /* Copy as much as possible from input to output: */
  18055. for (;;) {
  18056. /* Fill the window as much as possible: */
  18057. if (s.lookahead <= 1) {
  18058. //Assert(s->strstart < s->w_size+MAX_DIST(s) ||
  18059. // s->block_start >= (long)s->w_size, "slide too late");
  18060. // if (!(s.strstart < s.w_size + (s.w_size - MIN_LOOKAHEAD) ||
  18061. // s.block_start >= s.w_size)) {
  18062. // throw new Error("slide too late");
  18063. // }
  18064. fill_window(s);
  18065. if (s.lookahead === 0 && flush === Z_NO_FLUSH) {
  18066. return BS_NEED_MORE;
  18067. }
  18068. if (s.lookahead === 0) {
  18069. break;
  18070. }
  18071. /* flush the current block */
  18072. }
  18073. //Assert(s->block_start >= 0L, "block gone");
  18074. // if (s.block_start < 0) throw new Error("block gone");
  18075. s.strstart += s.lookahead;
  18076. s.lookahead = 0;
  18077. /* Emit a stored block if pending_buf will be full: */
  18078. var max_start = s.block_start + max_block_size;
  18079. if (s.strstart === 0 || s.strstart >= max_start) {
  18080. /* strstart == 0 is possible when wraparound on 16-bit machine */
  18081. s.lookahead = s.strstart - max_start;
  18082. s.strstart = max_start;
  18083. /*** FLUSH_BLOCK(s, 0); ***/
  18084. flush_block_only(s, false);
  18085. if (s.strm.avail_out === 0) {
  18086. return BS_NEED_MORE;
  18087. }
  18088. /***/
  18089. }
  18090. /* Flush if we may have to slide, otherwise block_start may become
  18091. * negative and the data will be gone:
  18092. */
  18093. if (s.strstart - s.block_start >= (s.w_size - MIN_LOOKAHEAD)) {
  18094. /*** FLUSH_BLOCK(s, 0); ***/
  18095. flush_block_only(s, false);
  18096. if (s.strm.avail_out === 0) {
  18097. return BS_NEED_MORE;
  18098. }
  18099. /***/
  18100. }
  18101. }
  18102. s.insert = 0;
  18103. if (flush === Z_FINISH) {
  18104. /*** FLUSH_BLOCK(s, 1); ***/
  18105. flush_block_only(s, true);
  18106. if (s.strm.avail_out === 0) {
  18107. return BS_FINISH_STARTED;
  18108. }
  18109. /***/
  18110. return BS_FINISH_DONE;
  18111. }
  18112. if (s.strstart > s.block_start) {
  18113. /*** FLUSH_BLOCK(s, 0); ***/
  18114. flush_block_only(s, false);
  18115. if (s.strm.avail_out === 0) {
  18116. return BS_NEED_MORE;
  18117. }
  18118. /***/
  18119. }
  18120. return BS_NEED_MORE;
  18121. }
  18122. /* ===========================================================================
  18123. * Compress as much as possible from the input stream, return the current
  18124. * block state.
  18125. * This function does not perform lazy evaluation of matches and inserts
  18126. * new strings in the dictionary only for unmatched strings or for short
  18127. * matches. It is used only for the fast compression options.
  18128. */
  18129. function deflate_fast(s, flush) {
  18130. var hash_head; /* head of the hash chain */
  18131. var bflush; /* set if current block must be flushed */
  18132. for (;;) {
  18133. /* Make sure that we always have enough lookahead, except
  18134. * at the end of the input file. We need MAX_MATCH bytes
  18135. * for the next match, plus MIN_MATCH bytes to insert the
  18136. * string following the next match.
  18137. */
  18138. if (s.lookahead < MIN_LOOKAHEAD) {
  18139. fill_window(s);
  18140. if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
  18141. return BS_NEED_MORE;
  18142. }
  18143. if (s.lookahead === 0) {
  18144. break; /* flush the current block */
  18145. }
  18146. }
  18147. /* Insert the string window[strstart .. strstart+2] in the
  18148. * dictionary, and set hash_head to the head of the hash chain:
  18149. */
  18150. hash_head = 0/*NIL*/;
  18151. if (s.lookahead >= MIN_MATCH) {
  18152. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  18153. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  18154. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  18155. s.head[s.ins_h] = s.strstart;
  18156. /***/
  18157. }
  18158. /* Find the longest match, discarding those <= prev_length.
  18159. * At this point we have always match_length < MIN_MATCH
  18160. */
  18161. if (hash_head !== 0/*NIL*/ && ((s.strstart - hash_head) <= (s.w_size - MIN_LOOKAHEAD))) {
  18162. /* To simplify the code, we prevent matches with the string
  18163. * of window index 0 (in particular we have to avoid a match
  18164. * of the string with itself at the start of the input file).
  18165. */
  18166. s.match_length = longest_match(s, hash_head);
  18167. /* longest_match() sets match_start */
  18168. }
  18169. if (s.match_length >= MIN_MATCH) {
  18170. // check_match(s, s.strstart, s.match_start, s.match_length); // for debug only
  18171. /*** _tr_tally_dist(s, s.strstart - s.match_start,
  18172. s.match_length - MIN_MATCH, bflush); ***/
  18173. bflush = trees._tr_tally(s, s.strstart - s.match_start, s.match_length - MIN_MATCH);
  18174. s.lookahead -= s.match_length;
  18175. /* Insert new strings in the hash table only if the match length
  18176. * is not too large. This saves time but degrades compression.
  18177. */
  18178. if (s.match_length <= s.max_lazy_match/*max_insert_length*/ && s.lookahead >= MIN_MATCH) {
  18179. s.match_length--; /* string at strstart already in table */
  18180. do {
  18181. s.strstart++;
  18182. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  18183. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  18184. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  18185. s.head[s.ins_h] = s.strstart;
  18186. /***/
  18187. /* strstart never exceeds WSIZE-MAX_MATCH, so there are
  18188. * always MIN_MATCH bytes ahead.
  18189. */
  18190. } while (--s.match_length !== 0);
  18191. s.strstart++;
  18192. } else
  18193. {
  18194. s.strstart += s.match_length;
  18195. s.match_length = 0;
  18196. s.ins_h = s.window[s.strstart];
  18197. /* UPDATE_HASH(s, s.ins_h, s.window[s.strstart+1]); */
  18198. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + 1]) & s.hash_mask;
  18199. //#if MIN_MATCH != 3
  18200. // Call UPDATE_HASH() MIN_MATCH-3 more times
  18201. //#endif
  18202. /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not
  18203. * matter since it will be recomputed at next deflate call.
  18204. */
  18205. }
  18206. } else {
  18207. /* No match, output a literal byte */
  18208. //Tracevv((stderr,"%c", s.window[s.strstart]));
  18209. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  18210. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  18211. s.lookahead--;
  18212. s.strstart++;
  18213. }
  18214. if (bflush) {
  18215. /*** FLUSH_BLOCK(s, 0); ***/
  18216. flush_block_only(s, false);
  18217. if (s.strm.avail_out === 0) {
  18218. return BS_NEED_MORE;
  18219. }
  18220. /***/
  18221. }
  18222. }
  18223. s.insert = ((s.strstart < (MIN_MATCH-1)) ? s.strstart : MIN_MATCH-1);
  18224. if (flush === Z_FINISH) {
  18225. /*** FLUSH_BLOCK(s, 1); ***/
  18226. flush_block_only(s, true);
  18227. if (s.strm.avail_out === 0) {
  18228. return BS_FINISH_STARTED;
  18229. }
  18230. /***/
  18231. return BS_FINISH_DONE;
  18232. }
  18233. if (s.last_lit) {
  18234. /*** FLUSH_BLOCK(s, 0); ***/
  18235. flush_block_only(s, false);
  18236. if (s.strm.avail_out === 0) {
  18237. return BS_NEED_MORE;
  18238. }
  18239. /***/
  18240. }
  18241. return BS_BLOCK_DONE;
  18242. }
  18243. /* ===========================================================================
  18244. * Same as above, but achieves better compression. We use a lazy
  18245. * evaluation for matches: a match is finally adopted only if there is
  18246. * no better match at the next window position.
  18247. */
  18248. function deflate_slow(s, flush) {
  18249. var hash_head; /* head of hash chain */
  18250. var bflush; /* set if current block must be flushed */
  18251. var max_insert;
  18252. /* Process the input block. */
  18253. for (;;) {
  18254. /* Make sure that we always have enough lookahead, except
  18255. * at the end of the input file. We need MAX_MATCH bytes
  18256. * for the next match, plus MIN_MATCH bytes to insert the
  18257. * string following the next match.
  18258. */
  18259. if (s.lookahead < MIN_LOOKAHEAD) {
  18260. fill_window(s);
  18261. if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
  18262. return BS_NEED_MORE;
  18263. }
  18264. if (s.lookahead === 0) { break; } /* flush the current block */
  18265. }
  18266. /* Insert the string window[strstart .. strstart+2] in the
  18267. * dictionary, and set hash_head to the head of the hash chain:
  18268. */
  18269. hash_head = 0/*NIL*/;
  18270. if (s.lookahead >= MIN_MATCH) {
  18271. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  18272. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  18273. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  18274. s.head[s.ins_h] = s.strstart;
  18275. /***/
  18276. }
  18277. /* Find the longest match, discarding those <= prev_length.
  18278. */
  18279. s.prev_length = s.match_length;
  18280. s.prev_match = s.match_start;
  18281. s.match_length = MIN_MATCH-1;
  18282. if (hash_head !== 0/*NIL*/ && s.prev_length < s.max_lazy_match &&
  18283. s.strstart - hash_head <= (s.w_size-MIN_LOOKAHEAD)/*MAX_DIST(s)*/) {
  18284. /* To simplify the code, we prevent matches with the string
  18285. * of window index 0 (in particular we have to avoid a match
  18286. * of the string with itself at the start of the input file).
  18287. */
  18288. s.match_length = longest_match(s, hash_head);
  18289. /* longest_match() sets match_start */
  18290. if (s.match_length <= 5 &&
  18291. (s.strategy === Z_FILTERED || (s.match_length === MIN_MATCH && s.strstart - s.match_start > 4096/*TOO_FAR*/))) {
  18292. /* If prev_match is also MIN_MATCH, match_start is garbage
  18293. * but we will ignore the current match anyway.
  18294. */
  18295. s.match_length = MIN_MATCH-1;
  18296. }
  18297. }
  18298. /* If there was a match at the previous step and the current
  18299. * match is not better, output the previous match:
  18300. */
  18301. if (s.prev_length >= MIN_MATCH && s.match_length <= s.prev_length) {
  18302. max_insert = s.strstart + s.lookahead - MIN_MATCH;
  18303. /* Do not insert strings in hash table beyond this. */
  18304. //check_match(s, s.strstart-1, s.prev_match, s.prev_length);
  18305. /***_tr_tally_dist(s, s.strstart - 1 - s.prev_match,
  18306. s.prev_length - MIN_MATCH, bflush);***/
  18307. bflush = trees._tr_tally(s, s.strstart - 1- s.prev_match, s.prev_length - MIN_MATCH);
  18308. /* Insert in hash table all strings up to the end of the match.
  18309. * strstart-1 and strstart are already inserted. If there is not
  18310. * enough lookahead, the last two strings are not inserted in
  18311. * the hash table.
  18312. */
  18313. s.lookahead -= s.prev_length-1;
  18314. s.prev_length -= 2;
  18315. do {
  18316. if (++s.strstart <= max_insert) {
  18317. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  18318. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  18319. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  18320. s.head[s.ins_h] = s.strstart;
  18321. /***/
  18322. }
  18323. } while (--s.prev_length !== 0);
  18324. s.match_available = 0;
  18325. s.match_length = MIN_MATCH-1;
  18326. s.strstart++;
  18327. if (bflush) {
  18328. /*** FLUSH_BLOCK(s, 0); ***/
  18329. flush_block_only(s, false);
  18330. if (s.strm.avail_out === 0) {
  18331. return BS_NEED_MORE;
  18332. }
  18333. /***/
  18334. }
  18335. } else if (s.match_available) {
  18336. /* If there was no match at the previous position, output a
  18337. * single literal. If there was a match but the current match
  18338. * is longer, truncate the previous match to a single literal.
  18339. */
  18340. //Tracevv((stderr,"%c", s->window[s->strstart-1]));
  18341. /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
  18342. bflush = trees._tr_tally(s, 0, s.window[s.strstart-1]);
  18343. if (bflush) {
  18344. /*** FLUSH_BLOCK_ONLY(s, 0) ***/
  18345. flush_block_only(s, false);
  18346. /***/
  18347. }
  18348. s.strstart++;
  18349. s.lookahead--;
  18350. if (s.strm.avail_out === 0) {
  18351. return BS_NEED_MORE;
  18352. }
  18353. } else {
  18354. /* There is no previous match to compare with, wait for
  18355. * the next step to decide.
  18356. */
  18357. s.match_available = 1;
  18358. s.strstart++;
  18359. s.lookahead--;
  18360. }
  18361. }
  18362. //Assert (flush != Z_NO_FLUSH, "no flush?");
  18363. if (s.match_available) {
  18364. //Tracevv((stderr,"%c", s->window[s->strstart-1]));
  18365. /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
  18366. bflush = trees._tr_tally(s, 0, s.window[s.strstart-1]);
  18367. s.match_available = 0;
  18368. }
  18369. s.insert = s.strstart < MIN_MATCH-1 ? s.strstart : MIN_MATCH-1;
  18370. if (flush === Z_FINISH) {
  18371. /*** FLUSH_BLOCK(s, 1); ***/
  18372. flush_block_only(s, true);
  18373. if (s.strm.avail_out === 0) {
  18374. return BS_FINISH_STARTED;
  18375. }
  18376. /***/
  18377. return BS_FINISH_DONE;
  18378. }
  18379. if (s.last_lit) {
  18380. /*** FLUSH_BLOCK(s, 0); ***/
  18381. flush_block_only(s, false);
  18382. if (s.strm.avail_out === 0) {
  18383. return BS_NEED_MORE;
  18384. }
  18385. /***/
  18386. }
  18387. return BS_BLOCK_DONE;
  18388. }
  18389. /* ===========================================================================
  18390. * For Z_RLE, simply look for runs of bytes, generate matches only of distance
  18391. * one. Do not maintain a hash table. (It will be regenerated if this run of
  18392. * deflate switches away from Z_RLE.)
  18393. */
  18394. function deflate_rle(s, flush) {
  18395. var bflush; /* set if current block must be flushed */
  18396. var prev; /* byte at distance one to match */
  18397. var scan, strend; /* scan goes up to strend for length of run */
  18398. var _win = s.window;
  18399. for (;;) {
  18400. /* Make sure that we always have enough lookahead, except
  18401. * at the end of the input file. We need MAX_MATCH bytes
  18402. * for the longest run, plus one for the unrolled loop.
  18403. */
  18404. if (s.lookahead <= MAX_MATCH) {
  18405. fill_window(s);
  18406. if (s.lookahead <= MAX_MATCH && flush === Z_NO_FLUSH) {
  18407. return BS_NEED_MORE;
  18408. }
  18409. if (s.lookahead === 0) { break; } /* flush the current block */
  18410. }
  18411. /* See how many times the previous byte repeats */
  18412. s.match_length = 0;
  18413. if (s.lookahead >= MIN_MATCH && s.strstart > 0) {
  18414. scan = s.strstart - 1;
  18415. prev = _win[scan];
  18416. if (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan]) {
  18417. strend = s.strstart + MAX_MATCH;
  18418. do {
  18419. /*jshint noempty:false*/
  18420. } while (prev === _win[++scan] && prev === _win[++scan] &&
  18421. prev === _win[++scan] && prev === _win[++scan] &&
  18422. prev === _win[++scan] && prev === _win[++scan] &&
  18423. prev === _win[++scan] && prev === _win[++scan] &&
  18424. scan < strend);
  18425. s.match_length = MAX_MATCH - (strend - scan);
  18426. if (s.match_length > s.lookahead) {
  18427. s.match_length = s.lookahead;
  18428. }
  18429. }
  18430. //Assert(scan <= s->window+(uInt)(s->window_size-1), "wild scan");
  18431. }
  18432. /* Emit match if have run of MIN_MATCH or longer, else emit literal */
  18433. if (s.match_length >= MIN_MATCH) {
  18434. //check_match(s, s.strstart, s.strstart - 1, s.match_length);
  18435. /*** _tr_tally_dist(s, 1, s.match_length - MIN_MATCH, bflush); ***/
  18436. bflush = trees._tr_tally(s, 1, s.match_length - MIN_MATCH);
  18437. s.lookahead -= s.match_length;
  18438. s.strstart += s.match_length;
  18439. s.match_length = 0;
  18440. } else {
  18441. /* No match, output a literal byte */
  18442. //Tracevv((stderr,"%c", s->window[s->strstart]));
  18443. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  18444. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  18445. s.lookahead--;
  18446. s.strstart++;
  18447. }
  18448. if (bflush) {
  18449. /*** FLUSH_BLOCK(s, 0); ***/
  18450. flush_block_only(s, false);
  18451. if (s.strm.avail_out === 0) {
  18452. return BS_NEED_MORE;
  18453. }
  18454. /***/
  18455. }
  18456. }
  18457. s.insert = 0;
  18458. if (flush === Z_FINISH) {
  18459. /*** FLUSH_BLOCK(s, 1); ***/
  18460. flush_block_only(s, true);
  18461. if (s.strm.avail_out === 0) {
  18462. return BS_FINISH_STARTED;
  18463. }
  18464. /***/
  18465. return BS_FINISH_DONE;
  18466. }
  18467. if (s.last_lit) {
  18468. /*** FLUSH_BLOCK(s, 0); ***/
  18469. flush_block_only(s, false);
  18470. if (s.strm.avail_out === 0) {
  18471. return BS_NEED_MORE;
  18472. }
  18473. /***/
  18474. }
  18475. return BS_BLOCK_DONE;
  18476. }
  18477. /* ===========================================================================
  18478. * For Z_HUFFMAN_ONLY, do not look for matches. Do not maintain a hash table.
  18479. * (It will be regenerated if this run of deflate switches away from Huffman.)
  18480. */
  18481. function deflate_huff(s, flush) {
  18482. var bflush; /* set if current block must be flushed */
  18483. for (;;) {
  18484. /* Make sure that we have a literal to write. */
  18485. if (s.lookahead === 0) {
  18486. fill_window(s);
  18487. if (s.lookahead === 0) {
  18488. if (flush === Z_NO_FLUSH) {
  18489. return BS_NEED_MORE;
  18490. }
  18491. break; /* flush the current block */
  18492. }
  18493. }
  18494. /* Output a literal byte */
  18495. s.match_length = 0;
  18496. //Tracevv((stderr,"%c", s->window[s->strstart]));
  18497. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  18498. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  18499. s.lookahead--;
  18500. s.strstart++;
  18501. if (bflush) {
  18502. /*** FLUSH_BLOCK(s, 0); ***/
  18503. flush_block_only(s, false);
  18504. if (s.strm.avail_out === 0) {
  18505. return BS_NEED_MORE;
  18506. }
  18507. /***/
  18508. }
  18509. }
  18510. s.insert = 0;
  18511. if (flush === Z_FINISH) {
  18512. /*** FLUSH_BLOCK(s, 1); ***/
  18513. flush_block_only(s, true);
  18514. if (s.strm.avail_out === 0) {
  18515. return BS_FINISH_STARTED;
  18516. }
  18517. /***/
  18518. return BS_FINISH_DONE;
  18519. }
  18520. if (s.last_lit) {
  18521. /*** FLUSH_BLOCK(s, 0); ***/
  18522. flush_block_only(s, false);
  18523. if (s.strm.avail_out === 0) {
  18524. return BS_NEED_MORE;
  18525. }
  18526. /***/
  18527. }
  18528. return BS_BLOCK_DONE;
  18529. }
  18530. /* Values for max_lazy_match, good_match and max_chain_length, depending on
  18531. * the desired pack level (0..9). The values given below have been tuned to
  18532. * exclude worst case performance for pathological files. Better values may be
  18533. * found for specific files.
  18534. */
  18535. var Config = function (good_length, max_lazy, nice_length, max_chain, func) {
  18536. this.good_length = good_length;
  18537. this.max_lazy = max_lazy;
  18538. this.nice_length = nice_length;
  18539. this.max_chain = max_chain;
  18540. this.func = func;
  18541. };
  18542. var configuration_table;
  18543. configuration_table = [
  18544. /* good lazy nice chain */
  18545. new Config(0, 0, 0, 0, deflate_stored), /* 0 store only */
  18546. new Config(4, 4, 8, 4, deflate_fast), /* 1 max speed, no lazy matches */
  18547. new Config(4, 5, 16, 8, deflate_fast), /* 2 */
  18548. new Config(4, 6, 32, 32, deflate_fast), /* 3 */
  18549. new Config(4, 4, 16, 16, deflate_slow), /* 4 lazy matches */
  18550. new Config(8, 16, 32, 32, deflate_slow), /* 5 */
  18551. new Config(8, 16, 128, 128, deflate_slow), /* 6 */
  18552. new Config(8, 32, 128, 256, deflate_slow), /* 7 */
  18553. new Config(32, 128, 258, 1024, deflate_slow), /* 8 */
  18554. new Config(32, 258, 258, 4096, deflate_slow) /* 9 max compression */
  18555. ];
  18556. /* ===========================================================================
  18557. * Initialize the "longest match" routines for a new zlib stream
  18558. */
  18559. function lm_init(s) {
  18560. s.window_size = 2 * s.w_size;
  18561. /*** CLEAR_HASH(s); ***/
  18562. zero(s.head); // Fill with NIL (= 0);
  18563. /* Set the default configuration parameters:
  18564. */
  18565. s.max_lazy_match = configuration_table[s.level].max_lazy;
  18566. s.good_match = configuration_table[s.level].good_length;
  18567. s.nice_match = configuration_table[s.level].nice_length;
  18568. s.max_chain_length = configuration_table[s.level].max_chain;
  18569. s.strstart = 0;
  18570. s.block_start = 0;
  18571. s.lookahead = 0;
  18572. s.insert = 0;
  18573. s.match_length = s.prev_length = MIN_MATCH - 1;
  18574. s.match_available = 0;
  18575. s.ins_h = 0;
  18576. }
  18577. function DeflateState() {
  18578. this.strm = null; /* pointer back to this zlib stream */
  18579. this.status = 0; /* as the name implies */
  18580. this.pending_buf = null; /* output still pending */
  18581. this.pending_buf_size = 0; /* size of pending_buf */
  18582. this.pending_out = 0; /* next pending byte to output to the stream */
  18583. this.pending = 0; /* nb of bytes in the pending buffer */
  18584. this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
  18585. this.gzhead = null; /* gzip header information to write */
  18586. this.gzindex = 0; /* where in extra, name, or comment */
  18587. this.method = Z_DEFLATED; /* can only be DEFLATED */
  18588. this.last_flush = -1; /* value of flush param for previous deflate call */
  18589. this.w_size = 0; /* LZ77 window size (32K by default) */
  18590. this.w_bits = 0; /* log2(w_size) (8..16) */
  18591. this.w_mask = 0; /* w_size - 1 */
  18592. this.window = null;
  18593. /* Sliding window. Input bytes are read into the second half of the window,
  18594. * and move to the first half later to keep a dictionary of at least wSize
  18595. * bytes. With this organization, matches are limited to a distance of
  18596. * wSize-MAX_MATCH bytes, but this ensures that IO is always
  18597. * performed with a length multiple of the block size.
  18598. */
  18599. this.window_size = 0;
  18600. /* Actual size of window: 2*wSize, except when the user input buffer
  18601. * is directly used as sliding window.
  18602. */
  18603. this.prev = null;
  18604. /* Link to older string with same hash index. To limit the size of this
  18605. * array to 64K, this link is maintained only for the last 32K strings.
  18606. * An index in this array is thus a window index modulo 32K.
  18607. */
  18608. this.head = null; /* Heads of the hash chains or NIL. */
  18609. this.ins_h = 0; /* hash index of string to be inserted */
  18610. this.hash_size = 0; /* number of elements in hash table */
  18611. this.hash_bits = 0; /* log2(hash_size) */
  18612. this.hash_mask = 0; /* hash_size-1 */
  18613. this.hash_shift = 0;
  18614. /* Number of bits by which ins_h must be shifted at each input
  18615. * step. It must be such that after MIN_MATCH steps, the oldest
  18616. * byte no longer takes part in the hash key, that is:
  18617. * hash_shift * MIN_MATCH >= hash_bits
  18618. */
  18619. this.block_start = 0;
  18620. /* Window position at the beginning of the current output block. Gets
  18621. * negative when the window is moved backwards.
  18622. */
  18623. this.match_length = 0; /* length of best match */
  18624. this.prev_match = 0; /* previous match */
  18625. this.match_available = 0; /* set if previous match exists */
  18626. this.strstart = 0; /* start of string to insert */
  18627. this.match_start = 0; /* start of matching string */
  18628. this.lookahead = 0; /* number of valid bytes ahead in window */
  18629. this.prev_length = 0;
  18630. /* Length of the best match at previous step. Matches not greater than this
  18631. * are discarded. This is used in the lazy match evaluation.
  18632. */
  18633. this.max_chain_length = 0;
  18634. /* To speed up deflation, hash chains are never searched beyond this
  18635. * length. A higher limit improves compression ratio but degrades the
  18636. * speed.
  18637. */
  18638. this.max_lazy_match = 0;
  18639. /* Attempt to find a better match only when the current match is strictly
  18640. * smaller than this value. This mechanism is used only for compression
  18641. * levels >= 4.
  18642. */
  18643. // That's alias to max_lazy_match, don't use directly
  18644. //this.max_insert_length = 0;
  18645. /* Insert new strings in the hash table only if the match length is not
  18646. * greater than this length. This saves time but degrades compression.
  18647. * max_insert_length is used only for compression levels <= 3.
  18648. */
  18649. this.level = 0; /* compression level (1..9) */
  18650. this.strategy = 0; /* favor or force Huffman coding*/
  18651. this.good_match = 0;
  18652. /* Use a faster search when the previous match is longer than this */
  18653. this.nice_match = 0; /* Stop searching when current match exceeds this */
  18654. /* used by trees.c: */
  18655. /* Didn't use ct_data typedef below to suppress compiler warning */
  18656. // struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */
  18657. // struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */
  18658. // struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */
  18659. // Use flat array of DOUBLE size, with interleaved fata,
  18660. // because JS does not support effective
  18661. this.dyn_ltree = new utils.Buf16(HEAP_SIZE * 2);
  18662. this.dyn_dtree = new utils.Buf16((2*D_CODES+1) * 2);
  18663. this.bl_tree = new utils.Buf16((2*BL_CODES+1) * 2);
  18664. zero(this.dyn_ltree);
  18665. zero(this.dyn_dtree);
  18666. zero(this.bl_tree);
  18667. this.l_desc = null; /* desc. for literal tree */
  18668. this.d_desc = null; /* desc. for distance tree */
  18669. this.bl_desc = null; /* desc. for bit length tree */
  18670. //ush bl_count[MAX_BITS+1];
  18671. this.bl_count = new utils.Buf16(MAX_BITS+1);
  18672. /* number of codes at each bit length for an optimal tree */
  18673. //int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */
  18674. this.heap = new utils.Buf16(2*L_CODES+1); /* heap used to build the Huffman trees */
  18675. zero(this.heap);
  18676. this.heap_len = 0; /* number of elements in the heap */
  18677. this.heap_max = 0; /* element of largest frequency */
  18678. /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.
  18679. * The same heap array is used to build all trees.
  18680. */
  18681. this.depth = new utils.Buf16(2*L_CODES+1); //uch depth[2*L_CODES+1];
  18682. zero(this.depth);
  18683. /* Depth of each subtree used as tie breaker for trees of equal frequency
  18684. */
  18685. this.l_buf = 0; /* buffer index for literals or lengths */
  18686. this.lit_bufsize = 0;
  18687. /* Size of match buffer for literals/lengths. There are 4 reasons for
  18688. * limiting lit_bufsize to 64K:
  18689. * - frequencies can be kept in 16 bit counters
  18690. * - if compression is not successful for the first block, all input
  18691. * data is still in the window so we can still emit a stored block even
  18692. * when input comes from standard input. (This can also be done for
  18693. * all blocks if lit_bufsize is not greater than 32K.)
  18694. * - if compression is not successful for a file smaller than 64K, we can
  18695. * even emit a stored file instead of a stored block (saving 5 bytes).
  18696. * This is applicable only for zip (not gzip or zlib).
  18697. * - creating new Huffman trees less frequently may not provide fast
  18698. * adaptation to changes in the input data statistics. (Take for
  18699. * example a binary file with poorly compressible code followed by
  18700. * a highly compressible string table.) Smaller buffer sizes give
  18701. * fast adaptation but have of course the overhead of transmitting
  18702. * trees more frequently.
  18703. * - I can't count above 4
  18704. */
  18705. this.last_lit = 0; /* running index in l_buf */
  18706. this.d_buf = 0;
  18707. /* Buffer index for distances. To simplify the code, d_buf and l_buf have
  18708. * the same number of elements. To use different lengths, an extra flag
  18709. * array would be necessary.
  18710. */
  18711. this.opt_len = 0; /* bit length of current block with optimal trees */
  18712. this.static_len = 0; /* bit length of current block with static trees */
  18713. this.matches = 0; /* number of string matches in current block */
  18714. this.insert = 0; /* bytes at end of window left to insert */
  18715. this.bi_buf = 0;
  18716. /* Output buffer. bits are inserted starting at the bottom (least
  18717. * significant bits).
  18718. */
  18719. this.bi_valid = 0;
  18720. /* Number of valid bits in bi_buf. All bits above the last valid bit
  18721. * are always zero.
  18722. */
  18723. // Used for window memory init. We safely ignore it for JS. That makes
  18724. // sense only for pointers and memory check tools.
  18725. //this.high_water = 0;
  18726. /* High water mark offset in window for initialized bytes -- bytes above
  18727. * this are set to zero in order to avoid memory check warnings when
  18728. * longest match routines access bytes past the input. This is then
  18729. * updated to the new high water mark.
  18730. */
  18731. }
  18732. function deflateResetKeep(strm) {
  18733. var s;
  18734. if (!strm || !strm.state) {
  18735. return err(strm, Z_STREAM_ERROR);
  18736. }
  18737. strm.total_in = strm.total_out = 0;
  18738. strm.data_type = Z_UNKNOWN;
  18739. s = strm.state;
  18740. s.pending = 0;
  18741. s.pending_out = 0;
  18742. if (s.wrap < 0) {
  18743. s.wrap = -s.wrap;
  18744. /* was made negative by deflate(..., Z_FINISH); */
  18745. }
  18746. s.status = (s.wrap ? INIT_STATE : BUSY_STATE);
  18747. strm.adler = (s.wrap === 2) ?
  18748. 0 // crc32(0, Z_NULL, 0)
  18749. :
  18750. 1; // adler32(0, Z_NULL, 0)
  18751. s.last_flush = Z_NO_FLUSH;
  18752. trees._tr_init(s);
  18753. return Z_OK;
  18754. }
  18755. function deflateReset(strm) {
  18756. var ret = deflateResetKeep(strm);
  18757. if (ret === Z_OK) {
  18758. lm_init(strm.state);
  18759. }
  18760. return ret;
  18761. }
  18762. function deflateSetHeader(strm, head) {
  18763. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  18764. if (strm.state.wrap !== 2) { return Z_STREAM_ERROR; }
  18765. strm.state.gzhead = head;
  18766. return Z_OK;
  18767. }
  18768. function deflateInit2(strm, level, method, windowBits, memLevel, strategy) {
  18769. if (!strm) { // === Z_NULL
  18770. return Z_STREAM_ERROR;
  18771. }
  18772. var wrap = 1;
  18773. if (level === Z_DEFAULT_COMPRESSION) {
  18774. level = 6;
  18775. }
  18776. if (windowBits < 0) { /* suppress zlib wrapper */
  18777. wrap = 0;
  18778. windowBits = -windowBits;
  18779. }
  18780. else if (windowBits > 15) {
  18781. wrap = 2; /* write gzip wrapper instead */
  18782. windowBits -= 16;
  18783. }
  18784. if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method !== Z_DEFLATED ||
  18785. windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||
  18786. strategy < 0 || strategy > Z_FIXED) {
  18787. return err(strm, Z_STREAM_ERROR);
  18788. }
  18789. if (windowBits === 8) {
  18790. windowBits = 9;
  18791. }
  18792. /* until 256-byte window bug fixed */
  18793. var s = new DeflateState();
  18794. strm.state = s;
  18795. s.strm = strm;
  18796. s.wrap = wrap;
  18797. s.gzhead = null;
  18798. s.w_bits = windowBits;
  18799. s.w_size = 1 << s.w_bits;
  18800. s.w_mask = s.w_size - 1;
  18801. s.hash_bits = memLevel + 7;
  18802. s.hash_size = 1 << s.hash_bits;
  18803. s.hash_mask = s.hash_size - 1;
  18804. s.hash_shift = ~~((s.hash_bits + MIN_MATCH - 1) / MIN_MATCH);
  18805. s.window = new utils.Buf8(s.w_size * 2);
  18806. s.head = new utils.Buf16(s.hash_size);
  18807. s.prev = new utils.Buf16(s.w_size);
  18808. // Don't need mem init magic for JS.
  18809. //s.high_water = 0; /* nothing written to s->window yet */
  18810. s.lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */
  18811. s.pending_buf_size = s.lit_bufsize * 4;
  18812. s.pending_buf = new utils.Buf8(s.pending_buf_size);
  18813. s.d_buf = s.lit_bufsize >> 1;
  18814. s.l_buf = (1 + 2) * s.lit_bufsize;
  18815. s.level = level;
  18816. s.strategy = strategy;
  18817. s.method = method;
  18818. return deflateReset(strm);
  18819. }
  18820. function deflateInit(strm, level) {
  18821. return deflateInit2(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY);
  18822. }
  18823. function deflate(strm, flush) {
  18824. var old_flush, s;
  18825. var beg, val; // for gzip header write only
  18826. if (!strm || !strm.state ||
  18827. flush > Z_BLOCK || flush < 0) {
  18828. return strm ? err(strm, Z_STREAM_ERROR) : Z_STREAM_ERROR;
  18829. }
  18830. s = strm.state;
  18831. if (!strm.output ||
  18832. (!strm.input && strm.avail_in !== 0) ||
  18833. (s.status === FINISH_STATE && flush !== Z_FINISH)) {
  18834. return err(strm, (strm.avail_out === 0) ? Z_BUF_ERROR : Z_STREAM_ERROR);
  18835. }
  18836. s.strm = strm; /* just in case */
  18837. old_flush = s.last_flush;
  18838. s.last_flush = flush;
  18839. /* Write the header */
  18840. if (s.status === INIT_STATE) {
  18841. if (s.wrap === 2) { // GZIP header
  18842. strm.adler = 0; //crc32(0L, Z_NULL, 0);
  18843. put_byte(s, 31);
  18844. put_byte(s, 139);
  18845. put_byte(s, 8);
  18846. if (!s.gzhead) { // s->gzhead == Z_NULL
  18847. put_byte(s, 0);
  18848. put_byte(s, 0);
  18849. put_byte(s, 0);
  18850. put_byte(s, 0);
  18851. put_byte(s, 0);
  18852. put_byte(s, s.level === 9 ? 2 :
  18853. (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
  18854. 4 : 0));
  18855. put_byte(s, OS_CODE);
  18856. s.status = BUSY_STATE;
  18857. }
  18858. else {
  18859. put_byte(s, (s.gzhead.text ? 1 : 0) +
  18860. (s.gzhead.hcrc ? 2 : 0) +
  18861. (!s.gzhead.extra ? 0 : 4) +
  18862. (!s.gzhead.name ? 0 : 8) +
  18863. (!s.gzhead.comment ? 0 : 16)
  18864. );
  18865. put_byte(s, s.gzhead.time & 0xff);
  18866. put_byte(s, (s.gzhead.time >> 8) & 0xff);
  18867. put_byte(s, (s.gzhead.time >> 16) & 0xff);
  18868. put_byte(s, (s.gzhead.time >> 24) & 0xff);
  18869. put_byte(s, s.level === 9 ? 2 :
  18870. (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
  18871. 4 : 0));
  18872. put_byte(s, s.gzhead.os & 0xff);
  18873. if (s.gzhead.extra && s.gzhead.extra.length) {
  18874. put_byte(s, s.gzhead.extra.length & 0xff);
  18875. put_byte(s, (s.gzhead.extra.length >> 8) & 0xff);
  18876. }
  18877. if (s.gzhead.hcrc) {
  18878. strm.adler = crc32(strm.adler, s.pending_buf, s.pending, 0);
  18879. }
  18880. s.gzindex = 0;
  18881. s.status = EXTRA_STATE;
  18882. }
  18883. }
  18884. else // DEFLATE header
  18885. {
  18886. var header = (Z_DEFLATED + ((s.w_bits - 8) << 4)) << 8;
  18887. var level_flags = -1;
  18888. if (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2) {
  18889. level_flags = 0;
  18890. } else if (s.level < 6) {
  18891. level_flags = 1;
  18892. } else if (s.level === 6) {
  18893. level_flags = 2;
  18894. } else {
  18895. level_flags = 3;
  18896. }
  18897. header |= (level_flags << 6);
  18898. if (s.strstart !== 0) { header |= PRESET_DICT; }
  18899. header += 31 - (header % 31);
  18900. s.status = BUSY_STATE;
  18901. putShortMSB(s, header);
  18902. /* Save the adler32 of the preset dictionary: */
  18903. if (s.strstart !== 0) {
  18904. putShortMSB(s, strm.adler >>> 16);
  18905. putShortMSB(s, strm.adler & 0xffff);
  18906. }
  18907. strm.adler = 1; // adler32(0L, Z_NULL, 0);
  18908. }
  18909. }
  18910. //#ifdef GZIP
  18911. if (s.status === EXTRA_STATE) {
  18912. if (s.gzhead.extra/* != Z_NULL*/) {
  18913. beg = s.pending; /* start of bytes to update crc */
  18914. while (s.gzindex < (s.gzhead.extra.length & 0xffff)) {
  18915. if (s.pending === s.pending_buf_size) {
  18916. if (s.gzhead.hcrc && s.pending > beg) {
  18917. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  18918. }
  18919. flush_pending(strm);
  18920. beg = s.pending;
  18921. if (s.pending === s.pending_buf_size) {
  18922. break;
  18923. }
  18924. }
  18925. put_byte(s, s.gzhead.extra[s.gzindex] & 0xff);
  18926. s.gzindex++;
  18927. }
  18928. if (s.gzhead.hcrc && s.pending > beg) {
  18929. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  18930. }
  18931. if (s.gzindex === s.gzhead.extra.length) {
  18932. s.gzindex = 0;
  18933. s.status = NAME_STATE;
  18934. }
  18935. }
  18936. else {
  18937. s.status = NAME_STATE;
  18938. }
  18939. }
  18940. if (s.status === NAME_STATE) {
  18941. if (s.gzhead.name/* != Z_NULL*/) {
  18942. beg = s.pending; /* start of bytes to update crc */
  18943. //int val;
  18944. do {
  18945. if (s.pending === s.pending_buf_size) {
  18946. if (s.gzhead.hcrc && s.pending > beg) {
  18947. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  18948. }
  18949. flush_pending(strm);
  18950. beg = s.pending;
  18951. if (s.pending === s.pending_buf_size) {
  18952. val = 1;
  18953. break;
  18954. }
  18955. }
  18956. // JS specific: little magic to add zero terminator to end of string
  18957. if (s.gzindex < s.gzhead.name.length) {
  18958. val = s.gzhead.name.charCodeAt(s.gzindex++) & 0xff;
  18959. } else {
  18960. val = 0;
  18961. }
  18962. put_byte(s, val);
  18963. } while (val !== 0);
  18964. if (s.gzhead.hcrc && s.pending > beg){
  18965. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  18966. }
  18967. if (val === 0) {
  18968. s.gzindex = 0;
  18969. s.status = COMMENT_STATE;
  18970. }
  18971. }
  18972. else {
  18973. s.status = COMMENT_STATE;
  18974. }
  18975. }
  18976. if (s.status === COMMENT_STATE) {
  18977. if (s.gzhead.comment/* != Z_NULL*/) {
  18978. beg = s.pending; /* start of bytes to update crc */
  18979. //int val;
  18980. do {
  18981. if (s.pending === s.pending_buf_size) {
  18982. if (s.gzhead.hcrc && s.pending > beg) {
  18983. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  18984. }
  18985. flush_pending(strm);
  18986. beg = s.pending;
  18987. if (s.pending === s.pending_buf_size) {
  18988. val = 1;
  18989. break;
  18990. }
  18991. }
  18992. // JS specific: little magic to add zero terminator to end of string
  18993. if (s.gzindex < s.gzhead.comment.length) {
  18994. val = s.gzhead.comment.charCodeAt(s.gzindex++) & 0xff;
  18995. } else {
  18996. val = 0;
  18997. }
  18998. put_byte(s, val);
  18999. } while (val !== 0);
  19000. if (s.gzhead.hcrc && s.pending > beg) {
  19001. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  19002. }
  19003. if (val === 0) {
  19004. s.status = HCRC_STATE;
  19005. }
  19006. }
  19007. else {
  19008. s.status = HCRC_STATE;
  19009. }
  19010. }
  19011. if (s.status === HCRC_STATE) {
  19012. if (s.gzhead.hcrc) {
  19013. if (s.pending + 2 > s.pending_buf_size) {
  19014. flush_pending(strm);
  19015. }
  19016. if (s.pending + 2 <= s.pending_buf_size) {
  19017. put_byte(s, strm.adler & 0xff);
  19018. put_byte(s, (strm.adler >> 8) & 0xff);
  19019. strm.adler = 0; //crc32(0L, Z_NULL, 0);
  19020. s.status = BUSY_STATE;
  19021. }
  19022. }
  19023. else {
  19024. s.status = BUSY_STATE;
  19025. }
  19026. }
  19027. //#endif
  19028. /* Flush as much pending output as possible */
  19029. if (s.pending !== 0) {
  19030. flush_pending(strm);
  19031. if (strm.avail_out === 0) {
  19032. /* Since avail_out is 0, deflate will be called again with
  19033. * more output space, but possibly with both pending and
  19034. * avail_in equal to zero. There won't be anything to do,
  19035. * but this is not an error situation so make sure we
  19036. * return OK instead of BUF_ERROR at next call of deflate:
  19037. */
  19038. s.last_flush = -1;
  19039. return Z_OK;
  19040. }
  19041. /* Make sure there is something to do and avoid duplicate consecutive
  19042. * flushes. For repeated and useless calls with Z_FINISH, we keep
  19043. * returning Z_STREAM_END instead of Z_BUF_ERROR.
  19044. */
  19045. } else if (strm.avail_in === 0 && rank(flush) <= rank(old_flush) &&
  19046. flush !== Z_FINISH) {
  19047. return err(strm, Z_BUF_ERROR);
  19048. }
  19049. /* User must not provide more input after the first FINISH: */
  19050. if (s.status === FINISH_STATE && strm.avail_in !== 0) {
  19051. return err(strm, Z_BUF_ERROR);
  19052. }
  19053. /* Start a new block or continue the current one.
  19054. */
  19055. if (strm.avail_in !== 0 || s.lookahead !== 0 ||
  19056. (flush !== Z_NO_FLUSH && s.status !== FINISH_STATE)) {
  19057. var bstate = (s.strategy === Z_HUFFMAN_ONLY) ? deflate_huff(s, flush) :
  19058. (s.strategy === Z_RLE ? deflate_rle(s, flush) :
  19059. configuration_table[s.level].func(s, flush));
  19060. if (bstate === BS_FINISH_STARTED || bstate === BS_FINISH_DONE) {
  19061. s.status = FINISH_STATE;
  19062. }
  19063. if (bstate === BS_NEED_MORE || bstate === BS_FINISH_STARTED) {
  19064. if (strm.avail_out === 0) {
  19065. s.last_flush = -1;
  19066. /* avoid BUF_ERROR next call, see above */
  19067. }
  19068. return Z_OK;
  19069. /* If flush != Z_NO_FLUSH && avail_out == 0, the next call
  19070. * of deflate should use the same flush parameter to make sure
  19071. * that the flush is complete. So we don't have to output an
  19072. * empty block here, this will be done at next call. This also
  19073. * ensures that for a very small output buffer, we emit at most
  19074. * one empty block.
  19075. */
  19076. }
  19077. if (bstate === BS_BLOCK_DONE) {
  19078. if (flush === Z_PARTIAL_FLUSH) {
  19079. trees._tr_align(s);
  19080. }
  19081. else if (flush !== Z_BLOCK) { /* FULL_FLUSH or SYNC_FLUSH */
  19082. trees._tr_stored_block(s, 0, 0, false);
  19083. /* For a full flush, this empty block will be recognized
  19084. * as a special marker by inflate_sync().
  19085. */
  19086. if (flush === Z_FULL_FLUSH) {
  19087. /*** CLEAR_HASH(s); ***/ /* forget history */
  19088. zero(s.head); // Fill with NIL (= 0);
  19089. if (s.lookahead === 0) {
  19090. s.strstart = 0;
  19091. s.block_start = 0;
  19092. s.insert = 0;
  19093. }
  19094. }
  19095. }
  19096. flush_pending(strm);
  19097. if (strm.avail_out === 0) {
  19098. s.last_flush = -1; /* avoid BUF_ERROR at next call, see above */
  19099. return Z_OK;
  19100. }
  19101. }
  19102. }
  19103. //Assert(strm->avail_out > 0, "bug2");
  19104. //if (strm.avail_out <= 0) { throw new Error("bug2");}
  19105. if (flush !== Z_FINISH) { return Z_OK; }
  19106. if (s.wrap <= 0) { return Z_STREAM_END; }
  19107. /* Write the trailer */
  19108. if (s.wrap === 2) {
  19109. put_byte(s, strm.adler & 0xff);
  19110. put_byte(s, (strm.adler >> 8) & 0xff);
  19111. put_byte(s, (strm.adler >> 16) & 0xff);
  19112. put_byte(s, (strm.adler >> 24) & 0xff);
  19113. put_byte(s, strm.total_in & 0xff);
  19114. put_byte(s, (strm.total_in >> 8) & 0xff);
  19115. put_byte(s, (strm.total_in >> 16) & 0xff);
  19116. put_byte(s, (strm.total_in >> 24) & 0xff);
  19117. }
  19118. else
  19119. {
  19120. putShortMSB(s, strm.adler >>> 16);
  19121. putShortMSB(s, strm.adler & 0xffff);
  19122. }
  19123. flush_pending(strm);
  19124. /* If avail_out is zero, the application will call deflate again
  19125. * to flush the rest.
  19126. */
  19127. if (s.wrap > 0) { s.wrap = -s.wrap; }
  19128. /* write the trailer only once! */
  19129. return s.pending !== 0 ? Z_OK : Z_STREAM_END;
  19130. }
  19131. function deflateEnd(strm) {
  19132. var status;
  19133. if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) {
  19134. return Z_STREAM_ERROR;
  19135. }
  19136. status = strm.state.status;
  19137. if (status !== INIT_STATE &&
  19138. status !== EXTRA_STATE &&
  19139. status !== NAME_STATE &&
  19140. status !== COMMENT_STATE &&
  19141. status !== HCRC_STATE &&
  19142. status !== BUSY_STATE &&
  19143. status !== FINISH_STATE
  19144. ) {
  19145. return err(strm, Z_STREAM_ERROR);
  19146. }
  19147. strm.state = null;
  19148. return status === BUSY_STATE ? err(strm, Z_DATA_ERROR) : Z_OK;
  19149. }
  19150. /* =========================================================================
  19151. * Copy the source state to the destination state
  19152. */
  19153. //function deflateCopy(dest, source) {
  19154. //
  19155. //}
  19156. exports.deflateInit = deflateInit;
  19157. exports.deflateInit2 = deflateInit2;
  19158. exports.deflateReset = deflateReset;
  19159. exports.deflateResetKeep = deflateResetKeep;
  19160. exports.deflateSetHeader = deflateSetHeader;
  19161. exports.deflate = deflate;
  19162. exports.deflateEnd = deflateEnd;
  19163. exports.deflateInfo = 'pako deflate (from Nodeca project)';
  19164. /* Not implemented
  19165. exports.deflateBound = deflateBound;
  19166. exports.deflateCopy = deflateCopy;
  19167. exports.deflateSetDictionary = deflateSetDictionary;
  19168. exports.deflateParams = deflateParams;
  19169. exports.deflatePending = deflatePending;
  19170. exports.deflatePrime = deflatePrime;
  19171. exports.deflateTune = deflateTune;
  19172. */
  19173. },{"../utils/common":65,"./adler32":67,"./crc32":69,"./messages":75,"./trees":76}],71:[function(require,module,exports){
  19174. 'use strict';
  19175. function GZheader() {
  19176. /* true if compressed data believed to be text */
  19177. this.text = 0;
  19178. /* modification time */
  19179. this.time = 0;
  19180. /* extra flags (not used when writing a gzip file) */
  19181. this.xflags = 0;
  19182. /* operating system */
  19183. this.os = 0;
  19184. /* pointer to extra field or Z_NULL if none */
  19185. this.extra = null;
  19186. /* extra field length (valid if extra != Z_NULL) */
  19187. this.extra_len = 0; // Actually, we don't need it in JS,
  19188. // but leave for few code modifications
  19189. //
  19190. // Setup limits is not necessary because in js we should not preallocate memory
  19191. // for inflate use constant limit in 65536 bytes
  19192. //
  19193. /* space at extra (only when reading header) */
  19194. // this.extra_max = 0;
  19195. /* pointer to zero-terminated file name or Z_NULL */
  19196. this.name = '';
  19197. /* space at name (only when reading header) */
  19198. // this.name_max = 0;
  19199. /* pointer to zero-terminated comment or Z_NULL */
  19200. this.comment = '';
  19201. /* space at comment (only when reading header) */
  19202. // this.comm_max = 0;
  19203. /* true if there was or will be a header crc */
  19204. this.hcrc = 0;
  19205. /* true when done reading gzip header (not used when writing a gzip file) */
  19206. this.done = false;
  19207. }
  19208. module.exports = GZheader;
  19209. },{}],72:[function(require,module,exports){
  19210. 'use strict';
  19211. // See state defs from inflate.js
  19212. var BAD = 30; /* got a data error -- remain here until reset */
  19213. var TYPE = 12; /* i: waiting for type bits, including last-flag bit */
  19214. /*
  19215. Decode literal, length, and distance codes and write out the resulting
  19216. literal and match bytes until either not enough input or output is
  19217. available, an end-of-block is encountered, or a data error is encountered.
  19218. When large enough input and output buffers are supplied to inflate(), for
  19219. example, a 16K input buffer and a 64K output buffer, more than 95% of the
  19220. inflate execution time is spent in this routine.
  19221. Entry assumptions:
  19222. state.mode === LEN
  19223. strm.avail_in >= 6
  19224. strm.avail_out >= 258
  19225. start >= strm.avail_out
  19226. state.bits < 8
  19227. On return, state.mode is one of:
  19228. LEN -- ran out of enough output space or enough available input
  19229. TYPE -- reached end of block code, inflate() to interpret next block
  19230. BAD -- error in block data
  19231. Notes:
  19232. - The maximum input bits used by a length/distance pair is 15 bits for the
  19233. length code, 5 bits for the length extra, 15 bits for the distance code,
  19234. and 13 bits for the distance extra. This totals 48 bits, or six bytes.
  19235. Therefore if strm.avail_in >= 6, then there is enough input to avoid
  19236. checking for available input while decoding.
  19237. - The maximum bytes that a single length/distance pair can output is 258
  19238. bytes, which is the maximum length that can be coded. inflate_fast()
  19239. requires strm.avail_out >= 258 for each loop to avoid checking for
  19240. output space.
  19241. */
  19242. module.exports = function inflate_fast(strm, start) {
  19243. var state;
  19244. var _in; /* local strm.input */
  19245. var last; /* have enough input while in < last */
  19246. var _out; /* local strm.output */
  19247. var beg; /* inflate()'s initial strm.output */
  19248. var end; /* while out < end, enough space available */
  19249. //#ifdef INFLATE_STRICT
  19250. var dmax; /* maximum distance from zlib header */
  19251. //#endif
  19252. var wsize; /* window size or zero if not using window */
  19253. var whave; /* valid bytes in the window */
  19254. var wnext; /* window write index */
  19255. var window; /* allocated sliding window, if wsize != 0 */
  19256. var hold; /* local strm.hold */
  19257. var bits; /* local strm.bits */
  19258. var lcode; /* local strm.lencode */
  19259. var dcode; /* local strm.distcode */
  19260. var lmask; /* mask for first level of length codes */
  19261. var dmask; /* mask for first level of distance codes */
  19262. var here; /* retrieved table entry */
  19263. var op; /* code bits, operation, extra bits, or */
  19264. /* window position, window bytes to copy */
  19265. var len; /* match length, unused bytes */
  19266. var dist; /* match distance */
  19267. var from; /* where to copy match from */
  19268. var from_source;
  19269. var input, output; // JS specific, because we have no pointers
  19270. /* copy state to local variables */
  19271. state = strm.state;
  19272. //here = state.here;
  19273. _in = strm.next_in;
  19274. input = strm.input;
  19275. last = _in + (strm.avail_in - 5);
  19276. _out = strm.next_out;
  19277. output = strm.output;
  19278. beg = _out - (start - strm.avail_out);
  19279. end = _out + (strm.avail_out - 257);
  19280. //#ifdef INFLATE_STRICT
  19281. dmax = state.dmax;
  19282. //#endif
  19283. wsize = state.wsize;
  19284. whave = state.whave;
  19285. wnext = state.wnext;
  19286. window = state.window;
  19287. hold = state.hold;
  19288. bits = state.bits;
  19289. lcode = state.lencode;
  19290. dcode = state.distcode;
  19291. lmask = (1 << state.lenbits) - 1;
  19292. dmask = (1 << state.distbits) - 1;
  19293. /* decode literals and length/distances until end-of-block or not enough
  19294. input data or output space */
  19295. top:
  19296. do {
  19297. if (bits < 15) {
  19298. hold += input[_in++] << bits;
  19299. bits += 8;
  19300. hold += input[_in++] << bits;
  19301. bits += 8;
  19302. }
  19303. here = lcode[hold & lmask];
  19304. dolen:
  19305. for (;;) { // Goto emulation
  19306. op = here >>> 24/*here.bits*/;
  19307. hold >>>= op;
  19308. bits -= op;
  19309. op = (here >>> 16) & 0xff/*here.op*/;
  19310. if (op === 0) { /* literal */
  19311. //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
  19312. // "inflate: literal '%c'\n" :
  19313. // "inflate: literal 0x%02x\n", here.val));
  19314. output[_out++] = here & 0xffff/*here.val*/;
  19315. }
  19316. else if (op & 16) { /* length base */
  19317. len = here & 0xffff/*here.val*/;
  19318. op &= 15; /* number of extra bits */
  19319. if (op) {
  19320. if (bits < op) {
  19321. hold += input[_in++] << bits;
  19322. bits += 8;
  19323. }
  19324. len += hold & ((1 << op) - 1);
  19325. hold >>>= op;
  19326. bits -= op;
  19327. }
  19328. //Tracevv((stderr, "inflate: length %u\n", len));
  19329. if (bits < 15) {
  19330. hold += input[_in++] << bits;
  19331. bits += 8;
  19332. hold += input[_in++] << bits;
  19333. bits += 8;
  19334. }
  19335. here = dcode[hold & dmask];
  19336. dodist:
  19337. for (;;) { // goto emulation
  19338. op = here >>> 24/*here.bits*/;
  19339. hold >>>= op;
  19340. bits -= op;
  19341. op = (here >>> 16) & 0xff/*here.op*/;
  19342. if (op & 16) { /* distance base */
  19343. dist = here & 0xffff/*here.val*/;
  19344. op &= 15; /* number of extra bits */
  19345. if (bits < op) {
  19346. hold += input[_in++] << bits;
  19347. bits += 8;
  19348. if (bits < op) {
  19349. hold += input[_in++] << bits;
  19350. bits += 8;
  19351. }
  19352. }
  19353. dist += hold & ((1 << op) - 1);
  19354. //#ifdef INFLATE_STRICT
  19355. if (dist > dmax) {
  19356. strm.msg = 'invalid distance too far back';
  19357. state.mode = BAD;
  19358. break top;
  19359. }
  19360. //#endif
  19361. hold >>>= op;
  19362. bits -= op;
  19363. //Tracevv((stderr, "inflate: distance %u\n", dist));
  19364. op = _out - beg; /* max distance in output */
  19365. if (dist > op) { /* see if copy from window */
  19366. op = dist - op; /* distance back in window */
  19367. if (op > whave) {
  19368. if (state.sane) {
  19369. strm.msg = 'invalid distance too far back';
  19370. state.mode = BAD;
  19371. break top;
  19372. }
  19373. // (!) This block is disabled in zlib defailts,
  19374. // don't enable it for binary compatibility
  19375. //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
  19376. // if (len <= op - whave) {
  19377. // do {
  19378. // output[_out++] = 0;
  19379. // } while (--len);
  19380. // continue top;
  19381. // }
  19382. // len -= op - whave;
  19383. // do {
  19384. // output[_out++] = 0;
  19385. // } while (--op > whave);
  19386. // if (op === 0) {
  19387. // from = _out - dist;
  19388. // do {
  19389. // output[_out++] = output[from++];
  19390. // } while (--len);
  19391. // continue top;
  19392. // }
  19393. //#endif
  19394. }
  19395. from = 0; // window index
  19396. from_source = window;
  19397. if (wnext === 0) { /* very common case */
  19398. from += wsize - op;
  19399. if (op < len) { /* some from window */
  19400. len -= op;
  19401. do {
  19402. output[_out++] = window[from++];
  19403. } while (--op);
  19404. from = _out - dist; /* rest from output */
  19405. from_source = output;
  19406. }
  19407. }
  19408. else if (wnext < op) { /* wrap around window */
  19409. from += wsize + wnext - op;
  19410. op -= wnext;
  19411. if (op < len) { /* some from end of window */
  19412. len -= op;
  19413. do {
  19414. output[_out++] = window[from++];
  19415. } while (--op);
  19416. from = 0;
  19417. if (wnext < len) { /* some from start of window */
  19418. op = wnext;
  19419. len -= op;
  19420. do {
  19421. output[_out++] = window[from++];
  19422. } while (--op);
  19423. from = _out - dist; /* rest from output */
  19424. from_source = output;
  19425. }
  19426. }
  19427. }
  19428. else { /* contiguous in window */
  19429. from += wnext - op;
  19430. if (op < len) { /* some from window */
  19431. len -= op;
  19432. do {
  19433. output[_out++] = window[from++];
  19434. } while (--op);
  19435. from = _out - dist; /* rest from output */
  19436. from_source = output;
  19437. }
  19438. }
  19439. while (len > 2) {
  19440. output[_out++] = from_source[from++];
  19441. output[_out++] = from_source[from++];
  19442. output[_out++] = from_source[from++];
  19443. len -= 3;
  19444. }
  19445. if (len) {
  19446. output[_out++] = from_source[from++];
  19447. if (len > 1) {
  19448. output[_out++] = from_source[from++];
  19449. }
  19450. }
  19451. }
  19452. else {
  19453. from = _out - dist; /* copy direct from output */
  19454. do { /* minimum length is three */
  19455. output[_out++] = output[from++];
  19456. output[_out++] = output[from++];
  19457. output[_out++] = output[from++];
  19458. len -= 3;
  19459. } while (len > 2);
  19460. if (len) {
  19461. output[_out++] = output[from++];
  19462. if (len > 1) {
  19463. output[_out++] = output[from++];
  19464. }
  19465. }
  19466. }
  19467. }
  19468. else if ((op & 64) === 0) { /* 2nd level distance code */
  19469. here = dcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
  19470. continue dodist;
  19471. }
  19472. else {
  19473. strm.msg = 'invalid distance code';
  19474. state.mode = BAD;
  19475. break top;
  19476. }
  19477. break; // need to emulate goto via "continue"
  19478. }
  19479. }
  19480. else if ((op & 64) === 0) { /* 2nd level length code */
  19481. here = lcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
  19482. continue dolen;
  19483. }
  19484. else if (op & 32) { /* end-of-block */
  19485. //Tracevv((stderr, "inflate: end of block\n"));
  19486. state.mode = TYPE;
  19487. break top;
  19488. }
  19489. else {
  19490. strm.msg = 'invalid literal/length code';
  19491. state.mode = BAD;
  19492. break top;
  19493. }
  19494. break; // need to emulate goto via "continue"
  19495. }
  19496. } while (_in < last && _out < end);
  19497. /* return unused bytes (on entry, bits < 8, so in won't go too far back) */
  19498. len = bits >> 3;
  19499. _in -= len;
  19500. bits -= len << 3;
  19501. hold &= (1 << bits) - 1;
  19502. /* update state and return */
  19503. strm.next_in = _in;
  19504. strm.next_out = _out;
  19505. strm.avail_in = (_in < last ? 5 + (last - _in) : 5 - (_in - last));
  19506. strm.avail_out = (_out < end ? 257 + (end - _out) : 257 - (_out - end));
  19507. state.hold = hold;
  19508. state.bits = bits;
  19509. return;
  19510. };
  19511. },{}],73:[function(require,module,exports){
  19512. 'use strict';
  19513. var utils = require('../utils/common');
  19514. var adler32 = require('./adler32');
  19515. var crc32 = require('./crc32');
  19516. var inflate_fast = require('./inffast');
  19517. var inflate_table = require('./inftrees');
  19518. var CODES = 0;
  19519. var LENS = 1;
  19520. var DISTS = 2;
  19521. /* Public constants ==========================================================*/
  19522. /* ===========================================================================*/
  19523. /* Allowed flush values; see deflate() and inflate() below for details */
  19524. //var Z_NO_FLUSH = 0;
  19525. //var Z_PARTIAL_FLUSH = 1;
  19526. //var Z_SYNC_FLUSH = 2;
  19527. //var Z_FULL_FLUSH = 3;
  19528. var Z_FINISH = 4;
  19529. var Z_BLOCK = 5;
  19530. var Z_TREES = 6;
  19531. /* Return codes for the compression/decompression functions. Negative values
  19532. * are errors, positive values are used for special but normal events.
  19533. */
  19534. var Z_OK = 0;
  19535. var Z_STREAM_END = 1;
  19536. var Z_NEED_DICT = 2;
  19537. //var Z_ERRNO = -1;
  19538. var Z_STREAM_ERROR = -2;
  19539. var Z_DATA_ERROR = -3;
  19540. var Z_MEM_ERROR = -4;
  19541. var Z_BUF_ERROR = -5;
  19542. //var Z_VERSION_ERROR = -6;
  19543. /* The deflate compression method */
  19544. var Z_DEFLATED = 8;
  19545. /* STATES ====================================================================*/
  19546. /* ===========================================================================*/
  19547. var HEAD = 1; /* i: waiting for magic header */
  19548. var FLAGS = 2; /* i: waiting for method and flags (gzip) */
  19549. var TIME = 3; /* i: waiting for modification time (gzip) */
  19550. var OS = 4; /* i: waiting for extra flags and operating system (gzip) */
  19551. var EXLEN = 5; /* i: waiting for extra length (gzip) */
  19552. var EXTRA = 6; /* i: waiting for extra bytes (gzip) */
  19553. var NAME = 7; /* i: waiting for end of file name (gzip) */
  19554. var COMMENT = 8; /* i: waiting for end of comment (gzip) */
  19555. var HCRC = 9; /* i: waiting for header crc (gzip) */
  19556. var DICTID = 10; /* i: waiting for dictionary check value */
  19557. var DICT = 11; /* waiting for inflateSetDictionary() call */
  19558. var TYPE = 12; /* i: waiting for type bits, including last-flag bit */
  19559. var TYPEDO = 13; /* i: same, but skip check to exit inflate on new block */
  19560. var STORED = 14; /* i: waiting for stored size (length and complement) */
  19561. var COPY_ = 15; /* i/o: same as COPY below, but only first time in */
  19562. var COPY = 16; /* i/o: waiting for input or output to copy stored block */
  19563. var TABLE = 17; /* i: waiting for dynamic block table lengths */
  19564. var LENLENS = 18; /* i: waiting for code length code lengths */
  19565. var CODELENS = 19; /* i: waiting for length/lit and distance code lengths */
  19566. var LEN_ = 20; /* i: same as LEN below, but only first time in */
  19567. var LEN = 21; /* i: waiting for length/lit/eob code */
  19568. var LENEXT = 22; /* i: waiting for length extra bits */
  19569. var DIST = 23; /* i: waiting for distance code */
  19570. var DISTEXT = 24; /* i: waiting for distance extra bits */
  19571. var MATCH = 25; /* o: waiting for output space to copy string */
  19572. var LIT = 26; /* o: waiting for output space to write literal */
  19573. var CHECK = 27; /* i: waiting for 32-bit check value */
  19574. var LENGTH = 28; /* i: waiting for 32-bit length (gzip) */
  19575. var DONE = 29; /* finished check, done -- remain here until reset */
  19576. var BAD = 30; /* got a data error -- remain here until reset */
  19577. var MEM = 31; /* got an inflate() memory error -- remain here until reset */
  19578. var SYNC = 32; /* looking for synchronization bytes to restart inflate() */
  19579. /* ===========================================================================*/
  19580. var ENOUGH_LENS = 852;
  19581. var ENOUGH_DISTS = 592;
  19582. //var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
  19583. var MAX_WBITS = 15;
  19584. /* 32K LZ77 window */
  19585. var DEF_WBITS = MAX_WBITS;
  19586. function ZSWAP32(q) {
  19587. return (((q >>> 24) & 0xff) +
  19588. ((q >>> 8) & 0xff00) +
  19589. ((q & 0xff00) << 8) +
  19590. ((q & 0xff) << 24));
  19591. }
  19592. function InflateState() {
  19593. this.mode = 0; /* current inflate mode */
  19594. this.last = false; /* true if processing last block */
  19595. this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
  19596. this.havedict = false; /* true if dictionary provided */
  19597. this.flags = 0; /* gzip header method and flags (0 if zlib) */
  19598. this.dmax = 0; /* zlib header max distance (INFLATE_STRICT) */
  19599. this.check = 0; /* protected copy of check value */
  19600. this.total = 0; /* protected copy of output count */
  19601. // TODO: may be {}
  19602. this.head = null; /* where to save gzip header information */
  19603. /* sliding window */
  19604. this.wbits = 0; /* log base 2 of requested window size */
  19605. this.wsize = 0; /* window size or zero if not using window */
  19606. this.whave = 0; /* valid bytes in the window */
  19607. this.wnext = 0; /* window write index */
  19608. this.window = null; /* allocated sliding window, if needed */
  19609. /* bit accumulator */
  19610. this.hold = 0; /* input bit accumulator */
  19611. this.bits = 0; /* number of bits in "in" */
  19612. /* for string and stored block copying */
  19613. this.length = 0; /* literal or length of data to copy */
  19614. this.offset = 0; /* distance back to copy string from */
  19615. /* for table and code decoding */
  19616. this.extra = 0; /* extra bits needed */
  19617. /* fixed and dynamic code tables */
  19618. this.lencode = null; /* starting table for length/literal codes */
  19619. this.distcode = null; /* starting table for distance codes */
  19620. this.lenbits = 0; /* index bits for lencode */
  19621. this.distbits = 0; /* index bits for distcode */
  19622. /* dynamic table building */
  19623. this.ncode = 0; /* number of code length code lengths */
  19624. this.nlen = 0; /* number of length code lengths */
  19625. this.ndist = 0; /* number of distance code lengths */
  19626. this.have = 0; /* number of code lengths in lens[] */
  19627. this.next = null; /* next available space in codes[] */
  19628. this.lens = new utils.Buf16(320); /* temporary storage for code lengths */
  19629. this.work = new utils.Buf16(288); /* work area for code table building */
  19630. /*
  19631. because we don't have pointers in js, we use lencode and distcode directly
  19632. as buffers so we don't need codes
  19633. */
  19634. //this.codes = new utils.Buf32(ENOUGH); /* space for code tables */
  19635. this.lendyn = null; /* dynamic table for length/literal codes (JS specific) */
  19636. this.distdyn = null; /* dynamic table for distance codes (JS specific) */
  19637. this.sane = 0; /* if false, allow invalid distance too far */
  19638. this.back = 0; /* bits back of last unprocessed length/lit */
  19639. this.was = 0; /* initial length of match */
  19640. }
  19641. function inflateResetKeep(strm) {
  19642. var state;
  19643. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  19644. state = strm.state;
  19645. strm.total_in = strm.total_out = state.total = 0;
  19646. strm.msg = ''; /*Z_NULL*/
  19647. if (state.wrap) { /* to support ill-conceived Java test suite */
  19648. strm.adler = state.wrap & 1;
  19649. }
  19650. state.mode = HEAD;
  19651. state.last = 0;
  19652. state.havedict = 0;
  19653. state.dmax = 32768;
  19654. state.head = null/*Z_NULL*/;
  19655. state.hold = 0;
  19656. state.bits = 0;
  19657. //state.lencode = state.distcode = state.next = state.codes;
  19658. state.lencode = state.lendyn = new utils.Buf32(ENOUGH_LENS);
  19659. state.distcode = state.distdyn = new utils.Buf32(ENOUGH_DISTS);
  19660. state.sane = 1;
  19661. state.back = -1;
  19662. //Tracev((stderr, "inflate: reset\n"));
  19663. return Z_OK;
  19664. }
  19665. function inflateReset(strm) {
  19666. var state;
  19667. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  19668. state = strm.state;
  19669. state.wsize = 0;
  19670. state.whave = 0;
  19671. state.wnext = 0;
  19672. return inflateResetKeep(strm);
  19673. }
  19674. function inflateReset2(strm, windowBits) {
  19675. var wrap;
  19676. var state;
  19677. /* get the state */
  19678. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  19679. state = strm.state;
  19680. /* extract wrap request from windowBits parameter */
  19681. if (windowBits < 0) {
  19682. wrap = 0;
  19683. windowBits = -windowBits;
  19684. }
  19685. else {
  19686. wrap = (windowBits >> 4) + 1;
  19687. if (windowBits < 48) {
  19688. windowBits &= 15;
  19689. }
  19690. }
  19691. /* set number of window bits, free window if different */
  19692. if (windowBits && (windowBits < 8 || windowBits > 15)) {
  19693. return Z_STREAM_ERROR;
  19694. }
  19695. if (state.window !== null && state.wbits !== windowBits) {
  19696. state.window = null;
  19697. }
  19698. /* update state and reset the rest of it */
  19699. state.wrap = wrap;
  19700. state.wbits = windowBits;
  19701. return inflateReset(strm);
  19702. }
  19703. function inflateInit2(strm, windowBits) {
  19704. var ret;
  19705. var state;
  19706. if (!strm) { return Z_STREAM_ERROR; }
  19707. //strm.msg = Z_NULL; /* in case we return an error */
  19708. state = new InflateState();
  19709. //if (state === Z_NULL) return Z_MEM_ERROR;
  19710. //Tracev((stderr, "inflate: allocated\n"));
  19711. strm.state = state;
  19712. state.window = null/*Z_NULL*/;
  19713. ret = inflateReset2(strm, windowBits);
  19714. if (ret !== Z_OK) {
  19715. strm.state = null/*Z_NULL*/;
  19716. }
  19717. return ret;
  19718. }
  19719. function inflateInit(strm) {
  19720. return inflateInit2(strm, DEF_WBITS);
  19721. }
  19722. /*
  19723. Return state with length and distance decoding tables and index sizes set to
  19724. fixed code decoding. Normally this returns fixed tables from inffixed.h.
  19725. If BUILDFIXED is defined, then instead this routine builds the tables the
  19726. first time it's called, and returns those tables the first time and
  19727. thereafter. This reduces the size of the code by about 2K bytes, in
  19728. exchange for a little execution time. However, BUILDFIXED should not be
  19729. used for threaded applications, since the rewriting of the tables and virgin
  19730. may not be thread-safe.
  19731. */
  19732. var virgin = true;
  19733. var lenfix, distfix; // We have no pointers in JS, so keep tables separate
  19734. function fixedtables(state) {
  19735. /* build fixed huffman tables if first call (may not be thread safe) */
  19736. if (virgin) {
  19737. var sym;
  19738. lenfix = new utils.Buf32(512);
  19739. distfix = new utils.Buf32(32);
  19740. /* literal/length table */
  19741. sym = 0;
  19742. while (sym < 144) { state.lens[sym++] = 8; }
  19743. while (sym < 256) { state.lens[sym++] = 9; }
  19744. while (sym < 280) { state.lens[sym++] = 7; }
  19745. while (sym < 288) { state.lens[sym++] = 8; }
  19746. inflate_table(LENS, state.lens, 0, 288, lenfix, 0, state.work, {bits: 9});
  19747. /* distance table */
  19748. sym = 0;
  19749. while (sym < 32) { state.lens[sym++] = 5; }
  19750. inflate_table(DISTS, state.lens, 0, 32, distfix, 0, state.work, {bits: 5});
  19751. /* do this just once */
  19752. virgin = false;
  19753. }
  19754. state.lencode = lenfix;
  19755. state.lenbits = 9;
  19756. state.distcode = distfix;
  19757. state.distbits = 5;
  19758. }
  19759. /*
  19760. Update the window with the last wsize (normally 32K) bytes written before
  19761. returning. If window does not exist yet, create it. This is only called
  19762. when a window is already in use, or when output has been written during this
  19763. inflate call, but the end of the deflate stream has not been reached yet.
  19764. It is also called to create a window for dictionary data when a dictionary
  19765. is loaded.
  19766. Providing output buffers larger than 32K to inflate() should provide a speed
  19767. advantage, since only the last 32K of output is copied to the sliding window
  19768. upon return from inflate(), and since all distances after the first 32K of
  19769. output will fall in the output data, making match copies simpler and faster.
  19770. The advantage may be dependent on the size of the processor's data caches.
  19771. */
  19772. function updatewindow(strm, src, end, copy) {
  19773. var dist;
  19774. var state = strm.state;
  19775. /* if it hasn't been done already, allocate space for the window */
  19776. if (state.window === null) {
  19777. state.wsize = 1 << state.wbits;
  19778. state.wnext = 0;
  19779. state.whave = 0;
  19780. state.window = new utils.Buf8(state.wsize);
  19781. }
  19782. /* copy state->wsize or less output bytes into the circular window */
  19783. if (copy >= state.wsize) {
  19784. utils.arraySet(state.window,src, end - state.wsize, state.wsize, 0);
  19785. state.wnext = 0;
  19786. state.whave = state.wsize;
  19787. }
  19788. else {
  19789. dist = state.wsize - state.wnext;
  19790. if (dist > copy) {
  19791. dist = copy;
  19792. }
  19793. //zmemcpy(state->window + state->wnext, end - copy, dist);
  19794. utils.arraySet(state.window,src, end - copy, dist, state.wnext);
  19795. copy -= dist;
  19796. if (copy) {
  19797. //zmemcpy(state->window, end - copy, copy);
  19798. utils.arraySet(state.window,src, end - copy, copy, 0);
  19799. state.wnext = copy;
  19800. state.whave = state.wsize;
  19801. }
  19802. else {
  19803. state.wnext += dist;
  19804. if (state.wnext === state.wsize) { state.wnext = 0; }
  19805. if (state.whave < state.wsize) { state.whave += dist; }
  19806. }
  19807. }
  19808. return 0;
  19809. }
  19810. function inflate(strm, flush) {
  19811. var state;
  19812. var input, output; // input/output buffers
  19813. var next; /* next input INDEX */
  19814. var put; /* next output INDEX */
  19815. var have, left; /* available input and output */
  19816. var hold; /* bit buffer */
  19817. var bits; /* bits in bit buffer */
  19818. var _in, _out; /* save starting available input and output */
  19819. var copy; /* number of stored or match bytes to copy */
  19820. var from; /* where to copy match bytes from */
  19821. var from_source;
  19822. var here = 0; /* current decoding table entry */
  19823. var here_bits, here_op, here_val; // paked "here" denormalized (JS specific)
  19824. //var last; /* parent table entry */
  19825. var last_bits, last_op, last_val; // paked "last" denormalized (JS specific)
  19826. var len; /* length to copy for repeats, bits to drop */
  19827. var ret; /* return code */
  19828. var hbuf = new utils.Buf8(4); /* buffer for gzip header crc calculation */
  19829. var opts;
  19830. var n; // temporary var for NEED_BITS
  19831. var order = /* permutation of code lengths */
  19832. [16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15];
  19833. if (!strm || !strm.state || !strm.output ||
  19834. (!strm.input && strm.avail_in !== 0)) {
  19835. return Z_STREAM_ERROR;
  19836. }
  19837. state = strm.state;
  19838. if (state.mode === TYPE) { state.mode = TYPEDO; } /* skip check */
  19839. //--- LOAD() ---
  19840. put = strm.next_out;
  19841. output = strm.output;
  19842. left = strm.avail_out;
  19843. next = strm.next_in;
  19844. input = strm.input;
  19845. have = strm.avail_in;
  19846. hold = state.hold;
  19847. bits = state.bits;
  19848. //---
  19849. _in = have;
  19850. _out = left;
  19851. ret = Z_OK;
  19852. inf_leave: // goto emulation
  19853. for (;;) {
  19854. switch (state.mode) {
  19855. case HEAD:
  19856. if (state.wrap === 0) {
  19857. state.mode = TYPEDO;
  19858. break;
  19859. }
  19860. //=== NEEDBITS(16);
  19861. while (bits < 16) {
  19862. if (have === 0) { break inf_leave; }
  19863. have--;
  19864. hold += input[next++] << bits;
  19865. bits += 8;
  19866. }
  19867. //===//
  19868. if ((state.wrap & 2) && hold === 0x8b1f) { /* gzip header */
  19869. state.check = 0/*crc32(0L, Z_NULL, 0)*/;
  19870. //=== CRC2(state.check, hold);
  19871. hbuf[0] = hold & 0xff;
  19872. hbuf[1] = (hold >>> 8) & 0xff;
  19873. state.check = crc32(state.check, hbuf, 2, 0);
  19874. //===//
  19875. //=== INITBITS();
  19876. hold = 0;
  19877. bits = 0;
  19878. //===//
  19879. state.mode = FLAGS;
  19880. break;
  19881. }
  19882. state.flags = 0; /* expect zlib header */
  19883. if (state.head) {
  19884. state.head.done = false;
  19885. }
  19886. if (!(state.wrap & 1) || /* check if zlib header allowed */
  19887. (((hold & 0xff)/*BITS(8)*/ << 8) + (hold >> 8)) % 31) {
  19888. strm.msg = 'incorrect header check';
  19889. state.mode = BAD;
  19890. break;
  19891. }
  19892. if ((hold & 0x0f)/*BITS(4)*/ !== Z_DEFLATED) {
  19893. strm.msg = 'unknown compression method';
  19894. state.mode = BAD;
  19895. break;
  19896. }
  19897. //--- DROPBITS(4) ---//
  19898. hold >>>= 4;
  19899. bits -= 4;
  19900. //---//
  19901. len = (hold & 0x0f)/*BITS(4)*/ + 8;
  19902. if (state.wbits === 0) {
  19903. state.wbits = len;
  19904. }
  19905. else if (len > state.wbits) {
  19906. strm.msg = 'invalid window size';
  19907. state.mode = BAD;
  19908. break;
  19909. }
  19910. state.dmax = 1 << len;
  19911. //Tracev((stderr, "inflate: zlib header ok\n"));
  19912. strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
  19913. state.mode = hold & 0x200 ? DICTID : TYPE;
  19914. //=== INITBITS();
  19915. hold = 0;
  19916. bits = 0;
  19917. //===//
  19918. break;
  19919. case FLAGS:
  19920. //=== NEEDBITS(16); */
  19921. while (bits < 16) {
  19922. if (have === 0) { break inf_leave; }
  19923. have--;
  19924. hold += input[next++] << bits;
  19925. bits += 8;
  19926. }
  19927. //===//
  19928. state.flags = hold;
  19929. if ((state.flags & 0xff) !== Z_DEFLATED) {
  19930. strm.msg = 'unknown compression method';
  19931. state.mode = BAD;
  19932. break;
  19933. }
  19934. if (state.flags & 0xe000) {
  19935. strm.msg = 'unknown header flags set';
  19936. state.mode = BAD;
  19937. break;
  19938. }
  19939. if (state.head) {
  19940. state.head.text = ((hold >> 8) & 1);
  19941. }
  19942. if (state.flags & 0x0200) {
  19943. //=== CRC2(state.check, hold);
  19944. hbuf[0] = hold & 0xff;
  19945. hbuf[1] = (hold >>> 8) & 0xff;
  19946. state.check = crc32(state.check, hbuf, 2, 0);
  19947. //===//
  19948. }
  19949. //=== INITBITS();
  19950. hold = 0;
  19951. bits = 0;
  19952. //===//
  19953. state.mode = TIME;
  19954. /* falls through */
  19955. case TIME:
  19956. //=== NEEDBITS(32); */
  19957. while (bits < 32) {
  19958. if (have === 0) { break inf_leave; }
  19959. have--;
  19960. hold += input[next++] << bits;
  19961. bits += 8;
  19962. }
  19963. //===//
  19964. if (state.head) {
  19965. state.head.time = hold;
  19966. }
  19967. if (state.flags & 0x0200) {
  19968. //=== CRC4(state.check, hold)
  19969. hbuf[0] = hold & 0xff;
  19970. hbuf[1] = (hold >>> 8) & 0xff;
  19971. hbuf[2] = (hold >>> 16) & 0xff;
  19972. hbuf[3] = (hold >>> 24) & 0xff;
  19973. state.check = crc32(state.check, hbuf, 4, 0);
  19974. //===
  19975. }
  19976. //=== INITBITS();
  19977. hold = 0;
  19978. bits = 0;
  19979. //===//
  19980. state.mode = OS;
  19981. /* falls through */
  19982. case OS:
  19983. //=== NEEDBITS(16); */
  19984. while (bits < 16) {
  19985. if (have === 0) { break inf_leave; }
  19986. have--;
  19987. hold += input[next++] << bits;
  19988. bits += 8;
  19989. }
  19990. //===//
  19991. if (state.head) {
  19992. state.head.xflags = (hold & 0xff);
  19993. state.head.os = (hold >> 8);
  19994. }
  19995. if (state.flags & 0x0200) {
  19996. //=== CRC2(state.check, hold);
  19997. hbuf[0] = hold & 0xff;
  19998. hbuf[1] = (hold >>> 8) & 0xff;
  19999. state.check = crc32(state.check, hbuf, 2, 0);
  20000. //===//
  20001. }
  20002. //=== INITBITS();
  20003. hold = 0;
  20004. bits = 0;
  20005. //===//
  20006. state.mode = EXLEN;
  20007. /* falls through */
  20008. case EXLEN:
  20009. if (state.flags & 0x0400) {
  20010. //=== NEEDBITS(16); */
  20011. while (bits < 16) {
  20012. if (have === 0) { break inf_leave; }
  20013. have--;
  20014. hold += input[next++] << bits;
  20015. bits += 8;
  20016. }
  20017. //===//
  20018. state.length = hold;
  20019. if (state.head) {
  20020. state.head.extra_len = hold;
  20021. }
  20022. if (state.flags & 0x0200) {
  20023. //=== CRC2(state.check, hold);
  20024. hbuf[0] = hold & 0xff;
  20025. hbuf[1] = (hold >>> 8) & 0xff;
  20026. state.check = crc32(state.check, hbuf, 2, 0);
  20027. //===//
  20028. }
  20029. //=== INITBITS();
  20030. hold = 0;
  20031. bits = 0;
  20032. //===//
  20033. }
  20034. else if (state.head) {
  20035. state.head.extra = null/*Z_NULL*/;
  20036. }
  20037. state.mode = EXTRA;
  20038. /* falls through */
  20039. case EXTRA:
  20040. if (state.flags & 0x0400) {
  20041. copy = state.length;
  20042. if (copy > have) { copy = have; }
  20043. if (copy) {
  20044. if (state.head) {
  20045. len = state.head.extra_len - state.length;
  20046. if (!state.head.extra) {
  20047. // Use untyped array for more conveniend processing later
  20048. state.head.extra = new Array(state.head.extra_len);
  20049. }
  20050. utils.arraySet(
  20051. state.head.extra,
  20052. input,
  20053. next,
  20054. // extra field is limited to 65536 bytes
  20055. // - no need for additional size check
  20056. copy,
  20057. /*len + copy > state.head.extra_max - len ? state.head.extra_max : copy,*/
  20058. len
  20059. );
  20060. //zmemcpy(state.head.extra + len, next,
  20061. // len + copy > state.head.extra_max ?
  20062. // state.head.extra_max - len : copy);
  20063. }
  20064. if (state.flags & 0x0200) {
  20065. state.check = crc32(state.check, input, copy, next);
  20066. }
  20067. have -= copy;
  20068. next += copy;
  20069. state.length -= copy;
  20070. }
  20071. if (state.length) { break inf_leave; }
  20072. }
  20073. state.length = 0;
  20074. state.mode = NAME;
  20075. /* falls through */
  20076. case NAME:
  20077. if (state.flags & 0x0800) {
  20078. if (have === 0) { break inf_leave; }
  20079. copy = 0;
  20080. do {
  20081. // TODO: 2 or 1 bytes?
  20082. len = input[next + copy++];
  20083. /* use constant limit because in js we should not preallocate memory */
  20084. if (state.head && len &&
  20085. (state.length < 65536 /*state.head.name_max*/)) {
  20086. state.head.name += String.fromCharCode(len);
  20087. }
  20088. } while (len && copy < have);
  20089. if (state.flags & 0x0200) {
  20090. state.check = crc32(state.check, input, copy, next);
  20091. }
  20092. have -= copy;
  20093. next += copy;
  20094. if (len) { break inf_leave; }
  20095. }
  20096. else if (state.head) {
  20097. state.head.name = null;
  20098. }
  20099. state.length = 0;
  20100. state.mode = COMMENT;
  20101. /* falls through */
  20102. case COMMENT:
  20103. if (state.flags & 0x1000) {
  20104. if (have === 0) { break inf_leave; }
  20105. copy = 0;
  20106. do {
  20107. len = input[next + copy++];
  20108. /* use constant limit because in js we should not preallocate memory */
  20109. if (state.head && len &&
  20110. (state.length < 65536 /*state.head.comm_max*/)) {
  20111. state.head.comment += String.fromCharCode(len);
  20112. }
  20113. } while (len && copy < have);
  20114. if (state.flags & 0x0200) {
  20115. state.check = crc32(state.check, input, copy, next);
  20116. }
  20117. have -= copy;
  20118. next += copy;
  20119. if (len) { break inf_leave; }
  20120. }
  20121. else if (state.head) {
  20122. state.head.comment = null;
  20123. }
  20124. state.mode = HCRC;
  20125. /* falls through */
  20126. case HCRC:
  20127. if (state.flags & 0x0200) {
  20128. //=== NEEDBITS(16); */
  20129. while (bits < 16) {
  20130. if (have === 0) { break inf_leave; }
  20131. have--;
  20132. hold += input[next++] << bits;
  20133. bits += 8;
  20134. }
  20135. //===//
  20136. if (hold !== (state.check & 0xffff)) {
  20137. strm.msg = 'header crc mismatch';
  20138. state.mode = BAD;
  20139. break;
  20140. }
  20141. //=== INITBITS();
  20142. hold = 0;
  20143. bits = 0;
  20144. //===//
  20145. }
  20146. if (state.head) {
  20147. state.head.hcrc = ((state.flags >> 9) & 1);
  20148. state.head.done = true;
  20149. }
  20150. strm.adler = state.check = 0 /*crc32(0L, Z_NULL, 0)*/;
  20151. state.mode = TYPE;
  20152. break;
  20153. case DICTID:
  20154. //=== NEEDBITS(32); */
  20155. while (bits < 32) {
  20156. if (have === 0) { break inf_leave; }
  20157. have--;
  20158. hold += input[next++] << bits;
  20159. bits += 8;
  20160. }
  20161. //===//
  20162. strm.adler = state.check = ZSWAP32(hold);
  20163. //=== INITBITS();
  20164. hold = 0;
  20165. bits = 0;
  20166. //===//
  20167. state.mode = DICT;
  20168. /* falls through */
  20169. case DICT:
  20170. if (state.havedict === 0) {
  20171. //--- RESTORE() ---
  20172. strm.next_out = put;
  20173. strm.avail_out = left;
  20174. strm.next_in = next;
  20175. strm.avail_in = have;
  20176. state.hold = hold;
  20177. state.bits = bits;
  20178. //---
  20179. return Z_NEED_DICT;
  20180. }
  20181. strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
  20182. state.mode = TYPE;
  20183. /* falls through */
  20184. case TYPE:
  20185. if (flush === Z_BLOCK || flush === Z_TREES) { break inf_leave; }
  20186. /* falls through */
  20187. case TYPEDO:
  20188. if (state.last) {
  20189. //--- BYTEBITS() ---//
  20190. hold >>>= bits & 7;
  20191. bits -= bits & 7;
  20192. //---//
  20193. state.mode = CHECK;
  20194. break;
  20195. }
  20196. //=== NEEDBITS(3); */
  20197. while (bits < 3) {
  20198. if (have === 0) { break inf_leave; }
  20199. have--;
  20200. hold += input[next++] << bits;
  20201. bits += 8;
  20202. }
  20203. //===//
  20204. state.last = (hold & 0x01)/*BITS(1)*/;
  20205. //--- DROPBITS(1) ---//
  20206. hold >>>= 1;
  20207. bits -= 1;
  20208. //---//
  20209. switch ((hold & 0x03)/*BITS(2)*/) {
  20210. case 0: /* stored block */
  20211. //Tracev((stderr, "inflate: stored block%s\n",
  20212. // state.last ? " (last)" : ""));
  20213. state.mode = STORED;
  20214. break;
  20215. case 1: /* fixed block */
  20216. fixedtables(state);
  20217. //Tracev((stderr, "inflate: fixed codes block%s\n",
  20218. // state.last ? " (last)" : ""));
  20219. state.mode = LEN_; /* decode codes */
  20220. if (flush === Z_TREES) {
  20221. //--- DROPBITS(2) ---//
  20222. hold >>>= 2;
  20223. bits -= 2;
  20224. //---//
  20225. break inf_leave;
  20226. }
  20227. break;
  20228. case 2: /* dynamic block */
  20229. //Tracev((stderr, "inflate: dynamic codes block%s\n",
  20230. // state.last ? " (last)" : ""));
  20231. state.mode = TABLE;
  20232. break;
  20233. case 3:
  20234. strm.msg = 'invalid block type';
  20235. state.mode = BAD;
  20236. }
  20237. //--- DROPBITS(2) ---//
  20238. hold >>>= 2;
  20239. bits -= 2;
  20240. //---//
  20241. break;
  20242. case STORED:
  20243. //--- BYTEBITS() ---// /* go to byte boundary */
  20244. hold >>>= bits & 7;
  20245. bits -= bits & 7;
  20246. //---//
  20247. //=== NEEDBITS(32); */
  20248. while (bits < 32) {
  20249. if (have === 0) { break inf_leave; }
  20250. have--;
  20251. hold += input[next++] << bits;
  20252. bits += 8;
  20253. }
  20254. //===//
  20255. if ((hold & 0xffff) !== ((hold >>> 16) ^ 0xffff)) {
  20256. strm.msg = 'invalid stored block lengths';
  20257. state.mode = BAD;
  20258. break;
  20259. }
  20260. state.length = hold & 0xffff;
  20261. //Tracev((stderr, "inflate: stored length %u\n",
  20262. // state.length));
  20263. //=== INITBITS();
  20264. hold = 0;
  20265. bits = 0;
  20266. //===//
  20267. state.mode = COPY_;
  20268. if (flush === Z_TREES) { break inf_leave; }
  20269. /* falls through */
  20270. case COPY_:
  20271. state.mode = COPY;
  20272. /* falls through */
  20273. case COPY:
  20274. copy = state.length;
  20275. if (copy) {
  20276. if (copy > have) { copy = have; }
  20277. if (copy > left) { copy = left; }
  20278. if (copy === 0) { break inf_leave; }
  20279. //--- zmemcpy(put, next, copy); ---
  20280. utils.arraySet(output, input, next, copy, put);
  20281. //---//
  20282. have -= copy;
  20283. next += copy;
  20284. left -= copy;
  20285. put += copy;
  20286. state.length -= copy;
  20287. break;
  20288. }
  20289. //Tracev((stderr, "inflate: stored end\n"));
  20290. state.mode = TYPE;
  20291. break;
  20292. case TABLE:
  20293. //=== NEEDBITS(14); */
  20294. while (bits < 14) {
  20295. if (have === 0) { break inf_leave; }
  20296. have--;
  20297. hold += input[next++] << bits;
  20298. bits += 8;
  20299. }
  20300. //===//
  20301. state.nlen = (hold & 0x1f)/*BITS(5)*/ + 257;
  20302. //--- DROPBITS(5) ---//
  20303. hold >>>= 5;
  20304. bits -= 5;
  20305. //---//
  20306. state.ndist = (hold & 0x1f)/*BITS(5)*/ + 1;
  20307. //--- DROPBITS(5) ---//
  20308. hold >>>= 5;
  20309. bits -= 5;
  20310. //---//
  20311. state.ncode = (hold & 0x0f)/*BITS(4)*/ + 4;
  20312. //--- DROPBITS(4) ---//
  20313. hold >>>= 4;
  20314. bits -= 4;
  20315. //---//
  20316. //#ifndef PKZIP_BUG_WORKAROUND
  20317. if (state.nlen > 286 || state.ndist > 30) {
  20318. strm.msg = 'too many length or distance symbols';
  20319. state.mode = BAD;
  20320. break;
  20321. }
  20322. //#endif
  20323. //Tracev((stderr, "inflate: table sizes ok\n"));
  20324. state.have = 0;
  20325. state.mode = LENLENS;
  20326. /* falls through */
  20327. case LENLENS:
  20328. while (state.have < state.ncode) {
  20329. //=== NEEDBITS(3);
  20330. while (bits < 3) {
  20331. if (have === 0) { break inf_leave; }
  20332. have--;
  20333. hold += input[next++] << bits;
  20334. bits += 8;
  20335. }
  20336. //===//
  20337. state.lens[order[state.have++]] = (hold & 0x07);//BITS(3);
  20338. //--- DROPBITS(3) ---//
  20339. hold >>>= 3;
  20340. bits -= 3;
  20341. //---//
  20342. }
  20343. while (state.have < 19) {
  20344. state.lens[order[state.have++]] = 0;
  20345. }
  20346. // We have separate tables & no pointers. 2 commented lines below not needed.
  20347. //state.next = state.codes;
  20348. //state.lencode = state.next;
  20349. // Switch to use dynamic table
  20350. state.lencode = state.lendyn;
  20351. state.lenbits = 7;
  20352. opts = {bits: state.lenbits};
  20353. ret = inflate_table(CODES, state.lens, 0, 19, state.lencode, 0, state.work, opts);
  20354. state.lenbits = opts.bits;
  20355. if (ret) {
  20356. strm.msg = 'invalid code lengths set';
  20357. state.mode = BAD;
  20358. break;
  20359. }
  20360. //Tracev((stderr, "inflate: code lengths ok\n"));
  20361. state.have = 0;
  20362. state.mode = CODELENS;
  20363. /* falls through */
  20364. case CODELENS:
  20365. while (state.have < state.nlen + state.ndist) {
  20366. for (;;) {
  20367. here = state.lencode[hold & ((1 << state.lenbits) - 1)];/*BITS(state.lenbits)*/
  20368. here_bits = here >>> 24;
  20369. here_op = (here >>> 16) & 0xff;
  20370. here_val = here & 0xffff;
  20371. if ((here_bits) <= bits) { break; }
  20372. //--- PULLBYTE() ---//
  20373. if (have === 0) { break inf_leave; }
  20374. have--;
  20375. hold += input[next++] << bits;
  20376. bits += 8;
  20377. //---//
  20378. }
  20379. if (here_val < 16) {
  20380. //--- DROPBITS(here.bits) ---//
  20381. hold >>>= here_bits;
  20382. bits -= here_bits;
  20383. //---//
  20384. state.lens[state.have++] = here_val;
  20385. }
  20386. else {
  20387. if (here_val === 16) {
  20388. //=== NEEDBITS(here.bits + 2);
  20389. n = here_bits + 2;
  20390. while (bits < n) {
  20391. if (have === 0) { break inf_leave; }
  20392. have--;
  20393. hold += input[next++] << bits;
  20394. bits += 8;
  20395. }
  20396. //===//
  20397. //--- DROPBITS(here.bits) ---//
  20398. hold >>>= here_bits;
  20399. bits -= here_bits;
  20400. //---//
  20401. if (state.have === 0) {
  20402. strm.msg = 'invalid bit length repeat';
  20403. state.mode = BAD;
  20404. break;
  20405. }
  20406. len = state.lens[state.have - 1];
  20407. copy = 3 + (hold & 0x03);//BITS(2);
  20408. //--- DROPBITS(2) ---//
  20409. hold >>>= 2;
  20410. bits -= 2;
  20411. //---//
  20412. }
  20413. else if (here_val === 17) {
  20414. //=== NEEDBITS(here.bits + 3);
  20415. n = here_bits + 3;
  20416. while (bits < n) {
  20417. if (have === 0) { break inf_leave; }
  20418. have--;
  20419. hold += input[next++] << bits;
  20420. bits += 8;
  20421. }
  20422. //===//
  20423. //--- DROPBITS(here.bits) ---//
  20424. hold >>>= here_bits;
  20425. bits -= here_bits;
  20426. //---//
  20427. len = 0;
  20428. copy = 3 + (hold & 0x07);//BITS(3);
  20429. //--- DROPBITS(3) ---//
  20430. hold >>>= 3;
  20431. bits -= 3;
  20432. //---//
  20433. }
  20434. else {
  20435. //=== NEEDBITS(here.bits + 7);
  20436. n = here_bits + 7;
  20437. while (bits < n) {
  20438. if (have === 0) { break inf_leave; }
  20439. have--;
  20440. hold += input[next++] << bits;
  20441. bits += 8;
  20442. }
  20443. //===//
  20444. //--- DROPBITS(here.bits) ---//
  20445. hold >>>= here_bits;
  20446. bits -= here_bits;
  20447. //---//
  20448. len = 0;
  20449. copy = 11 + (hold & 0x7f);//BITS(7);
  20450. //--- DROPBITS(7) ---//
  20451. hold >>>= 7;
  20452. bits -= 7;
  20453. //---//
  20454. }
  20455. if (state.have + copy > state.nlen + state.ndist) {
  20456. strm.msg = 'invalid bit length repeat';
  20457. state.mode = BAD;
  20458. break;
  20459. }
  20460. while (copy--) {
  20461. state.lens[state.have++] = len;
  20462. }
  20463. }
  20464. }
  20465. /* handle error breaks in while */
  20466. if (state.mode === BAD) { break; }
  20467. /* check for end-of-block code (better have one) */
  20468. if (state.lens[256] === 0) {
  20469. strm.msg = 'invalid code -- missing end-of-block';
  20470. state.mode = BAD;
  20471. break;
  20472. }
  20473. /* build code tables -- note: do not change the lenbits or distbits
  20474. values here (9 and 6) without reading the comments in inftrees.h
  20475. concerning the ENOUGH constants, which depend on those values */
  20476. state.lenbits = 9;
  20477. opts = {bits: state.lenbits};
  20478. ret = inflate_table(LENS, state.lens, 0, state.nlen, state.lencode, 0, state.work, opts);
  20479. // We have separate tables & no pointers. 2 commented lines below not needed.
  20480. // state.next_index = opts.table_index;
  20481. state.lenbits = opts.bits;
  20482. // state.lencode = state.next;
  20483. if (ret) {
  20484. strm.msg = 'invalid literal/lengths set';
  20485. state.mode = BAD;
  20486. break;
  20487. }
  20488. state.distbits = 6;
  20489. //state.distcode.copy(state.codes);
  20490. // Switch to use dynamic table
  20491. state.distcode = state.distdyn;
  20492. opts = {bits: state.distbits};
  20493. ret = inflate_table(DISTS, state.lens, state.nlen, state.ndist, state.distcode, 0, state.work, opts);
  20494. // We have separate tables & no pointers. 2 commented lines below not needed.
  20495. // state.next_index = opts.table_index;
  20496. state.distbits = opts.bits;
  20497. // state.distcode = state.next;
  20498. if (ret) {
  20499. strm.msg = 'invalid distances set';
  20500. state.mode = BAD;
  20501. break;
  20502. }
  20503. //Tracev((stderr, 'inflate: codes ok\n'));
  20504. state.mode = LEN_;
  20505. if (flush === Z_TREES) { break inf_leave; }
  20506. /* falls through */
  20507. case LEN_:
  20508. state.mode = LEN;
  20509. /* falls through */
  20510. case LEN:
  20511. if (have >= 6 && left >= 258) {
  20512. //--- RESTORE() ---
  20513. strm.next_out = put;
  20514. strm.avail_out = left;
  20515. strm.next_in = next;
  20516. strm.avail_in = have;
  20517. state.hold = hold;
  20518. state.bits = bits;
  20519. //---
  20520. inflate_fast(strm, _out);
  20521. //--- LOAD() ---
  20522. put = strm.next_out;
  20523. output = strm.output;
  20524. left = strm.avail_out;
  20525. next = strm.next_in;
  20526. input = strm.input;
  20527. have = strm.avail_in;
  20528. hold = state.hold;
  20529. bits = state.bits;
  20530. //---
  20531. if (state.mode === TYPE) {
  20532. state.back = -1;
  20533. }
  20534. break;
  20535. }
  20536. state.back = 0;
  20537. for (;;) {
  20538. here = state.lencode[hold & ((1 << state.lenbits) -1)]; /*BITS(state.lenbits)*/
  20539. here_bits = here >>> 24;
  20540. here_op = (here >>> 16) & 0xff;
  20541. here_val = here & 0xffff;
  20542. if (here_bits <= bits) { break; }
  20543. //--- PULLBYTE() ---//
  20544. if (have === 0) { break inf_leave; }
  20545. have--;
  20546. hold += input[next++] << bits;
  20547. bits += 8;
  20548. //---//
  20549. }
  20550. if (here_op && (here_op & 0xf0) === 0) {
  20551. last_bits = here_bits;
  20552. last_op = here_op;
  20553. last_val = here_val;
  20554. for (;;) {
  20555. here = state.lencode[last_val +
  20556. ((hold & ((1 << (last_bits + last_op)) -1))/*BITS(last.bits + last.op)*/ >> last_bits)];
  20557. here_bits = here >>> 24;
  20558. here_op = (here >>> 16) & 0xff;
  20559. here_val = here & 0xffff;
  20560. if ((last_bits + here_bits) <= bits) { break; }
  20561. //--- PULLBYTE() ---//
  20562. if (have === 0) { break inf_leave; }
  20563. have--;
  20564. hold += input[next++] << bits;
  20565. bits += 8;
  20566. //---//
  20567. }
  20568. //--- DROPBITS(last.bits) ---//
  20569. hold >>>= last_bits;
  20570. bits -= last_bits;
  20571. //---//
  20572. state.back += last_bits;
  20573. }
  20574. //--- DROPBITS(here.bits) ---//
  20575. hold >>>= here_bits;
  20576. bits -= here_bits;
  20577. //---//
  20578. state.back += here_bits;
  20579. state.length = here_val;
  20580. if (here_op === 0) {
  20581. //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
  20582. // "inflate: literal '%c'\n" :
  20583. // "inflate: literal 0x%02x\n", here.val));
  20584. state.mode = LIT;
  20585. break;
  20586. }
  20587. if (here_op & 32) {
  20588. //Tracevv((stderr, "inflate: end of block\n"));
  20589. state.back = -1;
  20590. state.mode = TYPE;
  20591. break;
  20592. }
  20593. if (here_op & 64) {
  20594. strm.msg = 'invalid literal/length code';
  20595. state.mode = BAD;
  20596. break;
  20597. }
  20598. state.extra = here_op & 15;
  20599. state.mode = LENEXT;
  20600. /* falls through */
  20601. case LENEXT:
  20602. if (state.extra) {
  20603. //=== NEEDBITS(state.extra);
  20604. n = state.extra;
  20605. while (bits < n) {
  20606. if (have === 0) { break inf_leave; }
  20607. have--;
  20608. hold += input[next++] << bits;
  20609. bits += 8;
  20610. }
  20611. //===//
  20612. state.length += hold & ((1 << state.extra) -1)/*BITS(state.extra)*/;
  20613. //--- DROPBITS(state.extra) ---//
  20614. hold >>>= state.extra;
  20615. bits -= state.extra;
  20616. //---//
  20617. state.back += state.extra;
  20618. }
  20619. //Tracevv((stderr, "inflate: length %u\n", state.length));
  20620. state.was = state.length;
  20621. state.mode = DIST;
  20622. /* falls through */
  20623. case DIST:
  20624. for (;;) {
  20625. here = state.distcode[hold & ((1 << state.distbits) -1)];/*BITS(state.distbits)*/
  20626. here_bits = here >>> 24;
  20627. here_op = (here >>> 16) & 0xff;
  20628. here_val = here & 0xffff;
  20629. if ((here_bits) <= bits) { break; }
  20630. //--- PULLBYTE() ---//
  20631. if (have === 0) { break inf_leave; }
  20632. have--;
  20633. hold += input[next++] << bits;
  20634. bits += 8;
  20635. //---//
  20636. }
  20637. if ((here_op & 0xf0) === 0) {
  20638. last_bits = here_bits;
  20639. last_op = here_op;
  20640. last_val = here_val;
  20641. for (;;) {
  20642. here = state.distcode[last_val +
  20643. ((hold & ((1 << (last_bits + last_op)) -1))/*BITS(last.bits + last.op)*/ >> last_bits)];
  20644. here_bits = here >>> 24;
  20645. here_op = (here >>> 16) & 0xff;
  20646. here_val = here & 0xffff;
  20647. if ((last_bits + here_bits) <= bits) { break; }
  20648. //--- PULLBYTE() ---//
  20649. if (have === 0) { break inf_leave; }
  20650. have--;
  20651. hold += input[next++] << bits;
  20652. bits += 8;
  20653. //---//
  20654. }
  20655. //--- DROPBITS(last.bits) ---//
  20656. hold >>>= last_bits;
  20657. bits -= last_bits;
  20658. //---//
  20659. state.back += last_bits;
  20660. }
  20661. //--- DROPBITS(here.bits) ---//
  20662. hold >>>= here_bits;
  20663. bits -= here_bits;
  20664. //---//
  20665. state.back += here_bits;
  20666. if (here_op & 64) {
  20667. strm.msg = 'invalid distance code';
  20668. state.mode = BAD;
  20669. break;
  20670. }
  20671. state.offset = here_val;
  20672. state.extra = (here_op) & 15;
  20673. state.mode = DISTEXT;
  20674. /* falls through */
  20675. case DISTEXT:
  20676. if (state.extra) {
  20677. //=== NEEDBITS(state.extra);
  20678. n = state.extra;
  20679. while (bits < n) {
  20680. if (have === 0) { break inf_leave; }
  20681. have--;
  20682. hold += input[next++] << bits;
  20683. bits += 8;
  20684. }
  20685. //===//
  20686. state.offset += hold & ((1 << state.extra) -1)/*BITS(state.extra)*/;
  20687. //--- DROPBITS(state.extra) ---//
  20688. hold >>>= state.extra;
  20689. bits -= state.extra;
  20690. //---//
  20691. state.back += state.extra;
  20692. }
  20693. //#ifdef INFLATE_STRICT
  20694. if (state.offset > state.dmax) {
  20695. strm.msg = 'invalid distance too far back';
  20696. state.mode = BAD;
  20697. break;
  20698. }
  20699. //#endif
  20700. //Tracevv((stderr, "inflate: distance %u\n", state.offset));
  20701. state.mode = MATCH;
  20702. /* falls through */
  20703. case MATCH:
  20704. if (left === 0) { break inf_leave; }
  20705. copy = _out - left;
  20706. if (state.offset > copy) { /* copy from window */
  20707. copy = state.offset - copy;
  20708. if (copy > state.whave) {
  20709. if (state.sane) {
  20710. strm.msg = 'invalid distance too far back';
  20711. state.mode = BAD;
  20712. break;
  20713. }
  20714. // (!) This block is disabled in zlib defailts,
  20715. // don't enable it for binary compatibility
  20716. //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
  20717. // Trace((stderr, "inflate.c too far\n"));
  20718. // copy -= state.whave;
  20719. // if (copy > state.length) { copy = state.length; }
  20720. // if (copy > left) { copy = left; }
  20721. // left -= copy;
  20722. // state.length -= copy;
  20723. // do {
  20724. // output[put++] = 0;
  20725. // } while (--copy);
  20726. // if (state.length === 0) { state.mode = LEN; }
  20727. // break;
  20728. //#endif
  20729. }
  20730. if (copy > state.wnext) {
  20731. copy -= state.wnext;
  20732. from = state.wsize - copy;
  20733. }
  20734. else {
  20735. from = state.wnext - copy;
  20736. }
  20737. if (copy > state.length) { copy = state.length; }
  20738. from_source = state.window;
  20739. }
  20740. else { /* copy from output */
  20741. from_source = output;
  20742. from = put - state.offset;
  20743. copy = state.length;
  20744. }
  20745. if (copy > left) { copy = left; }
  20746. left -= copy;
  20747. state.length -= copy;
  20748. do {
  20749. output[put++] = from_source[from++];
  20750. } while (--copy);
  20751. if (state.length === 0) { state.mode = LEN; }
  20752. break;
  20753. case LIT:
  20754. if (left === 0) { break inf_leave; }
  20755. output[put++] = state.length;
  20756. left--;
  20757. state.mode = LEN;
  20758. break;
  20759. case CHECK:
  20760. if (state.wrap) {
  20761. //=== NEEDBITS(32);
  20762. while (bits < 32) {
  20763. if (have === 0) { break inf_leave; }
  20764. have--;
  20765. // Use '|' insdead of '+' to make sure that result is signed
  20766. hold |= input[next++] << bits;
  20767. bits += 8;
  20768. }
  20769. //===//
  20770. _out -= left;
  20771. strm.total_out += _out;
  20772. state.total += _out;
  20773. if (_out) {
  20774. strm.adler = state.check =
  20775. /*UPDATE(state.check, put - _out, _out);*/
  20776. (state.flags ? crc32(state.check, output, _out, put - _out) : adler32(state.check, output, _out, put - _out));
  20777. }
  20778. _out = left;
  20779. // NB: crc32 stored as signed 32-bit int, ZSWAP32 returns signed too
  20780. if ((state.flags ? hold : ZSWAP32(hold)) !== state.check) {
  20781. strm.msg = 'incorrect data check';
  20782. state.mode = BAD;
  20783. break;
  20784. }
  20785. //=== INITBITS();
  20786. hold = 0;
  20787. bits = 0;
  20788. //===//
  20789. //Tracev((stderr, "inflate: check matches trailer\n"));
  20790. }
  20791. state.mode = LENGTH;
  20792. /* falls through */
  20793. case LENGTH:
  20794. if (state.wrap && state.flags) {
  20795. //=== NEEDBITS(32);
  20796. while (bits < 32) {
  20797. if (have === 0) { break inf_leave; }
  20798. have--;
  20799. hold += input[next++] << bits;
  20800. bits += 8;
  20801. }
  20802. //===//
  20803. if (hold !== (state.total & 0xffffffff)) {
  20804. strm.msg = 'incorrect length check';
  20805. state.mode = BAD;
  20806. break;
  20807. }
  20808. //=== INITBITS();
  20809. hold = 0;
  20810. bits = 0;
  20811. //===//
  20812. //Tracev((stderr, "inflate: length matches trailer\n"));
  20813. }
  20814. state.mode = DONE;
  20815. /* falls through */
  20816. case DONE:
  20817. ret = Z_STREAM_END;
  20818. break inf_leave;
  20819. case BAD:
  20820. ret = Z_DATA_ERROR;
  20821. break inf_leave;
  20822. case MEM:
  20823. return Z_MEM_ERROR;
  20824. case SYNC:
  20825. /* falls through */
  20826. default:
  20827. return Z_STREAM_ERROR;
  20828. }
  20829. }
  20830. // inf_leave <- here is real place for "goto inf_leave", emulated via "break inf_leave"
  20831. /*
  20832. Return from inflate(), updating the total counts and the check value.
  20833. If there was no progress during the inflate() call, return a buffer
  20834. error. Call updatewindow() to create and/or update the window state.
  20835. Note: a memory error from inflate() is non-recoverable.
  20836. */
  20837. //--- RESTORE() ---
  20838. strm.next_out = put;
  20839. strm.avail_out = left;
  20840. strm.next_in = next;
  20841. strm.avail_in = have;
  20842. state.hold = hold;
  20843. state.bits = bits;
  20844. //---
  20845. if (state.wsize || (_out !== strm.avail_out && state.mode < BAD &&
  20846. (state.mode < CHECK || flush !== Z_FINISH))) {
  20847. if (updatewindow(strm, strm.output, strm.next_out, _out - strm.avail_out)) {
  20848. state.mode = MEM;
  20849. return Z_MEM_ERROR;
  20850. }
  20851. }
  20852. _in -= strm.avail_in;
  20853. _out -= strm.avail_out;
  20854. strm.total_in += _in;
  20855. strm.total_out += _out;
  20856. state.total += _out;
  20857. if (state.wrap && _out) {
  20858. strm.adler = state.check = /*UPDATE(state.check, strm.next_out - _out, _out);*/
  20859. (state.flags ? crc32(state.check, output, _out, strm.next_out - _out) : adler32(state.check, output, _out, strm.next_out - _out));
  20860. }
  20861. strm.data_type = state.bits + (state.last ? 64 : 0) +
  20862. (state.mode === TYPE ? 128 : 0) +
  20863. (state.mode === LEN_ || state.mode === COPY_ ? 256 : 0);
  20864. if (((_in === 0 && _out === 0) || flush === Z_FINISH) && ret === Z_OK) {
  20865. ret = Z_BUF_ERROR;
  20866. }
  20867. return ret;
  20868. }
  20869. function inflateEnd(strm) {
  20870. if (!strm || !strm.state /*|| strm->zfree == (free_func)0*/) {
  20871. return Z_STREAM_ERROR;
  20872. }
  20873. var state = strm.state;
  20874. if (state.window) {
  20875. state.window = null;
  20876. }
  20877. strm.state = null;
  20878. return Z_OK;
  20879. }
  20880. function inflateGetHeader(strm, head) {
  20881. var state;
  20882. /* check state */
  20883. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  20884. state = strm.state;
  20885. if ((state.wrap & 2) === 0) { return Z_STREAM_ERROR; }
  20886. /* save header structure */
  20887. state.head = head;
  20888. head.done = false;
  20889. return Z_OK;
  20890. }
  20891. exports.inflateReset = inflateReset;
  20892. exports.inflateReset2 = inflateReset2;
  20893. exports.inflateResetKeep = inflateResetKeep;
  20894. exports.inflateInit = inflateInit;
  20895. exports.inflateInit2 = inflateInit2;
  20896. exports.inflate = inflate;
  20897. exports.inflateEnd = inflateEnd;
  20898. exports.inflateGetHeader = inflateGetHeader;
  20899. exports.inflateInfo = 'pako inflate (from Nodeca project)';
  20900. /* Not implemented
  20901. exports.inflateCopy = inflateCopy;
  20902. exports.inflateGetDictionary = inflateGetDictionary;
  20903. exports.inflateMark = inflateMark;
  20904. exports.inflatePrime = inflatePrime;
  20905. exports.inflateSetDictionary = inflateSetDictionary;
  20906. exports.inflateSync = inflateSync;
  20907. exports.inflateSyncPoint = inflateSyncPoint;
  20908. exports.inflateUndermine = inflateUndermine;
  20909. */
  20910. },{"../utils/common":65,"./adler32":67,"./crc32":69,"./inffast":72,"./inftrees":74}],74:[function(require,module,exports){
  20911. 'use strict';
  20912. var utils = require('../utils/common');
  20913. var MAXBITS = 15;
  20914. var ENOUGH_LENS = 852;
  20915. var ENOUGH_DISTS = 592;
  20916. //var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
  20917. var CODES = 0;
  20918. var LENS = 1;
  20919. var DISTS = 2;
  20920. var lbase = [ /* Length codes 257..285 base */
  20921. 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
  20922. 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0
  20923. ];
  20924. var lext = [ /* Length codes 257..285 extra */
  20925. 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,
  20926. 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 72, 78
  20927. ];
  20928. var dbase = [ /* Distance codes 0..29 base */
  20929. 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
  20930. 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
  20931. 8193, 12289, 16385, 24577, 0, 0
  20932. ];
  20933. var dext = [ /* Distance codes 0..29 extra */
  20934. 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,
  20935. 23, 23, 24, 24, 25, 25, 26, 26, 27, 27,
  20936. 28, 28, 29, 29, 64, 64
  20937. ];
  20938. module.exports = function inflate_table(type, lens, lens_index, codes, table, table_index, work, opts)
  20939. {
  20940. var bits = opts.bits;
  20941. //here = opts.here; /* table entry for duplication */
  20942. var len = 0; /* a code's length in bits */
  20943. var sym = 0; /* index of code symbols */
  20944. var min = 0, max = 0; /* minimum and maximum code lengths */
  20945. var root = 0; /* number of index bits for root table */
  20946. var curr = 0; /* number of index bits for current table */
  20947. var drop = 0; /* code bits to drop for sub-table */
  20948. var left = 0; /* number of prefix codes available */
  20949. var used = 0; /* code entries in table used */
  20950. var huff = 0; /* Huffman code */
  20951. var incr; /* for incrementing code, index */
  20952. var fill; /* index for replicating entries */
  20953. var low; /* low bits for current root entry */
  20954. var mask; /* mask for low root bits */
  20955. var next; /* next available space in table */
  20956. var base = null; /* base value table to use */
  20957. var base_index = 0;
  20958. // var shoextra; /* extra bits table to use */
  20959. var end; /* use base and extra for symbol > end */
  20960. var count = new utils.Buf16(MAXBITS+1); //[MAXBITS+1]; /* number of codes of each length */
  20961. var offs = new utils.Buf16(MAXBITS+1); //[MAXBITS+1]; /* offsets in table for each length */
  20962. var extra = null;
  20963. var extra_index = 0;
  20964. var here_bits, here_op, here_val;
  20965. /*
  20966. Process a set of code lengths to create a canonical Huffman code. The
  20967. code lengths are lens[0..codes-1]. Each length corresponds to the
  20968. symbols 0..codes-1. The Huffman code is generated by first sorting the
  20969. symbols by length from short to long, and retaining the symbol order
  20970. for codes with equal lengths. Then the code starts with all zero bits
  20971. for the first code of the shortest length, and the codes are integer
  20972. increments for the same length, and zeros are appended as the length
  20973. increases. For the deflate format, these bits are stored backwards
  20974. from their more natural integer increment ordering, and so when the
  20975. decoding tables are built in the large loop below, the integer codes
  20976. are incremented backwards.
  20977. This routine assumes, but does not check, that all of the entries in
  20978. lens[] are in the range 0..MAXBITS. The caller must assure this.
  20979. 1..MAXBITS is interpreted as that code length. zero means that that
  20980. symbol does not occur in this code.
  20981. The codes are sorted by computing a count of codes for each length,
  20982. creating from that a table of starting indices for each length in the
  20983. sorted table, and then entering the symbols in order in the sorted
  20984. table. The sorted table is work[], with that space being provided by
  20985. the caller.
  20986. The length counts are used for other purposes as well, i.e. finding
  20987. the minimum and maximum length codes, determining if there are any
  20988. codes at all, checking for a valid set of lengths, and looking ahead
  20989. at length counts to determine sub-table sizes when building the
  20990. decoding tables.
  20991. */
  20992. /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */
  20993. for (len = 0; len <= MAXBITS; len++) {
  20994. count[len] = 0;
  20995. }
  20996. for (sym = 0; sym < codes; sym++) {
  20997. count[lens[lens_index + sym]]++;
  20998. }
  20999. /* bound code lengths, force root to be within code lengths */
  21000. root = bits;
  21001. for (max = MAXBITS; max >= 1; max--) {
  21002. if (count[max] !== 0) { break; }
  21003. }
  21004. if (root > max) {
  21005. root = max;
  21006. }
  21007. if (max === 0) { /* no symbols to code at all */
  21008. //table.op[opts.table_index] = 64; //here.op = (var char)64; /* invalid code marker */
  21009. //table.bits[opts.table_index] = 1; //here.bits = (var char)1;
  21010. //table.val[opts.table_index++] = 0; //here.val = (var short)0;
  21011. table[table_index++] = (1 << 24) | (64 << 16) | 0;
  21012. //table.op[opts.table_index] = 64;
  21013. //table.bits[opts.table_index] = 1;
  21014. //table.val[opts.table_index++] = 0;
  21015. table[table_index++] = (1 << 24) | (64 << 16) | 0;
  21016. opts.bits = 1;
  21017. return 0; /* no symbols, but wait for decoding to report error */
  21018. }
  21019. for (min = 1; min < max; min++) {
  21020. if (count[min] !== 0) { break; }
  21021. }
  21022. if (root < min) {
  21023. root = min;
  21024. }
  21025. /* check for an over-subscribed or incomplete set of lengths */
  21026. left = 1;
  21027. for (len = 1; len <= MAXBITS; len++) {
  21028. left <<= 1;
  21029. left -= count[len];
  21030. if (left < 0) {
  21031. return -1;
  21032. } /* over-subscribed */
  21033. }
  21034. if (left > 0 && (type === CODES || max !== 1)) {
  21035. return -1; /* incomplete set */
  21036. }
  21037. /* generate offsets into symbol table for each length for sorting */
  21038. offs[1] = 0;
  21039. for (len = 1; len < MAXBITS; len++) {
  21040. offs[len + 1] = offs[len] + count[len];
  21041. }
  21042. /* sort symbols by length, by symbol order within each length */
  21043. for (sym = 0; sym < codes; sym++) {
  21044. if (lens[lens_index + sym] !== 0) {
  21045. work[offs[lens[lens_index + sym]]++] = sym;
  21046. }
  21047. }
  21048. /*
  21049. Create and fill in decoding tables. In this loop, the table being
  21050. filled is at next and has curr index bits. The code being used is huff
  21051. with length len. That code is converted to an index by dropping drop
  21052. bits off of the bottom. For codes where len is less than drop + curr,
  21053. those top drop + curr - len bits are incremented through all values to
  21054. fill the table with replicated entries.
  21055. root is the number of index bits for the root table. When len exceeds
  21056. root, sub-tables are created pointed to by the root entry with an index
  21057. of the low root bits of huff. This is saved in low to check for when a
  21058. new sub-table should be started. drop is zero when the root table is
  21059. being filled, and drop is root when sub-tables are being filled.
  21060. When a new sub-table is needed, it is necessary to look ahead in the
  21061. code lengths to determine what size sub-table is needed. The length
  21062. counts are used for this, and so count[] is decremented as codes are
  21063. entered in the tables.
  21064. used keeps track of how many table entries have been allocated from the
  21065. provided *table space. It is checked for LENS and DIST tables against
  21066. the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in
  21067. the initial root table size constants. See the comments in inftrees.h
  21068. for more information.
  21069. sym increments through all symbols, and the loop terminates when
  21070. all codes of length max, i.e. all codes, have been processed. This
  21071. routine permits incomplete codes, so another loop after this one fills
  21072. in the rest of the decoding tables with invalid code markers.
  21073. */
  21074. /* set up for code type */
  21075. // poor man optimization - use if-else instead of switch,
  21076. // to avoid deopts in old v8
  21077. if (type === CODES) {
  21078. base = extra = work; /* dummy value--not used */
  21079. end = 19;
  21080. } else if (type === LENS) {
  21081. base = lbase;
  21082. base_index -= 257;
  21083. extra = lext;
  21084. extra_index -= 257;
  21085. end = 256;
  21086. } else { /* DISTS */
  21087. base = dbase;
  21088. extra = dext;
  21089. end = -1;
  21090. }
  21091. /* initialize opts for loop */
  21092. huff = 0; /* starting code */
  21093. sym = 0; /* starting code symbol */
  21094. len = min; /* starting code length */
  21095. next = table_index; /* current table to fill in */
  21096. curr = root; /* current table index bits */
  21097. drop = 0; /* current bits to drop from code for index */
  21098. low = -1; /* trigger new sub-table when len > root */
  21099. used = 1 << root; /* use root table entries */
  21100. mask = used - 1; /* mask for comparing low */
  21101. /* check available table space */
  21102. if ((type === LENS && used > ENOUGH_LENS) ||
  21103. (type === DISTS && used > ENOUGH_DISTS)) {
  21104. return 1;
  21105. }
  21106. var i=0;
  21107. /* process all codes and make table entries */
  21108. for (;;) {
  21109. i++;
  21110. /* create table entry */
  21111. here_bits = len - drop;
  21112. if (work[sym] < end) {
  21113. here_op = 0;
  21114. here_val = work[sym];
  21115. }
  21116. else if (work[sym] > end) {
  21117. here_op = extra[extra_index + work[sym]];
  21118. here_val = base[base_index + work[sym]];
  21119. }
  21120. else {
  21121. here_op = 32 + 64; /* end of block */
  21122. here_val = 0;
  21123. }
  21124. /* replicate for those indices with low len bits equal to huff */
  21125. incr = 1 << (len - drop);
  21126. fill = 1 << curr;
  21127. min = fill; /* save offset to next table */
  21128. do {
  21129. fill -= incr;
  21130. table[next + (huff >> drop) + fill] = (here_bits << 24) | (here_op << 16) | here_val |0;
  21131. } while (fill !== 0);
  21132. /* backwards increment the len-bit code huff */
  21133. incr = 1 << (len - 1);
  21134. while (huff & incr) {
  21135. incr >>= 1;
  21136. }
  21137. if (incr !== 0) {
  21138. huff &= incr - 1;
  21139. huff += incr;
  21140. } else {
  21141. huff = 0;
  21142. }
  21143. /* go to next symbol, update count, len */
  21144. sym++;
  21145. if (--count[len] === 0) {
  21146. if (len === max) { break; }
  21147. len = lens[lens_index + work[sym]];
  21148. }
  21149. /* create new sub-table if needed */
  21150. if (len > root && (huff & mask) !== low) {
  21151. /* if first time, transition to sub-tables */
  21152. if (drop === 0) {
  21153. drop = root;
  21154. }
  21155. /* increment past last table */
  21156. next += min; /* here min is 1 << curr */
  21157. /* determine length of next table */
  21158. curr = len - drop;
  21159. left = 1 << curr;
  21160. while (curr + drop < max) {
  21161. left -= count[curr + drop];
  21162. if (left <= 0) { break; }
  21163. curr++;
  21164. left <<= 1;
  21165. }
  21166. /* check for enough space */
  21167. used += 1 << curr;
  21168. if ((type === LENS && used > ENOUGH_LENS) ||
  21169. (type === DISTS && used > ENOUGH_DISTS)) {
  21170. return 1;
  21171. }
  21172. /* point entry in root table to sub-table */
  21173. low = huff & mask;
  21174. /*table.op[low] = curr;
  21175. table.bits[low] = root;
  21176. table.val[low] = next - opts.table_index;*/
  21177. table[low] = (root << 24) | (curr << 16) | (next - table_index) |0;
  21178. }
  21179. }
  21180. /* fill in remaining table entry if code is incomplete (guaranteed to have
  21181. at most one remaining entry, since if the code is incomplete, the
  21182. maximum code length that was allowed to get this far is one bit) */
  21183. if (huff !== 0) {
  21184. //table.op[next + huff] = 64; /* invalid code marker */
  21185. //table.bits[next + huff] = len - drop;
  21186. //table.val[next + huff] = 0;
  21187. table[next + huff] = ((len - drop) << 24) | (64 << 16) |0;
  21188. }
  21189. /* set return parameters */
  21190. //opts.table_index += used;
  21191. opts.bits = root;
  21192. return 0;
  21193. };
  21194. },{"../utils/common":65}],75:[function(require,module,exports){
  21195. 'use strict';
  21196. module.exports = {
  21197. '2': 'need dictionary', /* Z_NEED_DICT 2 */
  21198. '1': 'stream end', /* Z_STREAM_END 1 */
  21199. '0': '', /* Z_OK 0 */
  21200. '-1': 'file error', /* Z_ERRNO (-1) */
  21201. '-2': 'stream error', /* Z_STREAM_ERROR (-2) */
  21202. '-3': 'data error', /* Z_DATA_ERROR (-3) */
  21203. '-4': 'insufficient memory', /* Z_MEM_ERROR (-4) */
  21204. '-5': 'buffer error', /* Z_BUF_ERROR (-5) */
  21205. '-6': 'incompatible version' /* Z_VERSION_ERROR (-6) */
  21206. };
  21207. },{}],76:[function(require,module,exports){
  21208. 'use strict';
  21209. var utils = require('../utils/common');
  21210. /* Public constants ==========================================================*/
  21211. /* ===========================================================================*/
  21212. //var Z_FILTERED = 1;
  21213. //var Z_HUFFMAN_ONLY = 2;
  21214. //var Z_RLE = 3;
  21215. var Z_FIXED = 4;
  21216. //var Z_DEFAULT_STRATEGY = 0;
  21217. /* Possible values of the data_type field (though see inflate()) */
  21218. var Z_BINARY = 0;
  21219. var Z_TEXT = 1;
  21220. //var Z_ASCII = 1; // = Z_TEXT
  21221. var Z_UNKNOWN = 2;
  21222. /*============================================================================*/
  21223. function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
  21224. // From zutil.h
  21225. var STORED_BLOCK = 0;
  21226. var STATIC_TREES = 1;
  21227. var DYN_TREES = 2;
  21228. /* The three kinds of block type */
  21229. var MIN_MATCH = 3;
  21230. var MAX_MATCH = 258;
  21231. /* The minimum and maximum match lengths */
  21232. // From deflate.h
  21233. /* ===========================================================================
  21234. * Internal compression state.
  21235. */
  21236. var LENGTH_CODES = 29;
  21237. /* number of length codes, not counting the special END_BLOCK code */
  21238. var LITERALS = 256;
  21239. /* number of literal bytes 0..255 */
  21240. var L_CODES = LITERALS + 1 + LENGTH_CODES;
  21241. /* number of Literal or Length codes, including the END_BLOCK code */
  21242. var D_CODES = 30;
  21243. /* number of distance codes */
  21244. var BL_CODES = 19;
  21245. /* number of codes used to transfer the bit lengths */
  21246. var HEAP_SIZE = 2*L_CODES + 1;
  21247. /* maximum heap size */
  21248. var MAX_BITS = 15;
  21249. /* All codes must not exceed MAX_BITS bits */
  21250. var Buf_size = 16;
  21251. /* size of bit buffer in bi_buf */
  21252. /* ===========================================================================
  21253. * Constants
  21254. */
  21255. var MAX_BL_BITS = 7;
  21256. /* Bit length codes must not exceed MAX_BL_BITS bits */
  21257. var END_BLOCK = 256;
  21258. /* end of block literal code */
  21259. var REP_3_6 = 16;
  21260. /* repeat previous bit length 3-6 times (2 bits of repeat count) */
  21261. var REPZ_3_10 = 17;
  21262. /* repeat a zero length 3-10 times (3 bits of repeat count) */
  21263. var REPZ_11_138 = 18;
  21264. /* repeat a zero length 11-138 times (7 bits of repeat count) */
  21265. var extra_lbits = /* extra bits for each length code */
  21266. [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];
  21267. var extra_dbits = /* extra bits for each distance code */
  21268. [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];
  21269. var extra_blbits = /* extra bits for each bit length code */
  21270. [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7];
  21271. var bl_order =
  21272. [16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];
  21273. /* The lengths of the bit length codes are sent in order of decreasing
  21274. * probability, to avoid transmitting the lengths for unused bit length codes.
  21275. */
  21276. /* ===========================================================================
  21277. * Local data. These are initialized only once.
  21278. */
  21279. // We pre-fill arrays with 0 to avoid uninitialized gaps
  21280. var DIST_CODE_LEN = 512; /* see definition of array dist_code below */
  21281. // !!!! Use flat array insdead of structure, Freq = i*2, Len = i*2+1
  21282. var static_ltree = new Array((L_CODES+2) * 2);
  21283. zero(static_ltree);
  21284. /* The static literal tree. Since the bit lengths are imposed, there is no
  21285. * need for the L_CODES extra codes used during heap construction. However
  21286. * The codes 286 and 287 are needed to build a canonical tree (see _tr_init
  21287. * below).
  21288. */
  21289. var static_dtree = new Array(D_CODES * 2);
  21290. zero(static_dtree);
  21291. /* The static distance tree. (Actually a trivial tree since all codes use
  21292. * 5 bits.)
  21293. */
  21294. var _dist_code = new Array(DIST_CODE_LEN);
  21295. zero(_dist_code);
  21296. /* Distance codes. The first 256 values correspond to the distances
  21297. * 3 .. 258, the last 256 values correspond to the top 8 bits of
  21298. * the 15 bit distances.
  21299. */
  21300. var _length_code = new Array(MAX_MATCH-MIN_MATCH+1);
  21301. zero(_length_code);
  21302. /* length code for each normalized match length (0 == MIN_MATCH) */
  21303. var base_length = new Array(LENGTH_CODES);
  21304. zero(base_length);
  21305. /* First normalized length for each code (0 = MIN_MATCH) */
  21306. var base_dist = new Array(D_CODES);
  21307. zero(base_dist);
  21308. /* First normalized distance for each code (0 = distance of 1) */
  21309. var StaticTreeDesc = function (static_tree, extra_bits, extra_base, elems, max_length) {
  21310. this.static_tree = static_tree; /* static tree or NULL */
  21311. this.extra_bits = extra_bits; /* extra bits for each code or NULL */
  21312. this.extra_base = extra_base; /* base index for extra_bits */
  21313. this.elems = elems; /* max number of elements in the tree */
  21314. this.max_length = max_length; /* max bit length for the codes */
  21315. // show if `static_tree` has data or dummy - needed for monomorphic objects
  21316. this.has_stree = static_tree && static_tree.length;
  21317. };
  21318. var static_l_desc;
  21319. var static_d_desc;
  21320. var static_bl_desc;
  21321. var TreeDesc = function(dyn_tree, stat_desc) {
  21322. this.dyn_tree = dyn_tree; /* the dynamic tree */
  21323. this.max_code = 0; /* largest code with non zero frequency */
  21324. this.stat_desc = stat_desc; /* the corresponding static tree */
  21325. };
  21326. function d_code(dist) {
  21327. return dist < 256 ? _dist_code[dist] : _dist_code[256 + (dist >>> 7)];
  21328. }
  21329. /* ===========================================================================
  21330. * Output a short LSB first on the stream.
  21331. * IN assertion: there is enough room in pendingBuf.
  21332. */
  21333. function put_short (s, w) {
  21334. // put_byte(s, (uch)((w) & 0xff));
  21335. // put_byte(s, (uch)((ush)(w) >> 8));
  21336. s.pending_buf[s.pending++] = (w) & 0xff;
  21337. s.pending_buf[s.pending++] = (w >>> 8) & 0xff;
  21338. }
  21339. /* ===========================================================================
  21340. * Send a value on a given number of bits.
  21341. * IN assertion: length <= 16 and value fits in length bits.
  21342. */
  21343. function send_bits(s, value, length) {
  21344. if (s.bi_valid > (Buf_size - length)) {
  21345. s.bi_buf |= (value << s.bi_valid) & 0xffff;
  21346. put_short(s, s.bi_buf);
  21347. s.bi_buf = value >> (Buf_size - s.bi_valid);
  21348. s.bi_valid += length - Buf_size;
  21349. } else {
  21350. s.bi_buf |= (value << s.bi_valid) & 0xffff;
  21351. s.bi_valid += length;
  21352. }
  21353. }
  21354. function send_code(s, c, tree) {
  21355. send_bits(s, tree[c*2]/*.Code*/, tree[c*2 + 1]/*.Len*/);
  21356. }
  21357. /* ===========================================================================
  21358. * Reverse the first len bits of a code, using straightforward code (a faster
  21359. * method would use a table)
  21360. * IN assertion: 1 <= len <= 15
  21361. */
  21362. function bi_reverse(code, len) {
  21363. var res = 0;
  21364. do {
  21365. res |= code & 1;
  21366. code >>>= 1;
  21367. res <<= 1;
  21368. } while (--len > 0);
  21369. return res >>> 1;
  21370. }
  21371. /* ===========================================================================
  21372. * Flush the bit buffer, keeping at most 7 bits in it.
  21373. */
  21374. function bi_flush(s) {
  21375. if (s.bi_valid === 16) {
  21376. put_short(s, s.bi_buf);
  21377. s.bi_buf = 0;
  21378. s.bi_valid = 0;
  21379. } else if (s.bi_valid >= 8) {
  21380. s.pending_buf[s.pending++] = s.bi_buf & 0xff;
  21381. s.bi_buf >>= 8;
  21382. s.bi_valid -= 8;
  21383. }
  21384. }
  21385. /* ===========================================================================
  21386. * Compute the optimal bit lengths for a tree and update the total bit length
  21387. * for the current block.
  21388. * IN assertion: the fields freq and dad are set, heap[heap_max] and
  21389. * above are the tree nodes sorted by increasing frequency.
  21390. * OUT assertions: the field len is set to the optimal bit length, the
  21391. * array bl_count contains the frequencies for each bit length.
  21392. * The length opt_len is updated; static_len is also updated if stree is
  21393. * not null.
  21394. */
  21395. function gen_bitlen(s, desc)
  21396. // deflate_state *s;
  21397. // tree_desc *desc; /* the tree descriptor */
  21398. {
  21399. var tree = desc.dyn_tree;
  21400. var max_code = desc.max_code;
  21401. var stree = desc.stat_desc.static_tree;
  21402. var has_stree = desc.stat_desc.has_stree;
  21403. var extra = desc.stat_desc.extra_bits;
  21404. var base = desc.stat_desc.extra_base;
  21405. var max_length = desc.stat_desc.max_length;
  21406. var h; /* heap index */
  21407. var n, m; /* iterate over the tree elements */
  21408. var bits; /* bit length */
  21409. var xbits; /* extra bits */
  21410. var f; /* frequency */
  21411. var overflow = 0; /* number of elements with bit length too large */
  21412. for (bits = 0; bits <= MAX_BITS; bits++) {
  21413. s.bl_count[bits] = 0;
  21414. }
  21415. /* In a first pass, compute the optimal bit lengths (which may
  21416. * overflow in the case of the bit length tree).
  21417. */
  21418. tree[s.heap[s.heap_max]*2 + 1]/*.Len*/ = 0; /* root of the heap */
  21419. for (h = s.heap_max+1; h < HEAP_SIZE; h++) {
  21420. n = s.heap[h];
  21421. bits = tree[tree[n*2 +1]/*.Dad*/ * 2 + 1]/*.Len*/ + 1;
  21422. if (bits > max_length) {
  21423. bits = max_length;
  21424. overflow++;
  21425. }
  21426. tree[n*2 + 1]/*.Len*/ = bits;
  21427. /* We overwrite tree[n].Dad which is no longer needed */
  21428. if (n > max_code) { continue; } /* not a leaf node */
  21429. s.bl_count[bits]++;
  21430. xbits = 0;
  21431. if (n >= base) {
  21432. xbits = extra[n-base];
  21433. }
  21434. f = tree[n * 2]/*.Freq*/;
  21435. s.opt_len += f * (bits + xbits);
  21436. if (has_stree) {
  21437. s.static_len += f * (stree[n*2 + 1]/*.Len*/ + xbits);
  21438. }
  21439. }
  21440. if (overflow === 0) { return; }
  21441. // Trace((stderr,"\nbit length overflow\n"));
  21442. /* This happens for example on obj2 and pic of the Calgary corpus */
  21443. /* Find the first bit length which could increase: */
  21444. do {
  21445. bits = max_length-1;
  21446. while (s.bl_count[bits] === 0) { bits--; }
  21447. s.bl_count[bits]--; /* move one leaf down the tree */
  21448. s.bl_count[bits+1] += 2; /* move one overflow item as its brother */
  21449. s.bl_count[max_length]--;
  21450. /* The brother of the overflow item also moves one step up,
  21451. * but this does not affect bl_count[max_length]
  21452. */
  21453. overflow -= 2;
  21454. } while (overflow > 0);
  21455. /* Now recompute all bit lengths, scanning in increasing frequency.
  21456. * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all
  21457. * lengths instead of fixing only the wrong ones. This idea is taken
  21458. * from 'ar' written by Haruhiko Okumura.)
  21459. */
  21460. for (bits = max_length; bits !== 0; bits--) {
  21461. n = s.bl_count[bits];
  21462. while (n !== 0) {
  21463. m = s.heap[--h];
  21464. if (m > max_code) { continue; }
  21465. if (tree[m*2 + 1]/*.Len*/ !== bits) {
  21466. // Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits));
  21467. s.opt_len += (bits - tree[m*2 + 1]/*.Len*/)*tree[m*2]/*.Freq*/;
  21468. tree[m*2 + 1]/*.Len*/ = bits;
  21469. }
  21470. n--;
  21471. }
  21472. }
  21473. }
  21474. /* ===========================================================================
  21475. * Generate the codes for a given tree and bit counts (which need not be
  21476. * optimal).
  21477. * IN assertion: the array bl_count contains the bit length statistics for
  21478. * the given tree and the field len is set for all tree elements.
  21479. * OUT assertion: the field code is set for all tree elements of non
  21480. * zero code length.
  21481. */
  21482. function gen_codes(tree, max_code, bl_count)
  21483. // ct_data *tree; /* the tree to decorate */
  21484. // int max_code; /* largest code with non zero frequency */
  21485. // ushf *bl_count; /* number of codes at each bit length */
  21486. {
  21487. var next_code = new Array(MAX_BITS+1); /* next code value for each bit length */
  21488. var code = 0; /* running code value */
  21489. var bits; /* bit index */
  21490. var n; /* code index */
  21491. /* The distribution counts are first used to generate the code values
  21492. * without bit reversal.
  21493. */
  21494. for (bits = 1; bits <= MAX_BITS; bits++) {
  21495. next_code[bits] = code = (code + bl_count[bits-1]) << 1;
  21496. }
  21497. /* Check that the bit counts in bl_count are consistent. The last code
  21498. * must be all ones.
  21499. */
  21500. //Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,
  21501. // "inconsistent bit counts");
  21502. //Tracev((stderr,"\ngen_codes: max_code %d ", max_code));
  21503. for (n = 0; n <= max_code; n++) {
  21504. var len = tree[n*2 + 1]/*.Len*/;
  21505. if (len === 0) { continue; }
  21506. /* Now reverse the bits */
  21507. tree[n*2]/*.Code*/ = bi_reverse(next_code[len]++, len);
  21508. //Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ",
  21509. // n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1));
  21510. }
  21511. }
  21512. /* ===========================================================================
  21513. * Initialize the various 'constant' tables.
  21514. */
  21515. function tr_static_init() {
  21516. var n; /* iterates over tree elements */
  21517. var bits; /* bit counter */
  21518. var length; /* length value */
  21519. var code; /* code value */
  21520. var dist; /* distance index */
  21521. var bl_count = new Array(MAX_BITS+1);
  21522. /* number of codes at each bit length for an optimal tree */
  21523. // do check in _tr_init()
  21524. //if (static_init_done) return;
  21525. /* For some embedded targets, global variables are not initialized: */
  21526. /*#ifdef NO_INIT_GLOBAL_POINTERS
  21527. static_l_desc.static_tree = static_ltree;
  21528. static_l_desc.extra_bits = extra_lbits;
  21529. static_d_desc.static_tree = static_dtree;
  21530. static_d_desc.extra_bits = extra_dbits;
  21531. static_bl_desc.extra_bits = extra_blbits;
  21532. #endif*/
  21533. /* Initialize the mapping length (0..255) -> length code (0..28) */
  21534. length = 0;
  21535. for (code = 0; code < LENGTH_CODES-1; code++) {
  21536. base_length[code] = length;
  21537. for (n = 0; n < (1<<extra_lbits[code]); n++) {
  21538. _length_code[length++] = code;
  21539. }
  21540. }
  21541. //Assert (length == 256, "tr_static_init: length != 256");
  21542. /* Note that the length 255 (match length 258) can be represented
  21543. * in two different ways: code 284 + 5 bits or code 285, so we
  21544. * overwrite length_code[255] to use the best encoding:
  21545. */
  21546. _length_code[length-1] = code;
  21547. /* Initialize the mapping dist (0..32K) -> dist code (0..29) */
  21548. dist = 0;
  21549. for (code = 0 ; code < 16; code++) {
  21550. base_dist[code] = dist;
  21551. for (n = 0; n < (1<<extra_dbits[code]); n++) {
  21552. _dist_code[dist++] = code;
  21553. }
  21554. }
  21555. //Assert (dist == 256, "tr_static_init: dist != 256");
  21556. dist >>= 7; /* from now on, all distances are divided by 128 */
  21557. for ( ; code < D_CODES; code++) {
  21558. base_dist[code] = dist << 7;
  21559. for (n = 0; n < (1<<(extra_dbits[code]-7)); n++) {
  21560. _dist_code[256 + dist++] = code;
  21561. }
  21562. }
  21563. //Assert (dist == 256, "tr_static_init: 256+dist != 512");
  21564. /* Construct the codes of the static literal tree */
  21565. for (bits = 0; bits <= MAX_BITS; bits++) {
  21566. bl_count[bits] = 0;
  21567. }
  21568. n = 0;
  21569. while (n <= 143) {
  21570. static_ltree[n*2 + 1]/*.Len*/ = 8;
  21571. n++;
  21572. bl_count[8]++;
  21573. }
  21574. while (n <= 255) {
  21575. static_ltree[n*2 + 1]/*.Len*/ = 9;
  21576. n++;
  21577. bl_count[9]++;
  21578. }
  21579. while (n <= 279) {
  21580. static_ltree[n*2 + 1]/*.Len*/ = 7;
  21581. n++;
  21582. bl_count[7]++;
  21583. }
  21584. while (n <= 287) {
  21585. static_ltree[n*2 + 1]/*.Len*/ = 8;
  21586. n++;
  21587. bl_count[8]++;
  21588. }
  21589. /* Codes 286 and 287 do not exist, but we must include them in the
  21590. * tree construction to get a canonical Huffman tree (longest code
  21591. * all ones)
  21592. */
  21593. gen_codes(static_ltree, L_CODES+1, bl_count);
  21594. /* The static distance tree is trivial: */
  21595. for (n = 0; n < D_CODES; n++) {
  21596. static_dtree[n*2 + 1]/*.Len*/ = 5;
  21597. static_dtree[n*2]/*.Code*/ = bi_reverse(n, 5);
  21598. }
  21599. // Now data ready and we can init static trees
  21600. static_l_desc = new StaticTreeDesc(static_ltree, extra_lbits, LITERALS+1, L_CODES, MAX_BITS);
  21601. static_d_desc = new StaticTreeDesc(static_dtree, extra_dbits, 0, D_CODES, MAX_BITS);
  21602. static_bl_desc =new StaticTreeDesc(new Array(0), extra_blbits, 0, BL_CODES, MAX_BL_BITS);
  21603. //static_init_done = true;
  21604. }
  21605. /* ===========================================================================
  21606. * Initialize a new block.
  21607. */
  21608. function init_block(s) {
  21609. var n; /* iterates over tree elements */
  21610. /* Initialize the trees. */
  21611. for (n = 0; n < L_CODES; n++) { s.dyn_ltree[n*2]/*.Freq*/ = 0; }
  21612. for (n = 0; n < D_CODES; n++) { s.dyn_dtree[n*2]/*.Freq*/ = 0; }
  21613. for (n = 0; n < BL_CODES; n++) { s.bl_tree[n*2]/*.Freq*/ = 0; }
  21614. s.dyn_ltree[END_BLOCK*2]/*.Freq*/ = 1;
  21615. s.opt_len = s.static_len = 0;
  21616. s.last_lit = s.matches = 0;
  21617. }
  21618. /* ===========================================================================
  21619. * Flush the bit buffer and align the output on a byte boundary
  21620. */
  21621. function bi_windup(s)
  21622. {
  21623. if (s.bi_valid > 8) {
  21624. put_short(s, s.bi_buf);
  21625. } else if (s.bi_valid > 0) {
  21626. //put_byte(s, (Byte)s->bi_buf);
  21627. s.pending_buf[s.pending++] = s.bi_buf;
  21628. }
  21629. s.bi_buf = 0;
  21630. s.bi_valid = 0;
  21631. }
  21632. /* ===========================================================================
  21633. * Copy a stored block, storing first the length and its
  21634. * one's complement if requested.
  21635. */
  21636. function copy_block(s, buf, len, header)
  21637. //DeflateState *s;
  21638. //charf *buf; /* the input data */
  21639. //unsigned len; /* its length */
  21640. //int header; /* true if block header must be written */
  21641. {
  21642. bi_windup(s); /* align on byte boundary */
  21643. if (header) {
  21644. put_short(s, len);
  21645. put_short(s, ~len);
  21646. }
  21647. // while (len--) {
  21648. // put_byte(s, *buf++);
  21649. // }
  21650. utils.arraySet(s.pending_buf, s.window, buf, len, s.pending);
  21651. s.pending += len;
  21652. }
  21653. /* ===========================================================================
  21654. * Compares to subtrees, using the tree depth as tie breaker when
  21655. * the subtrees have equal frequency. This minimizes the worst case length.
  21656. */
  21657. function smaller(tree, n, m, depth) {
  21658. var _n2 = n*2;
  21659. var _m2 = m*2;
  21660. return (tree[_n2]/*.Freq*/ < tree[_m2]/*.Freq*/ ||
  21661. (tree[_n2]/*.Freq*/ === tree[_m2]/*.Freq*/ && depth[n] <= depth[m]));
  21662. }
  21663. /* ===========================================================================
  21664. * Restore the heap property by moving down the tree starting at node k,
  21665. * exchanging a node with the smallest of its two sons if necessary, stopping
  21666. * when the heap property is re-established (each father smaller than its
  21667. * two sons).
  21668. */
  21669. function pqdownheap(s, tree, k)
  21670. // deflate_state *s;
  21671. // ct_data *tree; /* the tree to restore */
  21672. // int k; /* node to move down */
  21673. {
  21674. var v = s.heap[k];
  21675. var j = k << 1; /* left son of k */
  21676. while (j <= s.heap_len) {
  21677. /* Set j to the smallest of the two sons: */
  21678. if (j < s.heap_len &&
  21679. smaller(tree, s.heap[j+1], s.heap[j], s.depth)) {
  21680. j++;
  21681. }
  21682. /* Exit if v is smaller than both sons */
  21683. if (smaller(tree, v, s.heap[j], s.depth)) { break; }
  21684. /* Exchange v with the smallest son */
  21685. s.heap[k] = s.heap[j];
  21686. k = j;
  21687. /* And continue down the tree, setting j to the left son of k */
  21688. j <<= 1;
  21689. }
  21690. s.heap[k] = v;
  21691. }
  21692. // inlined manually
  21693. // var SMALLEST = 1;
  21694. /* ===========================================================================
  21695. * Send the block data compressed using the given Huffman trees
  21696. */
  21697. function compress_block(s, ltree, dtree)
  21698. // deflate_state *s;
  21699. // const ct_data *ltree; /* literal tree */
  21700. // const ct_data *dtree; /* distance tree */
  21701. {
  21702. var dist; /* distance of matched string */
  21703. var lc; /* match length or unmatched char (if dist == 0) */
  21704. var lx = 0; /* running index in l_buf */
  21705. var code; /* the code to send */
  21706. var extra; /* number of extra bits to send */
  21707. if (s.last_lit !== 0) {
  21708. do {
  21709. dist = (s.pending_buf[s.d_buf + lx*2] << 8) | (s.pending_buf[s.d_buf + lx*2 + 1]);
  21710. lc = s.pending_buf[s.l_buf + lx];
  21711. lx++;
  21712. if (dist === 0) {
  21713. send_code(s, lc, ltree); /* send a literal byte */
  21714. //Tracecv(isgraph(lc), (stderr," '%c' ", lc));
  21715. } else {
  21716. /* Here, lc is the match length - MIN_MATCH */
  21717. code = _length_code[lc];
  21718. send_code(s, code+LITERALS+1, ltree); /* send the length code */
  21719. extra = extra_lbits[code];
  21720. if (extra !== 0) {
  21721. lc -= base_length[code];
  21722. send_bits(s, lc, extra); /* send the extra length bits */
  21723. }
  21724. dist--; /* dist is now the match distance - 1 */
  21725. code = d_code(dist);
  21726. //Assert (code < D_CODES, "bad d_code");
  21727. send_code(s, code, dtree); /* send the distance code */
  21728. extra = extra_dbits[code];
  21729. if (extra !== 0) {
  21730. dist -= base_dist[code];
  21731. send_bits(s, dist, extra); /* send the extra distance bits */
  21732. }
  21733. } /* literal or match pair ? */
  21734. /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */
  21735. //Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx,
  21736. // "pendingBuf overflow");
  21737. } while (lx < s.last_lit);
  21738. }
  21739. send_code(s, END_BLOCK, ltree);
  21740. }
  21741. /* ===========================================================================
  21742. * Construct one Huffman tree and assigns the code bit strings and lengths.
  21743. * Update the total bit length for the current block.
  21744. * IN assertion: the field freq is set for all tree elements.
  21745. * OUT assertions: the fields len and code are set to the optimal bit length
  21746. * and corresponding code. The length opt_len is updated; static_len is
  21747. * also updated if stree is not null. The field max_code is set.
  21748. */
  21749. function build_tree(s, desc)
  21750. // deflate_state *s;
  21751. // tree_desc *desc; /* the tree descriptor */
  21752. {
  21753. var tree = desc.dyn_tree;
  21754. var stree = desc.stat_desc.static_tree;
  21755. var has_stree = desc.stat_desc.has_stree;
  21756. var elems = desc.stat_desc.elems;
  21757. var n, m; /* iterate over heap elements */
  21758. var max_code = -1; /* largest code with non zero frequency */
  21759. var node; /* new node being created */
  21760. /* Construct the initial heap, with least frequent element in
  21761. * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
  21762. * heap[0] is not used.
  21763. */
  21764. s.heap_len = 0;
  21765. s.heap_max = HEAP_SIZE;
  21766. for (n = 0; n < elems; n++) {
  21767. if (tree[n * 2]/*.Freq*/ !== 0) {
  21768. s.heap[++s.heap_len] = max_code = n;
  21769. s.depth[n] = 0;
  21770. } else {
  21771. tree[n*2 + 1]/*.Len*/ = 0;
  21772. }
  21773. }
  21774. /* The pkzip format requires that at least one distance code exists,
  21775. * and that at least one bit should be sent even if there is only one
  21776. * possible code. So to avoid special checks later on we force at least
  21777. * two codes of non zero frequency.
  21778. */
  21779. while (s.heap_len < 2) {
  21780. node = s.heap[++s.heap_len] = (max_code < 2 ? ++max_code : 0);
  21781. tree[node * 2]/*.Freq*/ = 1;
  21782. s.depth[node] = 0;
  21783. s.opt_len--;
  21784. if (has_stree) {
  21785. s.static_len -= stree[node*2 + 1]/*.Len*/;
  21786. }
  21787. /* node is 0 or 1 so it does not have extra bits */
  21788. }
  21789. desc.max_code = max_code;
  21790. /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
  21791. * establish sub-heaps of increasing lengths:
  21792. */
  21793. for (n = (s.heap_len >> 1/*int /2*/); n >= 1; n--) { pqdownheap(s, tree, n); }
  21794. /* Construct the Huffman tree by repeatedly combining the least two
  21795. * frequent nodes.
  21796. */
  21797. node = elems; /* next internal node of the tree */
  21798. do {
  21799. //pqremove(s, tree, n); /* n = node of least frequency */
  21800. /*** pqremove ***/
  21801. n = s.heap[1/*SMALLEST*/];
  21802. s.heap[1/*SMALLEST*/] = s.heap[s.heap_len--];
  21803. pqdownheap(s, tree, 1/*SMALLEST*/);
  21804. /***/
  21805. m = s.heap[1/*SMALLEST*/]; /* m = node of next least frequency */
  21806. s.heap[--s.heap_max] = n; /* keep the nodes sorted by frequency */
  21807. s.heap[--s.heap_max] = m;
  21808. /* Create a new node father of n and m */
  21809. tree[node * 2]/*.Freq*/ = tree[n * 2]/*.Freq*/ + tree[m * 2]/*.Freq*/;
  21810. s.depth[node] = (s.depth[n] >= s.depth[m] ? s.depth[n] : s.depth[m]) + 1;
  21811. tree[n*2 + 1]/*.Dad*/ = tree[m*2 + 1]/*.Dad*/ = node;
  21812. /* and insert the new node in the heap */
  21813. s.heap[1/*SMALLEST*/] = node++;
  21814. pqdownheap(s, tree, 1/*SMALLEST*/);
  21815. } while (s.heap_len >= 2);
  21816. s.heap[--s.heap_max] = s.heap[1/*SMALLEST*/];
  21817. /* At this point, the fields freq and dad are set. We can now
  21818. * generate the bit lengths.
  21819. */
  21820. gen_bitlen(s, desc);
  21821. /* The field len is now set, we can generate the bit codes */
  21822. gen_codes(tree, max_code, s.bl_count);
  21823. }
  21824. /* ===========================================================================
  21825. * Scan a literal or distance tree to determine the frequencies of the codes
  21826. * in the bit length tree.
  21827. */
  21828. function scan_tree(s, tree, max_code)
  21829. // deflate_state *s;
  21830. // ct_data *tree; /* the tree to be scanned */
  21831. // int max_code; /* and its largest code of non zero frequency */
  21832. {
  21833. var n; /* iterates over all tree elements */
  21834. var prevlen = -1; /* last emitted length */
  21835. var curlen; /* length of current code */
  21836. var nextlen = tree[0*2 + 1]/*.Len*/; /* length of next code */
  21837. var count = 0; /* repeat count of the current code */
  21838. var max_count = 7; /* max repeat count */
  21839. var min_count = 4; /* min repeat count */
  21840. if (nextlen === 0) {
  21841. max_count = 138;
  21842. min_count = 3;
  21843. }
  21844. tree[(max_code+1)*2 + 1]/*.Len*/ = 0xffff; /* guard */
  21845. for (n = 0; n <= max_code; n++) {
  21846. curlen = nextlen;
  21847. nextlen = tree[(n+1)*2 + 1]/*.Len*/;
  21848. if (++count < max_count && curlen === nextlen) {
  21849. continue;
  21850. } else if (count < min_count) {
  21851. s.bl_tree[curlen * 2]/*.Freq*/ += count;
  21852. } else if (curlen !== 0) {
  21853. if (curlen !== prevlen) { s.bl_tree[curlen * 2]/*.Freq*/++; }
  21854. s.bl_tree[REP_3_6*2]/*.Freq*/++;
  21855. } else if (count <= 10) {
  21856. s.bl_tree[REPZ_3_10*2]/*.Freq*/++;
  21857. } else {
  21858. s.bl_tree[REPZ_11_138*2]/*.Freq*/++;
  21859. }
  21860. count = 0;
  21861. prevlen = curlen;
  21862. if (nextlen === 0) {
  21863. max_count = 138;
  21864. min_count = 3;
  21865. } else if (curlen === nextlen) {
  21866. max_count = 6;
  21867. min_count = 3;
  21868. } else {
  21869. max_count = 7;
  21870. min_count = 4;
  21871. }
  21872. }
  21873. }
  21874. /* ===========================================================================
  21875. * Send a literal or distance tree in compressed form, using the codes in
  21876. * bl_tree.
  21877. */
  21878. function send_tree(s, tree, max_code)
  21879. // deflate_state *s;
  21880. // ct_data *tree; /* the tree to be scanned */
  21881. // int max_code; /* and its largest code of non zero frequency */
  21882. {
  21883. var n; /* iterates over all tree elements */
  21884. var prevlen = -1; /* last emitted length */
  21885. var curlen; /* length of current code */
  21886. var nextlen = tree[0*2 + 1]/*.Len*/; /* length of next code */
  21887. var count = 0; /* repeat count of the current code */
  21888. var max_count = 7; /* max repeat count */
  21889. var min_count = 4; /* min repeat count */
  21890. /* tree[max_code+1].Len = -1; */ /* guard already set */
  21891. if (nextlen === 0) {
  21892. max_count = 138;
  21893. min_count = 3;
  21894. }
  21895. for (n = 0; n <= max_code; n++) {
  21896. curlen = nextlen;
  21897. nextlen = tree[(n+1)*2 + 1]/*.Len*/;
  21898. if (++count < max_count && curlen === nextlen) {
  21899. continue;
  21900. } else if (count < min_count) {
  21901. do { send_code(s, curlen, s.bl_tree); } while (--count !== 0);
  21902. } else if (curlen !== 0) {
  21903. if (curlen !== prevlen) {
  21904. send_code(s, curlen, s.bl_tree);
  21905. count--;
  21906. }
  21907. //Assert(count >= 3 && count <= 6, " 3_6?");
  21908. send_code(s, REP_3_6, s.bl_tree);
  21909. send_bits(s, count-3, 2);
  21910. } else if (count <= 10) {
  21911. send_code(s, REPZ_3_10, s.bl_tree);
  21912. send_bits(s, count-3, 3);
  21913. } else {
  21914. send_code(s, REPZ_11_138, s.bl_tree);
  21915. send_bits(s, count-11, 7);
  21916. }
  21917. count = 0;
  21918. prevlen = curlen;
  21919. if (nextlen === 0) {
  21920. max_count = 138;
  21921. min_count = 3;
  21922. } else if (curlen === nextlen) {
  21923. max_count = 6;
  21924. min_count = 3;
  21925. } else {
  21926. max_count = 7;
  21927. min_count = 4;
  21928. }
  21929. }
  21930. }
  21931. /* ===========================================================================
  21932. * Construct the Huffman tree for the bit lengths and return the index in
  21933. * bl_order of the last bit length code to send.
  21934. */
  21935. function build_bl_tree(s) {
  21936. var max_blindex; /* index of last bit length code of non zero freq */
  21937. /* Determine the bit length frequencies for literal and distance trees */
  21938. scan_tree(s, s.dyn_ltree, s.l_desc.max_code);
  21939. scan_tree(s, s.dyn_dtree, s.d_desc.max_code);
  21940. /* Build the bit length tree: */
  21941. build_tree(s, s.bl_desc);
  21942. /* opt_len now includes the length of the tree representations, except
  21943. * the lengths of the bit lengths codes and the 5+5+4 bits for the counts.
  21944. */
  21945. /* Determine the number of bit length codes to send. The pkzip format
  21946. * requires that at least 4 bit length codes be sent. (appnote.txt says
  21947. * 3 but the actual value used is 4.)
  21948. */
  21949. for (max_blindex = BL_CODES-1; max_blindex >= 3; max_blindex--) {
  21950. if (s.bl_tree[bl_order[max_blindex]*2 + 1]/*.Len*/ !== 0) {
  21951. break;
  21952. }
  21953. }
  21954. /* Update opt_len to include the bit length tree and counts */
  21955. s.opt_len += 3*(max_blindex+1) + 5+5+4;
  21956. //Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld",
  21957. // s->opt_len, s->static_len));
  21958. return max_blindex;
  21959. }
  21960. /* ===========================================================================
  21961. * Send the header for a block using dynamic Huffman trees: the counts, the
  21962. * lengths of the bit length codes, the literal tree and the distance tree.
  21963. * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
  21964. */
  21965. function send_all_trees(s, lcodes, dcodes, blcodes)
  21966. // deflate_state *s;
  21967. // int lcodes, dcodes, blcodes; /* number of codes for each tree */
  21968. {
  21969. var rank; /* index in bl_order */
  21970. //Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes");
  21971. //Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,
  21972. // "too many codes");
  21973. //Tracev((stderr, "\nbl counts: "));
  21974. send_bits(s, lcodes-257, 5); /* not +255 as stated in appnote.txt */
  21975. send_bits(s, dcodes-1, 5);
  21976. send_bits(s, blcodes-4, 4); /* not -3 as stated in appnote.txt */
  21977. for (rank = 0; rank < blcodes; rank++) {
  21978. //Tracev((stderr, "\nbl code %2d ", bl_order[rank]));
  21979. send_bits(s, s.bl_tree[bl_order[rank]*2 + 1]/*.Len*/, 3);
  21980. }
  21981. //Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent));
  21982. send_tree(s, s.dyn_ltree, lcodes-1); /* literal tree */
  21983. //Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent));
  21984. send_tree(s, s.dyn_dtree, dcodes-1); /* distance tree */
  21985. //Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent));
  21986. }
  21987. /* ===========================================================================
  21988. * Check if the data type is TEXT or BINARY, using the following algorithm:
  21989. * - TEXT if the two conditions below are satisfied:
  21990. * a) There are no non-portable control characters belonging to the
  21991. * "black list" (0..6, 14..25, 28..31).
  21992. * b) There is at least one printable character belonging to the
  21993. * "white list" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255).
  21994. * - BINARY otherwise.
  21995. * - The following partially-portable control characters form a
  21996. * "gray list" that is ignored in this detection algorithm:
  21997. * (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}).
  21998. * IN assertion: the fields Freq of dyn_ltree are set.
  21999. */
  22000. function detect_data_type(s) {
  22001. /* black_mask is the bit mask of black-listed bytes
  22002. * set bits 0..6, 14..25, and 28..31
  22003. * 0xf3ffc07f = binary 11110011111111111100000001111111
  22004. */
  22005. var black_mask = 0xf3ffc07f;
  22006. var n;
  22007. /* Check for non-textual ("black-listed") bytes. */
  22008. for (n = 0; n <= 31; n++, black_mask >>>= 1) {
  22009. if ((black_mask & 1) && (s.dyn_ltree[n*2]/*.Freq*/ !== 0)) {
  22010. return Z_BINARY;
  22011. }
  22012. }
  22013. /* Check for textual ("white-listed") bytes. */
  22014. if (s.dyn_ltree[9 * 2]/*.Freq*/ !== 0 || s.dyn_ltree[10 * 2]/*.Freq*/ !== 0 ||
  22015. s.dyn_ltree[13 * 2]/*.Freq*/ !== 0) {
  22016. return Z_TEXT;
  22017. }
  22018. for (n = 32; n < LITERALS; n++) {
  22019. if (s.dyn_ltree[n * 2]/*.Freq*/ !== 0) {
  22020. return Z_TEXT;
  22021. }
  22022. }
  22023. /* There are no "black-listed" or "white-listed" bytes:
  22024. * this stream either is empty or has tolerated ("gray-listed") bytes only.
  22025. */
  22026. return Z_BINARY;
  22027. }
  22028. var static_init_done = false;
  22029. /* ===========================================================================
  22030. * Initialize the tree data structures for a new zlib stream.
  22031. */
  22032. function _tr_init(s)
  22033. {
  22034. if (!static_init_done) {
  22035. tr_static_init();
  22036. static_init_done = true;
  22037. }
  22038. s.l_desc = new TreeDesc(s.dyn_ltree, static_l_desc);
  22039. s.d_desc = new TreeDesc(s.dyn_dtree, static_d_desc);
  22040. s.bl_desc = new TreeDesc(s.bl_tree, static_bl_desc);
  22041. s.bi_buf = 0;
  22042. s.bi_valid = 0;
  22043. /* Initialize the first block of the first file: */
  22044. init_block(s);
  22045. }
  22046. /* ===========================================================================
  22047. * Send a stored block
  22048. */
  22049. function _tr_stored_block(s, buf, stored_len, last)
  22050. //DeflateState *s;
  22051. //charf *buf; /* input block */
  22052. //ulg stored_len; /* length of input block */
  22053. //int last; /* one if this is the last block for a file */
  22054. {
  22055. send_bits(s, (STORED_BLOCK<<1)+(last ? 1 : 0), 3); /* send block type */
  22056. copy_block(s, buf, stored_len, true); /* with header */
  22057. }
  22058. /* ===========================================================================
  22059. * Send one empty static block to give enough lookahead for inflate.
  22060. * This takes 10 bits, of which 7 may remain in the bit buffer.
  22061. */
  22062. function _tr_align(s) {
  22063. send_bits(s, STATIC_TREES<<1, 3);
  22064. send_code(s, END_BLOCK, static_ltree);
  22065. bi_flush(s);
  22066. }
  22067. /* ===========================================================================
  22068. * Determine the best encoding for the current block: dynamic trees, static
  22069. * trees or store, and output the encoded block to the zip file.
  22070. */
  22071. function _tr_flush_block(s, buf, stored_len, last)
  22072. //DeflateState *s;
  22073. //charf *buf; /* input block, or NULL if too old */
  22074. //ulg stored_len; /* length of input block */
  22075. //int last; /* one if this is the last block for a file */
  22076. {
  22077. var opt_lenb, static_lenb; /* opt_len and static_len in bytes */
  22078. var max_blindex = 0; /* index of last bit length code of non zero freq */
  22079. /* Build the Huffman trees unless a stored block is forced */
  22080. if (s.level > 0) {
  22081. /* Check if the file is binary or text */
  22082. if (s.strm.data_type === Z_UNKNOWN) {
  22083. s.strm.data_type = detect_data_type(s);
  22084. }
  22085. /* Construct the literal and distance trees */
  22086. build_tree(s, s.l_desc);
  22087. // Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len,
  22088. // s->static_len));
  22089. build_tree(s, s.d_desc);
  22090. // Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len,
  22091. // s->static_len));
  22092. /* At this point, opt_len and static_len are the total bit lengths of
  22093. * the compressed block data, excluding the tree representations.
  22094. */
  22095. /* Build the bit length tree for the above two trees, and get the index
  22096. * in bl_order of the last bit length code to send.
  22097. */
  22098. max_blindex = build_bl_tree(s);
  22099. /* Determine the best encoding. Compute the block lengths in bytes. */
  22100. opt_lenb = (s.opt_len+3+7) >>> 3;
  22101. static_lenb = (s.static_len+3+7) >>> 3;
  22102. // Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ",
  22103. // opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,
  22104. // s->last_lit));
  22105. if (static_lenb <= opt_lenb) { opt_lenb = static_lenb; }
  22106. } else {
  22107. // Assert(buf != (char*)0, "lost buf");
  22108. opt_lenb = static_lenb = stored_len + 5; /* force a stored block */
  22109. }
  22110. if ((stored_len+4 <= opt_lenb) && (buf !== -1)) {
  22111. /* 4: two words for the lengths */
  22112. /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
  22113. * Otherwise we can't have processed more than WSIZE input bytes since
  22114. * the last block flush, because compression would have been
  22115. * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
  22116. * transform a block into a stored block.
  22117. */
  22118. _tr_stored_block(s, buf, stored_len, last);
  22119. } else if (s.strategy === Z_FIXED || static_lenb === opt_lenb) {
  22120. send_bits(s, (STATIC_TREES<<1) + (last ? 1 : 0), 3);
  22121. compress_block(s, static_ltree, static_dtree);
  22122. } else {
  22123. send_bits(s, (DYN_TREES<<1) + (last ? 1 : 0), 3);
  22124. send_all_trees(s, s.l_desc.max_code+1, s.d_desc.max_code+1, max_blindex+1);
  22125. compress_block(s, s.dyn_ltree, s.dyn_dtree);
  22126. }
  22127. // Assert (s->compressed_len == s->bits_sent, "bad compressed size");
  22128. /* The above check is made mod 2^32, for files larger than 512 MB
  22129. * and uLong implemented on 32 bits.
  22130. */
  22131. init_block(s);
  22132. if (last) {
  22133. bi_windup(s);
  22134. }
  22135. // Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3,
  22136. // s->compressed_len-7*last));
  22137. }
  22138. /* ===========================================================================
  22139. * Save the match info and tally the frequency counts. Return true if
  22140. * the current block must be flushed.
  22141. */
  22142. function _tr_tally(s, dist, lc)
  22143. // deflate_state *s;
  22144. // unsigned dist; /* distance of matched string */
  22145. // unsigned lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */
  22146. {
  22147. //var out_length, in_length, dcode;
  22148. s.pending_buf[s.d_buf + s.last_lit * 2] = (dist >>> 8) & 0xff;
  22149. s.pending_buf[s.d_buf + s.last_lit * 2 + 1] = dist & 0xff;
  22150. s.pending_buf[s.l_buf + s.last_lit] = lc & 0xff;
  22151. s.last_lit++;
  22152. if (dist === 0) {
  22153. /* lc is the unmatched char */
  22154. s.dyn_ltree[lc*2]/*.Freq*/++;
  22155. } else {
  22156. s.matches++;
  22157. /* Here, lc is the match length - MIN_MATCH */
  22158. dist--; /* dist = match distance - 1 */
  22159. //Assert((ush)dist < (ush)MAX_DIST(s) &&
  22160. // (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&
  22161. // (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match");
  22162. s.dyn_ltree[(_length_code[lc]+LITERALS+1) * 2]/*.Freq*/++;
  22163. s.dyn_dtree[d_code(dist) * 2]/*.Freq*/++;
  22164. }
  22165. // (!) This block is disabled in zlib defailts,
  22166. // don't enable it for binary compatibility
  22167. //#ifdef TRUNCATE_BLOCK
  22168. // /* Try to guess if it is profitable to stop the current block here */
  22169. // if ((s.last_lit & 0x1fff) === 0 && s.level > 2) {
  22170. // /* Compute an upper bound for the compressed length */
  22171. // out_length = s.last_lit*8;
  22172. // in_length = s.strstart - s.block_start;
  22173. //
  22174. // for (dcode = 0; dcode < D_CODES; dcode++) {
  22175. // out_length += s.dyn_dtree[dcode*2]/*.Freq*/ * (5 + extra_dbits[dcode]);
  22176. // }
  22177. // out_length >>>= 3;
  22178. // //Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ",
  22179. // // s->last_lit, in_length, out_length,
  22180. // // 100L - out_length*100L/in_length));
  22181. // if (s.matches < (s.last_lit>>1)/*int /2*/ && out_length < (in_length>>1)/*int /2*/) {
  22182. // return true;
  22183. // }
  22184. // }
  22185. //#endif
  22186. return (s.last_lit === s.lit_bufsize-1);
  22187. /* We avoid equality with lit_bufsize because of wraparound at 64K
  22188. * on 16 bit machines and because stored blocks are restricted to
  22189. * 64K-1 bytes.
  22190. */
  22191. }
  22192. exports._tr_init = _tr_init;
  22193. exports._tr_stored_block = _tr_stored_block;
  22194. exports._tr_flush_block = _tr_flush_block;
  22195. exports._tr_tally = _tr_tally;
  22196. exports._tr_align = _tr_align;
  22197. },{"../utils/common":65}],77:[function(require,module,exports){
  22198. 'use strict';
  22199. function ZStream() {
  22200. /* next input byte */
  22201. this.input = null; // JS specific, because we have no pointers
  22202. this.next_in = 0;
  22203. /* number of bytes available at input */
  22204. this.avail_in = 0;
  22205. /* total number of input bytes read so far */
  22206. this.total_in = 0;
  22207. /* next output byte should be put there */
  22208. this.output = null; // JS specific, because we have no pointers
  22209. this.next_out = 0;
  22210. /* remaining free space at output */
  22211. this.avail_out = 0;
  22212. /* total number of bytes output so far */
  22213. this.total_out = 0;
  22214. /* last error message, NULL if no error */
  22215. this.msg = ''/*Z_NULL*/;
  22216. /* not visible by applications */
  22217. this.state = null;
  22218. /* best guess about the data type: binary or text */
  22219. this.data_type = 2/*Z_UNKNOWN*/;
  22220. /* adler32 value of the uncompressed data */
  22221. this.adler = 0;
  22222. }
  22223. module.exports = ZStream;
  22224. },{}],78:[function(require,module,exports){
  22225. module.exports = function arrayEquals(array) {
  22226. // if the other array is a falsy value, return
  22227. if (!array)
  22228. return false;
  22229. // compare lengths - can save a lot of time
  22230. if (this.length != array.length)
  22231. return false;
  22232. for (var i = 0, l = this.length; i < l; i++) {
  22233. // Check if we have nested arrays
  22234. if (this[i] instanceof Array && array[i] instanceof Array) {
  22235. // recurse into the nested arrays
  22236. if (!arrayEquals.apply(this[i], [array[i]]))
  22237. return false;
  22238. } else if (this[i] != array[i]) {
  22239. // Warning - two different object instances will never be equal:
  22240. // {x:20} != {x:20}
  22241. return false;
  22242. }
  22243. }
  22244. return true;
  22245. }
  22246. },{}],79:[function(require,module,exports){
  22247. exports.Interop = require('./interop');
  22248. },{"./interop":80}],80:[function(require,module,exports){
  22249. var transform = require('./transform');
  22250. var arrayEquals = require('./array-equals');
  22251. function Interop() { }
  22252. module.exports = Interop;
  22253. /**
  22254. * This map holds the most recent Plan A offer/answer SDP that was converted
  22255. * to Plan B, with the SDP type ('offer' or 'answer') as keys and the SDP
  22256. * string as values.
  22257. *
  22258. * @type {{}}
  22259. */
  22260. var cache = {};
  22261. /**
  22262. * This method transforms a Plan A SDP to an equivalent Plan B SDP. A
  22263. * PeerConnection wrapper transforms the SDP to Plan B before passing it to the
  22264. * application.
  22265. *
  22266. * @param desc
  22267. * @returns {*}
  22268. */
  22269. Interop.prototype.toPlanB = function(desc) {
  22270. //#region Preliminary input validation.
  22271. if (typeof desc !== 'object' || desc === null ||
  22272. typeof desc.sdp !== 'string') {
  22273. console.warn('An empty description was passed as an argument.');
  22274. return desc;
  22275. }
  22276. // Objectify the SDP for easier manipulation.
  22277. var session = transform.parse(desc.sdp);
  22278. // If the SDP contains no media, there's nothing to transform.
  22279. if (typeof session.media === 'undefined' ||
  22280. !Array.isArray(session.media) || session.media.length === 0) {
  22281. console.warn('The description has no media.');
  22282. return desc;
  22283. }
  22284. // Try some heuristics to "make sure" this is a Plan A SDP. Plan B SDP has
  22285. // a video, an audio and a data "channel" at most.
  22286. if (session.media.length <= 3 && session.media.every(function(m) {
  22287. return ['video', 'audio', 'data'].indexOf(m.mid) !== -1;
  22288. })) {
  22289. console.warn('This description does not look like Plan A.');
  22290. return desc;
  22291. }
  22292. //#endregion
  22293. // Plan A SDP is our "precious". Cache it for later use in the Plan B ->
  22294. // Plan A transformation.
  22295. cache[desc.type] = desc.sdp;
  22296. //#region Convert from Plan A to Plan B.
  22297. // We rebuild the session.media array.
  22298. var media = session.media;
  22299. session.media = [];
  22300. // Associative array that maps channel types to channel objects for fast
  22301. // access to channel objects by their type, e.g. channels['audio']->channel
  22302. // obj.
  22303. var channels = {};
  22304. // Used to build the group:BUNDLE value after the channels construction
  22305. // loop.
  22306. var types = [];
  22307. // Implode the Plan A m-lines/tracks into Plan B "channels".
  22308. media.forEach(function(mLine) {
  22309. // rtcp-mux is required in the Plan B SDP.
  22310. if (typeof mLine.rtcpMux !== 'string' ||
  22311. mLine.rtcpMux !== 'rtcp-mux') {
  22312. throw new Error('Cannot convert to Plan B because m-lines ' +
  22313. 'without the rtcp-mux attribute were found.');
  22314. }
  22315. // If we don't have a channel for this mLine.type, then use this mLine
  22316. // as the channel basis.
  22317. if (typeof channels[mLine.type] === 'undefined') {
  22318. channels[mLine.type] = mLine;
  22319. }
  22320. // Add sources to the channel and handle a=msid.
  22321. if (typeof mLine.sources === 'object') {
  22322. Object.keys(mLine.sources).forEach(function(ssrc) {
  22323. // Assign the sources to the channel.
  22324. channels[mLine.type].sources[ssrc] = mLine.sources[ssrc];
  22325. // In Plan B the msid is an SSRC attribute.
  22326. channels[mLine.type].sources[ssrc].msid = mLine.msid;
  22327. });
  22328. }
  22329. if (channels[mLine.type] === mLine) {
  22330. // Copy ICE related stuff from the principal media line.
  22331. mLine.candidates = media[0].candidates;
  22332. mLine.iceUfrag = media[0].iceUfrag;
  22333. mLine.icePwd = media[0].icePwd;
  22334. mLine.fingerprint = media[0].fingerprint;
  22335. // Plan B mids are in ['audio', 'video', 'data']
  22336. mLine.mid = mLine.type;
  22337. // Plan B doesn't support/need the bundle-only attribute.
  22338. delete mLine.bundleOnly;
  22339. // In Plan B the msid is an SSRC attribute.
  22340. delete mLine.msid;
  22341. // Used to build the group:BUNDLE value after this loop.
  22342. types.push(mLine.type);
  22343. // Add the channel to the new media array.
  22344. session.media.push(mLine);
  22345. }
  22346. // TODO(gp) add support for ssrc-group.
  22347. });
  22348. // We regenerate the BUNDLE group with the new mids.
  22349. session.groups.every(function(group) {
  22350. if (group.type === 'BUNDLE') {
  22351. group.mids = types.join(' ');
  22352. return false;
  22353. } else {
  22354. return true;
  22355. }
  22356. });
  22357. // msid semantic
  22358. session.msidSemantic = {
  22359. semantic: 'WMS',
  22360. token: '*'
  22361. };
  22362. var resStr = transform.write(session);
  22363. return new RTCSessionDescription({
  22364. type: desc.type,
  22365. sdp: resStr
  22366. });
  22367. //#endregion
  22368. };
  22369. /**
  22370. * This method transforms a Plan B SDP to an equivalent Plan A SDP. A
  22371. * PeerConnection wrapper transforms the SDP to Plan A before passing it to FF.
  22372. *
  22373. * @param desc
  22374. * @returns {*}
  22375. */
  22376. Interop.prototype.toPlanA = function(desc) {
  22377. //#region Preliminary input validation.
  22378. if (typeof desc !== 'object' || desc === null ||
  22379. typeof desc.sdp !== 'string') {
  22380. console.warn('An empty description was passed as an argument.');
  22381. return desc;
  22382. }
  22383. var session = transform.parse(desc.sdp);
  22384. // If the SDP contains no media, there's nothing to transform.
  22385. if (typeof session.media === 'undefined' ||
  22386. !Array.isArray(session.media) || session.media.length === 0) {
  22387. console.warn('The description has no media.');
  22388. return desc;
  22389. }
  22390. // Try some heuristics to "make sure" this is a Plan B SDP. Plan B SDP has
  22391. // a video, an audio and a data "channel" at most.
  22392. if (session.media.length > 3 || !session.media.every(function(m) {
  22393. return ['video', 'audio', 'data'].indexOf(m.mid) !== -1;
  22394. })) {
  22395. console.warn('This description does not look like Plan B.');
  22396. return desc;
  22397. }
  22398. // Make sure this Plan B SDP can be converted to a Plan A SDP.
  22399. var mids = [];
  22400. session.media.forEach(function(m) {
  22401. mids.push(m.mid);
  22402. });
  22403. var hasBundle = false;
  22404. if (typeof session.groups !== 'undefined' &&
  22405. Array.isArray(session.groups)) {
  22406. hasBundle = session.groups.every(function(g) {
  22407. return g.type !== 'BUNDLE' ||
  22408. arrayEquals.apply(g.mids.sort(), [mids.sort()]);
  22409. });
  22410. }
  22411. if (!hasBundle) {
  22412. throw new Error("Cannot convert to Plan A because m-lines that are " +
  22413. "not bundled were found.");
  22414. }
  22415. //#endregion
  22416. //#region Convert from Plan B to Plan A.
  22417. // Unfortunately, a Plan B offer/answer doesn't have enough information to
  22418. // rebuild an equivalent Plan A offer/answer.
  22419. //
  22420. // For example, if this is a local answer (in Plan A style) that we convert
  22421. // to Plan B prior to handing it over to the application (the
  22422. // PeerConnection wrapper called us, for instance, after a successful
  22423. // createAnswer), we want to remember the m-line at which we've seen the
  22424. // (local) SSRC. That's because when the application wants to do call the
  22425. // SLD method, forcing us to do the inverse transformation (from Plan B to
  22426. // Plan A), we need to know to which m-line to assign the (local) SSRC. We
  22427. // also need to know all the other m-lines that the original answer had and
  22428. // include them in the transformed answer as well.
  22429. //
  22430. // Another example is if this is a remote offer that we convert to Plan B
  22431. // prior to giving it to the application, we want to remember the mid at
  22432. // which we've seen the (remote) SSRC.
  22433. //
  22434. // In the iteration that follows, we use the cached Plan A (if it exists)
  22435. // to assign mids to ssrcs.
  22436. var cached;
  22437. if (typeof cache[desc.type] !== 'undefined') {
  22438. cached = transform.parse(cache[desc.type]);
  22439. }
  22440. // A helper map that sends mids to m-line objects. We use it later to
  22441. // rebuild the Plan A style session.media array.
  22442. var media = {};
  22443. session.media.forEach(function(channel) {
  22444. if (typeof channel.rtcpMux !== 'string' ||
  22445. channel.rtcpMux !== 'rtcp-mux') {
  22446. throw new Error("Cannot convert to Plan A because m-lines " +
  22447. "without the rtcp-mux attribute were found.");
  22448. }
  22449. // With rtcp-mux and bundle all the channels should have the same ICE
  22450. // stuff.
  22451. var sources = channel.sources;
  22452. var candidates = channel.candidates;
  22453. var iceUfrag = channel.iceUfrag;
  22454. var icePwd = channel.icePwd;
  22455. var fingerprint = channel.fingerprint;
  22456. var port = channel.port;
  22457. // We'll use the "channel" object as a prototype for each new "mLine"
  22458. // that we create, but first we need to clean it up a bit.
  22459. delete channel.sources;
  22460. delete channel.candidates;
  22461. delete channel.iceUfrag;
  22462. delete channel.icePwd;
  22463. delete channel.fingerprint;
  22464. delete channel.port;
  22465. delete channel.mid;
  22466. if (typeof sources === 'object') {
  22467. // Explode the Plan B channel sources with one m-line per source.
  22468. Object.keys(sources).forEach(function(ssrc) {
  22469. // Use the "channel" as a prototype for the "mLine".
  22470. var mLine = Object.create(channel);
  22471. // Assign the msid of the source to the m-line.
  22472. mLine.msid = sources[ssrc].msid;
  22473. delete sources[ssrc].msid;
  22474. // We assign one SSRC per media line.
  22475. mLine.sources = {};
  22476. mLine.sources[ssrc] = sources[ssrc];
  22477. // Use the cached Plan A SDP (if it exists) to assign SSRCs to
  22478. // mids.
  22479. if (typeof cached !== 'undefined' &&
  22480. typeof cached.media !== 'undefined' &&
  22481. Array.isArray(cached.media)) {
  22482. cached.media.forEach(function(m) {
  22483. if (typeof m.sources === 'object') {
  22484. Object.keys(m.sources).forEach(function(s) {
  22485. if (s === ssrc) {
  22486. mLine.mid = m.mid;
  22487. }
  22488. });
  22489. }
  22490. });
  22491. }
  22492. if (typeof mLine.mid === 'undefined') {
  22493. // If this is an SSRC that we see for the first time assign
  22494. // it a new mid. This is typically the case when this
  22495. // method is called to transform a remote description for
  22496. // the first time or when there is a new SSRC in the remote
  22497. // description because a new peer has joined the
  22498. // conference. Local SSRCs should have already been added
  22499. // to the map in the toPlanB method.
  22500. //
  22501. // Because FF generates answers in Plan A style, we MUST
  22502. // already have a cached answer with all the local SSRCs
  22503. // mapped to some mLine/mid.
  22504. if (desc.type === 'answer') {
  22505. throw new Error("An unmapped SSRC was found.");
  22506. }
  22507. mLine.mid = [channel.type, '-', ssrc].join('');
  22508. }
  22509. // Include the candidates in the 1st media line.
  22510. mLine.candidates = candidates;
  22511. mLine.iceUfrag = iceUfrag;
  22512. mLine.icePwd = icePwd;
  22513. mLine.fingerprint = fingerprint;
  22514. mLine.port = port;
  22515. media[mLine.mid] = mLine;
  22516. });
  22517. }
  22518. // TODO(gp) add support for ssrc-groups
  22519. });
  22520. // Rebuild the media array in the right order and add the missing mLines
  22521. // (missing from the Plan B SDP).
  22522. session.media = [];
  22523. mids = []; // reuse
  22524. if (desc.type === 'answer') {
  22525. // The media lines in the answer must match the media lines in the
  22526. // offer. The order is important too. Here we use the cached offer to
  22527. // find the m-lines that are missing (from the converted answer), and
  22528. // use the cached answer to complete the converted answer.
  22529. if (typeof cache['offer'] === 'undefined') {
  22530. throw new Error("An answer is being processed but we couldn't " +
  22531. "find a cached offer.");
  22532. }
  22533. var cachedOffer = transform.parse(cache['offer']);
  22534. if (typeof cachedOffer === 'undefined' ||
  22535. typeof cachedOffer.media === 'undefined' ||
  22536. !Array.isArray(cachedOffer.media)) {
  22537. // FIXME(gp) is this really a problem in the general case?
  22538. throw new Error("The cached offer has no media.");
  22539. }
  22540. cachedOffer.media.forEach(function(mo) {
  22541. var mLine;
  22542. if (typeof media[mo.mid] === 'undefined') {
  22543. // This is probably an m-line containing a remote track only.
  22544. // It MUST exist in the cached answer as a remote track only
  22545. // mLine.
  22546. cached.media.every(function(ma) {
  22547. if (mo.mid == ma.mid) {
  22548. mLine = ma;
  22549. return false;
  22550. } else {
  22551. return true;
  22552. }
  22553. });
  22554. } else {
  22555. mLine = media[mo.mid];
  22556. }
  22557. if (typeof mLine === 'undefined') {
  22558. throw new Error("The cached offer contains an m-line that " +
  22559. "doesn't exist neither in the cached answer nor in " +
  22560. "the converted answer.");
  22561. }
  22562. session.media.push(mLine);
  22563. mids.push(mLine.mid);
  22564. });
  22565. } else {
  22566. // Add all the m-lines that are in both the cached and the transformed
  22567. // SDP in the order of the cached SDP. We take the intersection because
  22568. // don't want to add m-lines from the cached SDP that have been removed
  22569. // from the transformed SDP.
  22570. if (typeof cached !== 'undefined' &&
  22571. typeof cached.media !== 'undefined' &&
  22572. Array.isArray(cached.media)) {
  22573. cached.media.forEach(function(pm) {
  22574. if (typeof media[pm.mid] !== 'undefined') {
  22575. mids.push(pm.mid);
  22576. session.media.push(media[pm.mid]);
  22577. }
  22578. });
  22579. }
  22580. // Add all the remaining (new) m-lines of the transformed SDP.
  22581. Object.keys(media).forEach(function(mid) {
  22582. if (mids.indexOf(mid) === -1) {
  22583. mids.push(mid);
  22584. session.media.push(media[mid]);
  22585. }
  22586. });
  22587. }
  22588. // We regenerate the BUNDLE group (since we regenerated the mids)
  22589. session.groups.every(function(group) {
  22590. if (group.type === 'BUNDLE') {
  22591. group.mids = mids.join(' ');
  22592. return false;
  22593. } else {
  22594. return true;
  22595. }
  22596. });
  22597. // msid semantic
  22598. session.msidSemantic = {
  22599. semantic: 'WMS',
  22600. token: '*'
  22601. };
  22602. var resStr = transform.write(session);
  22603. // Cache the transformed SDP (Plan A) for later re-use in this function.
  22604. cache[desc.type] = resStr;
  22605. return new RTCSessionDescription({
  22606. type: desc.type,
  22607. sdp: resStr
  22608. });
  22609. //#endregion
  22610. };
  22611. },{"./array-equals":78,"./transform":81}],81:[function(require,module,exports){
  22612. var transform = require('sdp-transform');
  22613. exports.write = function(session, opts) {
  22614. // expand sources to ssrcs
  22615. if (typeof session !== 'undefined' &&
  22616. typeof session.media !== 'undefined' &&
  22617. Array.isArray(session.media)) {
  22618. session.media.forEach(function (mLine) {
  22619. if (typeof mLine.sources !== 'undefined' &&
  22620. Object.keys(mLine.sources).length !== 0) {
  22621. mLine.ssrcs = [];
  22622. Object.keys(mLine.sources).forEach(function (ssrc) {
  22623. var source = mLine.sources[ssrc];
  22624. Object.keys(source).forEach(function (attribute) {
  22625. mLine.ssrcs.push({
  22626. id: ssrc,
  22627. attribute: attribute,
  22628. value: source[attribute]
  22629. });
  22630. });
  22631. });
  22632. delete mLine.sources;
  22633. }
  22634. });
  22635. }
  22636. // join group mids
  22637. if (typeof session !== 'undefined' &&
  22638. typeof session.groups !== 'undefined' && Array.isArray(session.groups)) {
  22639. session.groups.forEach(function (g) {
  22640. if (typeof g.mids !== 'undefined' && Array.isArray(g.mids)) {
  22641. g.mids = g.mids.join(' ');
  22642. }
  22643. });
  22644. }
  22645. return transform.write(session, opts);
  22646. };
  22647. exports.parse = function(sdp) {
  22648. var session = transform.parse(sdp);
  22649. if (typeof session !== 'undefined' && typeof session.media !== 'undefined' &&
  22650. Array.isArray(session.media)) {
  22651. // group sources attributes by ssrc
  22652. session.media.forEach(function (mLine) {
  22653. if (typeof mLine.ssrcs !== 'undefined' && Array.isArray(mLine.ssrcs)) {
  22654. mLine.sources = {};
  22655. mLine.ssrcs.forEach(function (ssrc) {
  22656. if (!mLine.sources[ssrc.id])
  22657. mLine.sources[ssrc.id] = {};
  22658. mLine.sources[ssrc.id][ssrc.attribute] = ssrc.value;
  22659. });
  22660. delete mLine.ssrcs;
  22661. }
  22662. });
  22663. }
  22664. // split group mids
  22665. if (typeof session !== 'undefined' &&
  22666. typeof session.groups !== 'undefined' && Array.isArray(session.groups)) {
  22667. session.groups.forEach(function (g) {
  22668. if (typeof g.mids === 'string') {
  22669. g.mids = g.mids.split(' ');
  22670. }
  22671. });
  22672. }
  22673. return session;
  22674. };
  22675. },{"sdp-transform":83}],82:[function(require,module,exports){
  22676. var grammar = module.exports = {
  22677. v: [{
  22678. name: 'version',
  22679. reg: /^(\d*)$/
  22680. }],
  22681. o: [{ //o=- 20518 0 IN IP4 203.0.113.1
  22682. // NB: sessionId will be a String in most cases because it is huge
  22683. name: 'origin',
  22684. reg: /^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/,
  22685. names: ['username', 'sessionId', 'sessionVersion', 'netType', 'ipVer', 'address'],
  22686. format: "%s %s %d %s IP%d %s"
  22687. }],
  22688. // default parsing of these only (though some of these feel outdated)
  22689. s: [{ name: 'name' }],
  22690. i: [{ name: 'description' }],
  22691. u: [{ name: 'uri' }],
  22692. e: [{ name: 'email' }],
  22693. p: [{ name: 'phone' }],
  22694. z: [{ name: 'timezones' }], // TODO: this one can actually be parsed properly..
  22695. r: [{ name: 'repeats' }], // TODO: this one can also be parsed properly
  22696. //k: [{}], // outdated thing ignored
  22697. t: [{ //t=0 0
  22698. name: 'timing',
  22699. reg: /^(\d*) (\d*)/,
  22700. names: ['start', 'stop'],
  22701. format: "%d %d"
  22702. }],
  22703. c: [{ //c=IN IP4 10.47.197.26
  22704. name: 'connection',
  22705. reg: /^IN IP(\d) (\S*)/,
  22706. names: ['version', 'ip'],
  22707. format: "IN IP%d %s"
  22708. }],
  22709. b: [{ //b=AS:4000
  22710. push: 'bandwidth',
  22711. reg: /^(TIAS|AS|CT|RR|RS):(\d*)/,
  22712. names: ['type', 'limit'],
  22713. format: "%s:%s"
  22714. }],
  22715. m: [{ //m=video 51744 RTP/AVP 126 97 98 34 31
  22716. // NB: special - pushes to session
  22717. // TODO: rtp/fmtp should be filtered by the payloads found here?
  22718. reg: /^(\w*) (\d*) ([\w\/]*)(?: (.*))?/,
  22719. names: ['type', 'port', 'protocol', 'payloads'],
  22720. format: "%s %d %s %s"
  22721. }],
  22722. a: [
  22723. { //a=rtpmap:110 opus/48000/2
  22724. push: 'rtp',
  22725. reg: /^rtpmap:(\d*) ([\w\-]*)\/(\d*)(?:\s*\/(\S*))?/,
  22726. names: ['payload', 'codec', 'rate', 'encoding'],
  22727. format: function (o) {
  22728. return (o.encoding) ?
  22729. "rtpmap:%d %s/%s/%s":
  22730. "rtpmap:%d %s/%s";
  22731. }
  22732. },
  22733. { //a=fmtp:108 profile-level-id=24;object=23;bitrate=64000
  22734. push: 'fmtp',
  22735. reg: /^fmtp:(\d*) (\S*)/,
  22736. names: ['payload', 'config'],
  22737. format: "fmtp:%d %s"
  22738. },
  22739. { //a=control:streamid=0
  22740. name: 'control',
  22741. reg: /^control:(.*)/,
  22742. format: "control:%s"
  22743. },
  22744. { //a=rtcp:65179 IN IP4 193.84.77.194
  22745. name: 'rtcp',
  22746. reg: /^rtcp:(\d*)(?: (\S*) IP(\d) (\S*))?/,
  22747. names: ['port', 'netType', 'ipVer', 'address'],
  22748. format: function (o) {
  22749. return (o.address != null) ?
  22750. "rtcp:%d %s IP%d %s":
  22751. "rtcp:%d";
  22752. }
  22753. },
  22754. { //a=rtcp-fb:98 trr-int 100
  22755. push: 'rtcpFbTrrInt',
  22756. reg: /^rtcp-fb:(\*|\d*) trr-int (\d*)/,
  22757. names: ['payload', 'value'],
  22758. format: "rtcp-fb:%d trr-int %d"
  22759. },
  22760. { //a=rtcp-fb:98 nack rpsi
  22761. push: 'rtcpFb',
  22762. reg: /^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,
  22763. names: ['payload', 'type', 'subtype'],
  22764. format: function (o) {
  22765. return (o.subtype != null) ?
  22766. "rtcp-fb:%s %s %s":
  22767. "rtcp-fb:%s %s";
  22768. }
  22769. },
  22770. { //a=extmap:2 urn:ietf:params:rtp-hdrext:toffset
  22771. //a=extmap:1/recvonly URI-gps-string
  22772. push: 'ext',
  22773. reg: /^extmap:([\w_\/]*) (\S*)(?: (\S*))?/,
  22774. names: ['value', 'uri', 'config'], // value may include "/direction" suffix
  22775. format: function (o) {
  22776. return (o.config != null) ?
  22777. "extmap:%s %s %s":
  22778. "extmap:%s %s";
  22779. }
  22780. },
  22781. {
  22782. //a=crypto:1 AES_CM_128_HMAC_SHA1_80 inline:PS1uQCVeeCFCanVmcjkpPywjNWhcYD0mXXtxaVBR|2^20|1:32
  22783. push: 'crypto',
  22784. reg: /^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,
  22785. names: ['id', 'suite', 'config', 'sessionConfig'],
  22786. format: function (o) {
  22787. return (o.sessionConfig != null) ?
  22788. "crypto:%d %s %s %s":
  22789. "crypto:%d %s %s";
  22790. }
  22791. },
  22792. { //a=setup:actpass
  22793. name: 'setup',
  22794. reg: /^setup:(\w*)/,
  22795. format: "setup:%s"
  22796. },
  22797. { //a=mid:1
  22798. name: 'mid',
  22799. reg: /^mid:([^\s]*)/,
  22800. format: "mid:%s"
  22801. },
  22802. { //a=msid:0c8b064d-d807-43b4-b434-f92a889d8587 98178685-d409-46e0-8e16-7ef0db0db64a
  22803. name: 'msid',
  22804. reg: /^msid:(.*)/,
  22805. format: "msid:%s"
  22806. },
  22807. { //a=ptime:20
  22808. name: 'ptime',
  22809. reg: /^ptime:(\d*)/,
  22810. format: "ptime:%d"
  22811. },
  22812. { //a=maxptime:60
  22813. name: 'maxptime',
  22814. reg: /^maxptime:(\d*)/,
  22815. format: "maxptime:%d"
  22816. },
  22817. { //a=sendrecv
  22818. name: 'direction',
  22819. reg: /^(sendrecv|recvonly|sendonly|inactive)/
  22820. },
  22821. { //a=ice-lite
  22822. name: 'icelite',
  22823. reg: /^(ice-lite)/
  22824. },
  22825. { //a=ice-ufrag:F7gI
  22826. name: 'iceUfrag',
  22827. reg: /^ice-ufrag:(\S*)/,
  22828. format: "ice-ufrag:%s"
  22829. },
  22830. { //a=ice-pwd:x9cml/YzichV2+XlhiMu8g
  22831. name: 'icePwd',
  22832. reg: /^ice-pwd:(\S*)/,
  22833. format: "ice-pwd:%s"
  22834. },
  22835. { //a=fingerprint:SHA-1 00:11:22:33:44:55:66:77:88:99:AA:BB:CC:DD:EE:FF:00:11:22:33
  22836. name: 'fingerprint',
  22837. reg: /^fingerprint:(\S*) (\S*)/,
  22838. names: ['type', 'hash'],
  22839. format: "fingerprint:%s %s"
  22840. },
  22841. {
  22842. //a=candidate:0 1 UDP 2113667327 203.0.113.1 54400 typ host
  22843. //a=candidate:1162875081 1 udp 2113937151 192.168.34.75 60017 typ host generation 0
  22844. //a=candidate:3289912957 2 udp 1845501695 193.84.77.194 60017 typ srflx raddr 192.168.34.75 rport 60017 generation 0
  22845. push:'candidates',
  22846. reg: /^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: generation (\d*))?/,
  22847. names: ['foundation', 'component', 'transport', 'priority', 'ip', 'port', 'type', 'raddr', 'rport', 'generation'],
  22848. format: function (o) {
  22849. var str = "candidate:%s %d %s %d %s %d typ %s";
  22850. // NB: candidate has two optional chunks, so %void middle one if it's missing
  22851. str += (o.raddr != null) ? " raddr %s rport %d" : "%v%v";
  22852. if (o.generation != null) {
  22853. str += " generation %d";
  22854. }
  22855. return str;
  22856. }
  22857. },
  22858. { //a=remote-candidates:1 203.0.113.1 54400 2 203.0.113.1 54401 ...
  22859. name: 'remoteCandidates',
  22860. reg: /^remote-candidates:(.*)/,
  22861. format: "remote-candidates:%s"
  22862. },
  22863. { //a=ice-options:google-ice
  22864. name: 'iceOptions',
  22865. reg: /^ice-options:(\S*)/,
  22866. format: "ice-options:%s"
  22867. },
  22868. { //a=ssrc:2566107569 cname:t9YU8M1UxTF8Y1A1
  22869. push: "ssrcs",
  22870. reg: /^ssrc:(\d*) ([\w_]*):(.*)/,
  22871. names: ['id', 'attribute', 'value'],
  22872. format: "ssrc:%d %s:%s"
  22873. },
  22874. { //a=msid-semantic: WMS Jvlam5X3SX1OP6pn20zWogvaKJz5Hjf9OnlV
  22875. name: "msidSemantic",
  22876. reg: /^msid-semantic:\s?(\w*) (\S*)/,
  22877. names: ['semantic', 'token'],
  22878. format: "msid-semantic: %s %s" // space after ":" is not accidental
  22879. },
  22880. { //a=group:BUNDLE audio video
  22881. push: 'groups',
  22882. reg: /^group:(\w*) (.*)/,
  22883. names: ['type', 'mids'],
  22884. format: "group:%s %s"
  22885. },
  22886. { //a=rtcp-mux
  22887. name: 'rtcpMux',
  22888. reg: /^(rtcp-mux)/
  22889. },
  22890. { // any a= that we don't understand is kepts verbatim on media.invalid
  22891. push: 'invalid',
  22892. names: ["value"]
  22893. }
  22894. ]
  22895. };
  22896. // set sensible defaults to avoid polluting the grammar with boring details
  22897. Object.keys(grammar).forEach(function (key) {
  22898. var objs = grammar[key];
  22899. objs.forEach(function (obj) {
  22900. if (!obj.reg) {
  22901. obj.reg = /(.*)/;
  22902. }
  22903. if (!obj.format) {
  22904. obj.format = "%s";
  22905. }
  22906. });
  22907. });
  22908. },{}],83:[function(require,module,exports){
  22909. var parser = require('./parser');
  22910. var writer = require('./writer');
  22911. exports.write = writer;
  22912. exports.parse = parser.parse;
  22913. exports.parseFmtpConfig = parser.parseFmtpConfig;
  22914. exports.parsePayloads = parser.parsePayloads;
  22915. exports.parseRemoteCandidates = parser.parseRemoteCandidates;
  22916. },{"./parser":84,"./writer":85}],84:[function(require,module,exports){
  22917. var toIntIfInt = function (v) {
  22918. return String(Number(v)) === v ? Number(v) : v;
  22919. };
  22920. var attachProperties = function (match, location, names, rawName) {
  22921. if (rawName && !names) {
  22922. location[rawName] = toIntIfInt(match[1]);
  22923. }
  22924. else {
  22925. for (var i = 0; i < names.length; i += 1) {
  22926. if (match[i+1] != null) {
  22927. location[names[i]] = toIntIfInt(match[i+1]);
  22928. }
  22929. }
  22930. }
  22931. };
  22932. var parseReg = function (obj, location, content) {
  22933. var needsBlank = obj.name && obj.names;
  22934. if (obj.push && !location[obj.push]) {
  22935. location[obj.push] = [];
  22936. }
  22937. else if (needsBlank && !location[obj.name]) {
  22938. location[obj.name] = {};
  22939. }
  22940. var keyLocation = obj.push ?
  22941. {} : // blank object that will be pushed
  22942. needsBlank ? location[obj.name] : location; // otherwise, named location or root
  22943. attachProperties(content.match(obj.reg), keyLocation, obj.names, obj.name);
  22944. if (obj.push) {
  22945. location[obj.push].push(keyLocation);
  22946. }
  22947. };
  22948. var grammar = require('./grammar');
  22949. var validLine = RegExp.prototype.test.bind(/^([a-z])=(.*)/);
  22950. exports.parse = function (sdp) {
  22951. var session = {}
  22952. , media = []
  22953. , location = session; // points at where properties go under (one of the above)
  22954. // parse lines we understand
  22955. sdp.split(/(\r\n|\r|\n)/).filter(validLine).forEach(function (l) {
  22956. var type = l[0];
  22957. var content = l.slice(2);
  22958. if (type === 'm') {
  22959. media.push({rtp: [], fmtp: []});
  22960. location = media[media.length-1]; // point at latest media line
  22961. }
  22962. for (var j = 0; j < (grammar[type] || []).length; j += 1) {
  22963. var obj = grammar[type][j];
  22964. if (obj.reg.test(content)) {
  22965. return parseReg(obj, location, content);
  22966. }
  22967. }
  22968. });
  22969. session.media = media; // link it up
  22970. return session;
  22971. };
  22972. var fmtpReducer = function (acc, expr) {
  22973. var s = expr.split('=');
  22974. if (s.length === 2) {
  22975. acc[s[0]] = toIntIfInt(s[1]);
  22976. }
  22977. return acc;
  22978. };
  22979. exports.parseFmtpConfig = function (str) {
  22980. return str.split(';').reduce(fmtpReducer, {});
  22981. };
  22982. exports.parsePayloads = function (str) {
  22983. return str.split(' ').map(Number);
  22984. };
  22985. exports.parseRemoteCandidates = function (str) {
  22986. var candidates = [];
  22987. var parts = str.split(' ').map(toIntIfInt);
  22988. for (var i = 0; i < parts.length; i += 3) {
  22989. candidates.push({
  22990. component: parts[i],
  22991. ip: parts[i + 1],
  22992. port: parts[i + 2]
  22993. });
  22994. }
  22995. return candidates;
  22996. };
  22997. },{"./grammar":82}],85:[function(require,module,exports){
  22998. var grammar = require('./grammar');
  22999. // customized util.format - discards excess arguments and can void middle ones
  23000. var formatRegExp = /%[sdv%]/g;
  23001. var format = function (formatStr) {
  23002. var i = 1;
  23003. var args = arguments;
  23004. var len = args.length;
  23005. return formatStr.replace(formatRegExp, function (x) {
  23006. if (i >= len) {
  23007. return x; // missing argument
  23008. }
  23009. var arg = args[i];
  23010. i += 1;
  23011. switch (x) {
  23012. case '%%':
  23013. return '%';
  23014. case '%s':
  23015. return String(arg);
  23016. case '%d':
  23017. return Number(arg);
  23018. case '%v':
  23019. return '';
  23020. }
  23021. });
  23022. // NB: we discard excess arguments - they are typically undefined from makeLine
  23023. };
  23024. var makeLine = function (type, obj, location) {
  23025. var str = obj.format instanceof Function ?
  23026. (obj.format(obj.push ? location : location[obj.name])) :
  23027. obj.format;
  23028. var args = [type + '=' + str];
  23029. if (obj.names) {
  23030. for (var i = 0; i < obj.names.length; i += 1) {
  23031. var n = obj.names[i];
  23032. if (obj.name) {
  23033. args.push(location[obj.name][n]);
  23034. }
  23035. else { // for mLine and push attributes
  23036. args.push(location[obj.names[i]]);
  23037. }
  23038. }
  23039. }
  23040. else {
  23041. args.push(location[obj.name]);
  23042. }
  23043. return format.apply(null, args);
  23044. };
  23045. // RFC specified order
  23046. // TODO: extend this with all the rest
  23047. var defaultOuterOrder = [
  23048. 'v', 'o', 's', 'i',
  23049. 'u', 'e', 'p', 'c',
  23050. 'b', 't', 'r', 'z', 'a'
  23051. ];
  23052. var defaultInnerOrder = ['i', 'c', 'b', 'a'];
  23053. module.exports = function (session, opts) {
  23054. opts = opts || {};
  23055. // ensure certain properties exist
  23056. if (session.version == null) {
  23057. session.version = 0; // "v=0" must be there (only defined version atm)
  23058. }
  23059. if (session.name == null) {
  23060. session.name = " "; // "s= " must be there if no meaningful name set
  23061. }
  23062. session.media.forEach(function (mLine) {
  23063. if (mLine.payloads == null) {
  23064. mLine.payloads = "";
  23065. }
  23066. });
  23067. var outerOrder = opts.outerOrder || defaultOuterOrder;
  23068. var innerOrder = opts.innerOrder || defaultInnerOrder;
  23069. var sdp = [];
  23070. // loop through outerOrder for matching properties on session
  23071. outerOrder.forEach(function (type) {
  23072. grammar[type].forEach(function (obj) {
  23073. if (obj.name in session && typeof session[obj.name] !== 'undefined') {
  23074. sdp.push(makeLine(type, obj, session));
  23075. }
  23076. else if (obj.push in session && typeof session[obj.push] !== 'undefined') {
  23077. session[obj.push].forEach(function (el) {
  23078. sdp.push(makeLine(type, obj, el));
  23079. });
  23080. }
  23081. });
  23082. });
  23083. // then for each media line, follow the innerOrder
  23084. session.media.forEach(function (mLine) {
  23085. sdp.push(makeLine('m', grammar.m[0], mLine));
  23086. innerOrder.forEach(function (type) {
  23087. grammar[type].forEach(function (obj) {
  23088. if (obj.name in mLine && typeof mLine[obj.name] !== 'undefined') {
  23089. sdp.push(makeLine(type, obj, mLine));
  23090. }
  23091. else if (obj.push in mLine && typeof mLine[obj.push] !== 'undefined') {
  23092. mLine[obj.push].forEach(function (el) {
  23093. sdp.push(makeLine(type, obj, el));
  23094. });
  23095. }
  23096. });
  23097. });
  23098. });
  23099. return sdp.join('\r\n') + '\r\n';
  23100. };
  23101. },{"./grammar":82}],86:[function(require,module,exports){
  23102. var MediaStreamType = {
  23103. VIDEO_TYPE: "Video",
  23104. AUDIO_TYPE: "Audio"
  23105. };
  23106. module.exports = MediaStreamType;
  23107. },{}],87:[function(require,module,exports){
  23108. var RTCBrowserType = {
  23109. RTC_BROWSER_CHROME: "rtc_browser.chrome",
  23110. RTC_BROWSER_FIREFOX: "rtc_browser.firefox"
  23111. };
  23112. module.exports = RTCBrowserType;
  23113. },{}],88:[function(require,module,exports){
  23114. var RTCEvents = {
  23115. LASTN_CHANGED: "rtc.lastn_changed",
  23116. DOMINANTSPEAKER_CHANGED: "rtc.dominantspeaker_changed",
  23117. LASTN_ENDPOINT_CHANGED: "rtc.lastn_endpoint_changed",
  23118. SIMULCAST_LAYER_CHANGED: "rtc.simulcast_layer_changed",
  23119. SIMULCAST_LAYER_CHANGING: "rtc.simulcast_layer_changing",
  23120. SIMULCAST_START: "rtc.simlcast_start",
  23121. SIMULCAST_STOP: "rtc.simlcast_stop"
  23122. };
  23123. module.exports = RTCEvents;
  23124. },{}],89:[function(require,module,exports){
  23125. var Resolutions = {
  23126. "1080": {
  23127. width: 1920,
  23128. height: 1080,
  23129. order: 7
  23130. },
  23131. "fullhd": {
  23132. width: 1920,
  23133. height: 1080,
  23134. order: 7
  23135. },
  23136. "720": {
  23137. width: 1280,
  23138. height: 720,
  23139. order: 6
  23140. },
  23141. "hd": {
  23142. width: 1280,
  23143. height: 720,
  23144. order: 6
  23145. },
  23146. "960": {
  23147. width: 960,
  23148. height: 720,
  23149. order: 5
  23150. },
  23151. "640": {
  23152. width: 640,
  23153. height: 480,
  23154. order: 4
  23155. },
  23156. "vga": {
  23157. width: 640,
  23158. height: 480,
  23159. order: 4
  23160. },
  23161. "360": {
  23162. width: 640,
  23163. height: 360,
  23164. order: 3
  23165. },
  23166. "320": {
  23167. width: 320,
  23168. height: 240,
  23169. order: 2
  23170. },
  23171. "180": {
  23172. width: 320,
  23173. height: 180,
  23174. order: 1
  23175. }
  23176. };
  23177. module.exports = Resolutions;
  23178. },{}],90:[function(require,module,exports){
  23179. var StreamEventTypes = {
  23180. EVENT_TYPE_LOCAL_CREATED: "stream.local_created",
  23181. EVENT_TYPE_LOCAL_CHANGED: "stream.local_changed",
  23182. EVENT_TYPE_LOCAL_ENDED: "stream.local_ended",
  23183. EVENT_TYPE_REMOTE_CREATED: "stream.remote_created",
  23184. EVENT_TYPE_REMOTE_ENDED: "stream.remote_ended"
  23185. };
  23186. module.exports = StreamEventTypes;
  23187. },{}],91:[function(require,module,exports){
  23188. var UIEvents = {
  23189. NICKNAME_CHANGED: "UI.nickname_changed",
  23190. SELECTED_ENDPOINT: "UI.selected_endpoint",
  23191. PINNED_ENDPOINT: "UI.pinned_endpoint"
  23192. };
  23193. module.exports = UIEvents;
  23194. },{}],92:[function(require,module,exports){
  23195. var AuthenticationEvents = {
  23196. /**
  23197. * Event callback arguments:
  23198. * function(authenticationEnabled, userIdentity)
  23199. * authenticationEnabled - indicates whether authentication has been enabled
  23200. * in this session
  23201. * userIdentity - if user has been logged in then it contains user name. If
  23202. * contains 'null' or 'undefined' then user is not logged in.
  23203. */
  23204. IDENTITY_UPDATED: "authentication.identity_updated"
  23205. };
  23206. module.exports = AuthenticationEvents;
  23207. },{}],93:[function(require,module,exports){
  23208. var CQEvents = {
  23209. LOCALSTATS_UPDATED: "cq.localstats_updated",
  23210. REMOTESTATS_UPDATED: "cq.remotestats_updated",
  23211. STOP: "cq.stop"
  23212. };
  23213. module.exports = CQEvents;
  23214. },{}],94:[function(require,module,exports){
  23215. var DesktopSharingEventTypes = {
  23216. INIT: "ds.init",
  23217. SWITCHING_DONE: "ds.switching_done",
  23218. NEW_STREAM_CREATED: "ds.new_stream_created"
  23219. };
  23220. module.exports = DesktopSharingEventTypes;
  23221. },{}],95:[function(require,module,exports){
  23222. module.exports = {
  23223. getLanguages : function () {
  23224. var languages = [];
  23225. for(var lang in this)
  23226. {
  23227. if(typeof this[lang] === "string")
  23228. languages.push(this[lang]);
  23229. }
  23230. return languages;
  23231. },
  23232. EN: "en",
  23233. BG: "bg",
  23234. DE: "de",
  23235. TR: "tr"
  23236. }
  23237. },{}],96:[function(require,module,exports){
  23238. var XMPPEvents = {
  23239. CONFERENCE_CERATED: "xmpp.conferenceCreated.jingle",
  23240. CALL_TERMINATED: "xmpp.callterminated.jingle",
  23241. CALL_INCOMING: "xmpp.callincoming.jingle",
  23242. DISPOSE_CONFERENCE: "xmpp.dispoce_confernce",
  23243. GRACEFUL_SHUTDOWN: "xmpp.graceful_shutdown",
  23244. KICKED: "xmpp.kicked",
  23245. BRIDGE_DOWN: "xmpp.bridge_down",
  23246. USER_ID_CHANGED: "xmpp.user_id_changed",
  23247. CHANGED_STREAMS: "xmpp.changed_streams",
  23248. MUC_JOINED: "xmpp.muc_joined",
  23249. MUC_ENTER: "xmpp.muc_enter",
  23250. MUC_ROLE_CHANGED: "xmpp.muc_role_changed",
  23251. MUC_LEFT: "xmpp.muc_left",
  23252. MUC_DESTROYED: "xmpp.muc_destroyed",
  23253. DISPLAY_NAME_CHANGED: "xmpp.display_name_changed",
  23254. REMOTE_STATS: "xmpp.remote_stats",
  23255. LOCALROLE_CHANGED: "xmpp.localrole_changed",
  23256. PRESENCE_STATUS: "xmpp.presence_status",
  23257. RESERVATION_ERROR: "xmpp.room_reservation_error",
  23258. SUBJECT_CHANGED: "xmpp.subject_changed",
  23259. MESSAGE_RECEIVED: "xmpp.message_received",
  23260. SENDING_CHAT_MESSAGE: "xmpp.sending_chat_message",
  23261. PASSWORD_REQUIRED: "xmpp.password_required",
  23262. AUTHENTICATION_REQUIRED: "xmpp.authentication_required",
  23263. CHAT_ERROR_RECEIVED: "xmpp.chat_error_received",
  23264. ETHERPAD: "xmpp.etherpad"
  23265. };
  23266. module.exports = XMPPEvents;
  23267. },{}],97:[function(require,module,exports){
  23268. // Copyright Joyent, Inc. and other Node contributors.
  23269. //
  23270. // Permission is hereby granted, free of charge, to any person obtaining a
  23271. // copy of this software and associated documentation files (the
  23272. // "Software"), to deal in the Software without restriction, including
  23273. // without limitation the rights to use, copy, modify, merge, publish,
  23274. // distribute, sublicense, and/or sell copies of the Software, and to permit
  23275. // persons to whom the Software is furnished to do so, subject to the
  23276. // following conditions:
  23277. //
  23278. // The above copyright notice and this permission notice shall be included
  23279. // in all copies or substantial portions of the Software.
  23280. //
  23281. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  23282. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  23283. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  23284. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  23285. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  23286. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  23287. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  23288. function EventEmitter() {
  23289. this._events = this._events || {};
  23290. this._maxListeners = this._maxListeners || undefined;
  23291. }
  23292. module.exports = EventEmitter;
  23293. // Backwards-compat with node 0.10.x
  23294. EventEmitter.EventEmitter = EventEmitter;
  23295. EventEmitter.prototype._events = undefined;
  23296. EventEmitter.prototype._maxListeners = undefined;
  23297. // By default EventEmitters will print a warning if more than 10 listeners are
  23298. // added to it. This is a useful default which helps finding memory leaks.
  23299. EventEmitter.defaultMaxListeners = 10;
  23300. // Obviously not all Emitters should be limited to 10. This function allows
  23301. // that to be increased. Set to zero for unlimited.
  23302. EventEmitter.prototype.setMaxListeners = function(n) {
  23303. if (!isNumber(n) || n < 0 || isNaN(n))
  23304. throw TypeError('n must be a positive number');
  23305. this._maxListeners = n;
  23306. return this;
  23307. };
  23308. EventEmitter.prototype.emit = function(type) {
  23309. var er, handler, len, args, i, listeners;
  23310. if (!this._events)
  23311. this._events = {};
  23312. // If there is no 'error' event listener then throw.
  23313. if (type === 'error') {
  23314. if (!this._events.error ||
  23315. (isObject(this._events.error) && !this._events.error.length)) {
  23316. er = arguments[1];
  23317. if (er instanceof Error) {
  23318. throw er; // Unhandled 'error' event
  23319. }
  23320. throw TypeError('Uncaught, unspecified "error" event.');
  23321. }
  23322. }
  23323. handler = this._events[type];
  23324. if (isUndefined(handler))
  23325. return false;
  23326. if (isFunction(handler)) {
  23327. switch (arguments.length) {
  23328. // fast cases
  23329. case 1:
  23330. handler.call(this);
  23331. break;
  23332. case 2:
  23333. handler.call(this, arguments[1]);
  23334. break;
  23335. case 3:
  23336. handler.call(this, arguments[1], arguments[2]);
  23337. break;
  23338. // slower
  23339. default:
  23340. len = arguments.length;
  23341. args = new Array(len - 1);
  23342. for (i = 1; i < len; i++)
  23343. args[i - 1] = arguments[i];
  23344. handler.apply(this, args);
  23345. }
  23346. } else if (isObject(handler)) {
  23347. len = arguments.length;
  23348. args = new Array(len - 1);
  23349. for (i = 1; i < len; i++)
  23350. args[i - 1] = arguments[i];
  23351. listeners = handler.slice();
  23352. len = listeners.length;
  23353. for (i = 0; i < len; i++)
  23354. listeners[i].apply(this, args);
  23355. }
  23356. return true;
  23357. };
  23358. EventEmitter.prototype.addListener = function(type, listener) {
  23359. var m;
  23360. if (!isFunction(listener))
  23361. throw TypeError('listener must be a function');
  23362. if (!this._events)
  23363. this._events = {};
  23364. // To avoid recursion in the case that type === "newListener"! Before
  23365. // adding it to the listeners, first emit "newListener".
  23366. if (this._events.newListener)
  23367. this.emit('newListener', type,
  23368. isFunction(listener.listener) ?
  23369. listener.listener : listener);
  23370. if (!this._events[type])
  23371. // Optimize the case of one listener. Don't need the extra array object.
  23372. this._events[type] = listener;
  23373. else if (isObject(this._events[type]))
  23374. // If we've already got an array, just append.
  23375. this._events[type].push(listener);
  23376. else
  23377. // Adding the second element, need to change to array.
  23378. this._events[type] = [this._events[type], listener];
  23379. // Check for listener leak
  23380. if (isObject(this._events[type]) && !this._events[type].warned) {
  23381. var m;
  23382. if (!isUndefined(this._maxListeners)) {
  23383. m = this._maxListeners;
  23384. } else {
  23385. m = EventEmitter.defaultMaxListeners;
  23386. }
  23387. if (m && m > 0 && this._events[type].length > m) {
  23388. this._events[type].warned = true;
  23389. console.error('(node) warning: possible EventEmitter memory ' +
  23390. 'leak detected. %d listeners added. ' +
  23391. 'Use emitter.setMaxListeners() to increase limit.',
  23392. this._events[type].length);
  23393. if (typeof console.trace === 'function') {
  23394. // not supported in IE 10
  23395. console.trace();
  23396. }
  23397. }
  23398. }
  23399. return this;
  23400. };
  23401. EventEmitter.prototype.on = EventEmitter.prototype.addListener;
  23402. EventEmitter.prototype.once = function(type, listener) {
  23403. if (!isFunction(listener))
  23404. throw TypeError('listener must be a function');
  23405. var fired = false;
  23406. function g() {
  23407. this.removeListener(type, g);
  23408. if (!fired) {
  23409. fired = true;
  23410. listener.apply(this, arguments);
  23411. }
  23412. }
  23413. g.listener = listener;
  23414. this.on(type, g);
  23415. return this;
  23416. };
  23417. // emits a 'removeListener' event iff the listener was removed
  23418. EventEmitter.prototype.removeListener = function(type, listener) {
  23419. var list, position, length, i;
  23420. if (!isFunction(listener))
  23421. throw TypeError('listener must be a function');
  23422. if (!this._events || !this._events[type])
  23423. return this;
  23424. list = this._events[type];
  23425. length = list.length;
  23426. position = -1;
  23427. if (list === listener ||
  23428. (isFunction(list.listener) && list.listener === listener)) {
  23429. delete this._events[type];
  23430. if (this._events.removeListener)
  23431. this.emit('removeListener', type, listener);
  23432. } else if (isObject(list)) {
  23433. for (i = length; i-- > 0;) {
  23434. if (list[i] === listener ||
  23435. (list[i].listener && list[i].listener === listener)) {
  23436. position = i;
  23437. break;
  23438. }
  23439. }
  23440. if (position < 0)
  23441. return this;
  23442. if (list.length === 1) {
  23443. list.length = 0;
  23444. delete this._events[type];
  23445. } else {
  23446. list.splice(position, 1);
  23447. }
  23448. if (this._events.removeListener)
  23449. this.emit('removeListener', type, listener);
  23450. }
  23451. return this;
  23452. };
  23453. EventEmitter.prototype.removeAllListeners = function(type) {
  23454. var key, listeners;
  23455. if (!this._events)
  23456. return this;
  23457. // not listening for removeListener, no need to emit
  23458. if (!this._events.removeListener) {
  23459. if (arguments.length === 0)
  23460. this._events = {};
  23461. else if (this._events[type])
  23462. delete this._events[type];
  23463. return this;
  23464. }
  23465. // emit removeListener for all listeners on all events
  23466. if (arguments.length === 0) {
  23467. for (key in this._events) {
  23468. if (key === 'removeListener') continue;
  23469. this.removeAllListeners(key);
  23470. }
  23471. this.removeAllListeners('removeListener');
  23472. this._events = {};
  23473. return this;
  23474. }
  23475. listeners = this._events[type];
  23476. if (isFunction(listeners)) {
  23477. this.removeListener(type, listeners);
  23478. } else {
  23479. // LIFO order
  23480. while (listeners.length)
  23481. this.removeListener(type, listeners[listeners.length - 1]);
  23482. }
  23483. delete this._events[type];
  23484. return this;
  23485. };
  23486. EventEmitter.prototype.listeners = function(type) {
  23487. var ret;
  23488. if (!this._events || !this._events[type])
  23489. ret = [];
  23490. else if (isFunction(this._events[type]))
  23491. ret = [this._events[type]];
  23492. else
  23493. ret = this._events[type].slice();
  23494. return ret;
  23495. };
  23496. EventEmitter.listenerCount = function(emitter, type) {
  23497. var ret;
  23498. if (!emitter._events || !emitter._events[type])
  23499. ret = 0;
  23500. else if (isFunction(emitter._events[type]))
  23501. ret = 1;
  23502. else
  23503. ret = emitter._events[type].length;
  23504. return ret;
  23505. };
  23506. function isFunction(arg) {
  23507. return typeof arg === 'function';
  23508. }
  23509. function isNumber(arg) {
  23510. return typeof arg === 'number';
  23511. }
  23512. function isObject(arg) {
  23513. return typeof arg === 'object' && arg !== null;
  23514. }
  23515. function isUndefined(arg) {
  23516. return arg === void 0;
  23517. }
  23518. },{}]},{},[1])(1)
  23519. });